feat: init repo
This commit is contained in:
66
backend/app/middlewares/m_wechat_auth.go
Normal file
66
backend/app/middlewares/m_wechat_auth.go
Normal file
@@ -0,0 +1,66 @@
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user