mirror of https://github.com/veypi/OneAuth.git
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
// Copyright (C) 2024 veypi <i@veypi.com>
|
|
// 2025-03-04 16:08:06
|
|
// Distributed under terms of the MIT license.
|
|
|
|
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/veypi/vbase/libs/cache"
|
|
"github.com/veypi/vbase/libs/jwt"
|
|
"github.com/veypi/vigo"
|
|
)
|
|
|
|
// AuthRequired JWT认证中间件
|
|
func AuthRequired() func(*vigo.X) error {
|
|
return func(x *vigo.X) error {
|
|
tokenString := extractToken(x)
|
|
if tokenString == "" {
|
|
return vigo.ErrNotAuthorized.WithString("missing token")
|
|
}
|
|
|
|
// 解析token
|
|
claims, err := jwt.ParseToken(tokenString)
|
|
if err != nil {
|
|
if err == jwt.ErrExpiredToken {
|
|
return vigo.ErrNotAuthorized.WithString("token expired")
|
|
}
|
|
return vigo.ErrNotAuthorized.WithString("invalid token")
|
|
}
|
|
|
|
// 检查token是否在黑名单中
|
|
if cache.IsEnabled() {
|
|
blacklisted, _ := cache.IsTokenBlacklisted(claims.ID)
|
|
if blacklisted {
|
|
return vigo.ErrNotAuthorized.WithString("token has been revoked")
|
|
}
|
|
}
|
|
|
|
// 将用户信息存入上下文
|
|
x.Set("user_id", claims.UserID)
|
|
x.Set("user_name", claims.Username)
|
|
x.Set("user_orgs", claims.Orgs)
|
|
x.Set("token_claims", claims)
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func extractToken(x *vigo.X) string {
|
|
auth := x.Request.Header.Get("Authorization")
|
|
if auth != "" {
|
|
if len(auth) > 7 && strings.HasPrefix(auth, "Bearer ") {
|
|
return auth[7:]
|
|
}
|
|
}
|
|
return x.Request.URL.Query().Get("access_token")
|
|
}
|