47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"backend/providers/wechat"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/pkg/errors"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func (f *Middlewares) WeChatAuth(c fiber.Ctx) error {
|
|
log.WithField("module", "middleware.AuthUserInfo").Debugf("%s, query: %v", c.OriginalURL(), c.Queries())
|
|
state := c.Query("state")
|
|
code := c.Query("code")
|
|
log.WithField("module", "middleware.AuthUserInfo").Debugf("code: %s, state: %s", code, state)
|
|
|
|
if state == "" && code == "" {
|
|
url := string(c.Request().URI().FullURI())
|
|
if f.app.IsDevMode() && f.app.BaseURI != nil {
|
|
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("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())
|
|
|
|
}
|
|
|
|
if state != "sns_basic_auth" || code == "" {
|
|
return errors.New("invalid request")
|
|
}
|
|
|
|
return c.Next()
|
|
}
|