55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
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("/")
|
|
}
|