Files
workspace/code/allapp/allapp-go-v3/internal/middleware/auth.go
T
2026-04-21 22:12:34 +08:00

45 lines
828 B
Go

package middleware
import (
"allapp-go/internal/httpx"
"allapp-go/pkg/jwtx"
"context"
"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, "登录已过期")
}
ctx := context.WithValue(c.Context(), CtxUserIDKey, verifyToken.Data.UserID)
//ctx := context.WithValue(c.Context(), CtxUserIDKey, int64(796541901389893))
c.SetContext(ctx)
return c.Next()
}
}
func GetUserID(ctx context.Context) (int64, bool) {
v := ctx.Value(CtxUserIDKey)
id, ok := v.(int64)
return id, ok
}