diff --git a/core/jwt/jwt.go b/core/jwt/jwt.go index 6890189..eee3186 100644 --- a/core/jwt/jwt.go +++ b/core/jwt/jwt.go @@ -1,7 +1,9 @@ package jwt import ( + "git.noahlan.cn/noahlan/ntool/ndef" "git.noahlan.cn/noahlan/ntool/nrandom" + "git.noahlan.cn/noahlan/ntool/nstr" "github.com/golang-jwt/jwt/v5" "strconv" "time" @@ -28,6 +30,10 @@ func WithOption(key string, val any) Option { return Option{key, val} } +func WithRoles(codes []string) Option { + return WithOption(KeyRoles, nstr.JoinAny(ndef.CommaStr, codes)) +} + func WithID(id string) Option { return WithOption("jti", id) } diff --git a/core/jwt/util.go b/core/jwt/util.go index 099ce83..7c282d8 100644 --- a/core/jwt/util.go +++ b/core/jwt/util.go @@ -3,7 +3,9 @@ package jwt import ( "context" "encoding/json" + "git.noahlan.cn/noahlan/ntool/ndef" "git.noahlan.cn/noahlan/ntool/nlog" + "git.noahlan.cn/noahlan/ntool/nstr" ) // GetCurrentUserId 获取当前用户ID @@ -20,3 +22,10 @@ func GetCurrentUserId(ctx context.Context) int64 { } return uid } + +func GetCurrentRoles(ctx context.Context) []string { + if roleStr, ok := ctx.Value(KeyRoles).(string); ok { + return nstr.Split(roleStr, ndef.CommaStr) + } + return []string{} +}