u
This commit is contained in:
1 parent
f08db1959b
commit
c6671c8a8c
68 files changed
+13904
-1131
No files matched your search
@@ -0,0 +1,47 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"allapp-go/internal/httpx"
|
||||
"allapp-go/pkg/jwtx"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
const CtxUserIDKey = "user_id"
|
||||
|
||||
// Auth 登录校验中间件
|
||||
func Auth() fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
token := strings.TrimSpace(c.Get("Token"))
|
||||
|
||||
if token == "" {
|
||||
return httpx.Unauthorized(c, "未登录")
|
||||
}
|
||||
|
||||
verifyToken, ok := jwtx.VerifyToken(c.Context(), token)
|
||||
if !ok {
|
||||
return httpx.Unauthorized(c, "登录已过期")
|
||||
}
|
||||
|
||||
c.Locals(CtxUserIDKey, verifyToken.Data["user_id"])
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserID(c fiber.Ctx) (int64, error) {
|
||||
v := c.Locals(CtxUserIDKey)
|
||||
|
||||
if v == nil {
|
||||
return 0, httpx.Unauthorized(c, "登录已过期")
|
||||
}
|
||||
|
||||
userID, ok := v.(int64)
|
||||
|
||||
if !ok {
|
||||
return 0, httpx.Unauthorized(c, "登录已过期")
|
||||
}
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
Reference in new issue
Block a user