43 lines
1.2 KiB
Go
43 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) WeChatSilentAuth(c fiber.Ctx) error {
|
|
log.WithField("module", "middleware.WeChatSilentAuth").Debug("Begin")
|
|
defer log.WithField("module", "middleware.WeChatSilentAuth").Debug("END")
|
|
|
|
// if cookie not exists key "openid", then redirect to the wechat auth page
|
|
token := c.GetReqHeaders()["Authorization"]
|
|
if len(token) != 0 {
|
|
return c.Next()
|
|
}
|
|
|
|
// get current full url
|
|
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())
|
|
}
|