67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"kra/pkg/jwt"
|
|
|
|
khttp "github.com/go-kratos/kratos/v2/transport/http"
|
|
)
|
|
|
|
// claimsKey 用于context存储claims的key
|
|
type claimsKey struct{}
|
|
|
|
// GetAuthorityID 从Kratos HTTP Context获取用户角色ID
|
|
func GetAuthorityID(ctx khttp.Context) uint {
|
|
claims, ok := GetClaims(ctx)
|
|
if !ok {
|
|
return 0
|
|
}
|
|
return claims.AuthorityID
|
|
}
|
|
|
|
// GetUserID 从Kratos HTTP Context获取用户ID
|
|
func GetUserID(ctx khttp.Context) uint {
|
|
claims, ok := GetClaims(ctx)
|
|
if !ok {
|
|
return 0
|
|
}
|
|
return claims.BaseClaims.ID
|
|
}
|
|
|
|
// GetClaims 从Kratos HTTP Context获取JWT Claims
|
|
func GetClaims(ctx khttp.Context) (*jwt.CustomClaims, bool) {
|
|
// 尝试从request context获取
|
|
if claims, ok := ctx.Request().Context().Value(claimsKey{}).(*jwt.CustomClaims); ok {
|
|
return claims, true
|
|
}
|
|
// 尝试使用字符串key
|
|
if claims, ok := ctx.Request().Context().Value("claims").(*jwt.CustomClaims); ok {
|
|
return claims, true
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// GetToken 从Kratos HTTP Context获取Token
|
|
func GetToken(ctx khttp.Context) string {
|
|
// 从header获取
|
|
token := ctx.Request().Header.Get("x-token")
|
|
if token != "" {
|
|
return token
|
|
}
|
|
|
|
// 从cookie获取
|
|
if cookie, err := ctx.Request().Cookie("x-token"); err == nil {
|
|
return cookie.Value
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// GetUserUUID 从Kratos HTTP Context获取用户UUID
|
|
func GetUserUUID(ctx khttp.Context) string {
|
|
claims, ok := GetClaims(ctx)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return claims.UUID
|
|
}
|