feat: add middlewares
This commit is contained in:
54
backend/modules/middlewares/mid_auth_userinfo.go
Normal file
54
backend/modules/middlewares/mid_auth_userinfo.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"backend/pkg/pg"
|
||||
"backend/providers/jwt"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/pkg/errors"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (f *Middlewares) 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")
|
||||
}
|
||||
|
||||
var oauthInfo pg.UserOAuth
|
||||
copier.Copy(&oauthInfo, token)
|
||||
user, err := f.userSvc.GetOrNew(c.Context(), 1, token.Openid, oauthInfo)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get user")
|
||||
}
|
||||
|
||||
claim := f.jwt.CreateClaims(jwt.BaseClaims{UID: uint64(user.ID)})
|
||||
claim.ID = user.OpenID
|
||||
jwtToken, err := f.jwt.CreateToken(claim)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create token")
|
||||
}
|
||||
|
||||
// set the openid to the cookie
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "token",
|
||||
Value: jwtToken,
|
||||
HTTPOnly: true,
|
||||
})
|
||||
|
||||
return c.Redirect().To("/")
|
||||
}
|
||||
Reference in New Issue
Block a user