fix: wechat verify

This commit is contained in:
Rogee
2025-01-10 19:44:24 +08:00
parent ab576706e7
commit 52c17b63bb
13 changed files with 83 additions and 92 deletions

View File

@@ -7,10 +7,14 @@ import (
)
func (m *Middlewares) CheckUA(ctx fiber.Ctx) error {
if m.app.IsDevMode() {
return ctx.Next()
}
keyword := strings.ToLower("MicroMessenger")
userAgent := ctx.GetReqHeaders()["User-Agent"][0]
if strings.Contains(userAgent, keyword) {
if !strings.Contains(userAgent, keyword) {
return ctx.SendString("")
}
return ctx.Next()

View File

@@ -1,37 +1,27 @@
package middlewares
import (
"time"
"backend/app/consts"
"backend/app/errorx"
"github.com/gofiber/fiber/v3"
log "github.com/sirupsen/logrus"
)
func (f *Middlewares) ParseJWT(c fiber.Ctx) error {
tokens := c.GetReqHeaders()["Authorization"]
if len(tokens) == 0 {
queryToken := c.Query("token")
tokens = []string{queryToken}
if len(tokens) == 0 {
token := c.Cookies(consts.TokenTypeUser.String())
if token == "" {
token = c.Query("token")
if token == "" {
return c.Next()
}
}
token := tokens[0]
claim, err := f.jwt.Parse(token)
if err != nil {
c.Cookie(&fiber.Cookie{
Name: "token",
Value: "",
Expires: time.Now().Add(-1 * time.Hour),
HTTPOnly: true,
})
log.Errorf("failed to parse jwt from token: %s", token)
c.ClearCookie(consts.TokenTypeUser.String())
return errorx.Unauthorized
}
_ = claim
c.Locals("claim", claim)
return c.Next()
}

View File

@@ -1,66 +0,0 @@
package middlewares
import (
"fmt"
"strings"
"time"
"backend/providers/wechat"
"github.com/gofiber/fiber/v3"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const StatePrefix = "sns_basic_auth"
func (f *Middlewares) WeChatAuth(c fiber.Ctx) error {
log := log.WithField("module", "middleware.AuthUserInfo")
log.Debugf("%s, query: %v", c.OriginalURL(), c.Queries())
state := c.Query("state")
code := c.Query("code")
log.Debugf("code: %s, state: %s", code, state)
jwtToken := c.Cookies("token")
if jwtToken != "" {
log.Debugf("jwtToken: %s", jwtToken)
if _, err := f.jwt.Parse(jwtToken); err != nil {
log.WithError(err).Error("failed to parse jwt token")
c.Cookie(&fiber.Cookie{
Name: "token",
Value: "",
Expires: time.Now().Add(-1 * time.Hour),
HTTPOnly: true,
})
return c.Redirect().To(c.Path())
}
}
if state == "" && code == "" {
url := string(c.Request().URI().FullURI())
url = strings.ReplaceAll(url, "http", "https")
url = strings.ReplaceAll(url, c.BaseURL(), *f.app.BaseURI)
log.WithField("module", "middleware.SilentAuth").Debug("redirect_uri: ", url)
to, err := f.client.ScopeAuthorizeURL(
wechat.ScopeAuthorizeURLWithRedirectURI(url),
wechat.ScopeAuthorizeURLWithState(fmt.Sprintf("%s_%d", StatePrefix, time.Now().UnixNano())),
)
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())
}
if !strings.HasPrefix(state, StatePrefix) || code == "" {
return errors.New("invalid request")
}
return c.Next()
}