101 lines
2.2 KiB
Go
101 lines
2.2 KiB
Go
package fiberv3
|
|
|
|
import (
|
|
"git.ipao.vip/rogeecn/mp-qvyun/pkg/wechat"
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/pkg/errors"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type fiberMiddlewares struct {
|
|
client *wechat.Client
|
|
}
|
|
|
|
func Init(client *wechat.Client) *fiberMiddlewares {
|
|
return &fiberMiddlewares{
|
|
client: client,
|
|
}
|
|
}
|
|
|
|
func (f *fiberMiddlewares) Verify(c fiber.Ctx) error {
|
|
// get the query parameters
|
|
signature := c.Query("signature")
|
|
timestamp := c.Query("timestamp")
|
|
nonce := c.Query("nonce")
|
|
echostr := c.Query("echostr")
|
|
|
|
if signature == "" || timestamp == "" || nonce == "" || echostr == "" {
|
|
return c.Next()
|
|
}
|
|
|
|
log.Infof(
|
|
"begin verify signature, signature: %s, timestamp: %s, nonce: %s, echostr: %s",
|
|
signature,
|
|
timestamp,
|
|
nonce,
|
|
echostr,
|
|
)
|
|
|
|
// verify the signature
|
|
if err := f.client.Verify(signature, timestamp, nonce); err != nil {
|
|
return c.SendString(err.Error())
|
|
}
|
|
|
|
return c.SendString(echostr)
|
|
}
|
|
|
|
func (f *fiberMiddlewares) SilentAuth(c fiber.Ctx) error {
|
|
// if cookie not exists key "openid", then redirect to the wechat auth page
|
|
sid := c.Cookies("sid", "")
|
|
if sid != "" {
|
|
// TODO: verify sid
|
|
return c.Next()
|
|
}
|
|
|
|
// get current full url
|
|
url := c.BaseURL()
|
|
url = "https://qvyun.mp.jdwan.com"
|
|
log.WithField("module", "middleware.SilentAuth").Debug("url:", url)
|
|
|
|
to, err := f.client.ScopeAuthorizeURL(
|
|
wechat.ScopeAuthorizeURLWithRedirectURI(url),
|
|
wechat.ScopeAuthorizeURLWithState("sns_basic_auth"),
|
|
)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to get wechat auth url")
|
|
}
|
|
log.WithField("module", "middleware.SilentAuth").Debug("redirectTo: ", to.String())
|
|
|
|
return c.Redirect().To(to.String())
|
|
}
|
|
|
|
func (f *fiberMiddlewares) AuthUserInfo(c fiber.Ctx) error {
|
|
state := c.Query("state")
|
|
code := c.Query("code")
|
|
|
|
if state == "" && code == "" {
|
|
return c.Next()
|
|
}
|
|
|
|
if state != "sns_basic_auth" {
|
|
return c.Next()
|
|
}
|
|
log.WithField("module", "middleware.AuthUserInfo").Debug("code", code)
|
|
|
|
// get the openid
|
|
token, err := f.client.AuthorizeCode2Token(code)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to get openid")
|
|
}
|
|
// TODO: store the openid to the session
|
|
|
|
// set the openid to the cookie
|
|
c.Cookie(&fiber.Cookie{
|
|
Name: "sid",
|
|
Value: token.Openid,
|
|
HTTPOnly: true,
|
|
})
|
|
|
|
return c.Redirect().To("/")
|
|
}
|