feat: complete login
This commit is contained in:
57
backend/app/middlewares/mid_auth.go
Normal file
57
backend/app/middlewares/mid_auth.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"quyun/app/models"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/log"
|
||||
)
|
||||
|
||||
func (f *Middlewares) Auth(ctx fiber.Ctx) error {
|
||||
if strings.HasPrefix(ctx.Path(), "/admin/") {
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
if strings.HasPrefix(ctx.Path(), "/auth/") {
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
fullUrl := string(ctx.Request().URI().FullURI())
|
||||
u, err := url.Parse(fullUrl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query := u.Query()
|
||||
query.Set("redirect", fullUrl)
|
||||
u.RawQuery = query.Encode()
|
||||
u.Path = "/auth/wechat"
|
||||
fullUrl = u.String()
|
||||
|
||||
// check cookie exists
|
||||
cookie := ctx.Cookies("token")
|
||||
log.Infof("cookie: %s", cookie)
|
||||
if cookie == "" {
|
||||
log.Infof("auth redirect_uri: %s", fullUrl)
|
||||
return ctx.Redirect().To(fullUrl)
|
||||
}
|
||||
|
||||
jwt, err := f.jwt.Parse(cookie)
|
||||
if err != nil {
|
||||
// remove cookie
|
||||
ctx.ClearCookie("token")
|
||||
return ctx.Redirect().To(fullUrl)
|
||||
}
|
||||
|
||||
user, err := models.Users.GetByID(ctx.Context(), jwt.UserID)
|
||||
if err != nil {
|
||||
// remove cookie
|
||||
ctx.ClearCookie("token")
|
||||
return ctx.Redirect().To(fullUrl)
|
||||
}
|
||||
ctx.Locals("user", user)
|
||||
|
||||
return ctx.Next()
|
||||
}
|
||||
Reference in New Issue
Block a user