feat: jwt添加roles注入和获取当前用户roles的方法。

main v1.2.7
NoahLan 1 year ago
parent 6d2a60e3fa
commit 0dda8560d2

@ -1,7 +1,9 @@
package jwt package jwt
import ( import (
"git.noahlan.cn/noahlan/ntool/ndef"
"git.noahlan.cn/noahlan/ntool/nrandom" "git.noahlan.cn/noahlan/ntool/nrandom"
"git.noahlan.cn/noahlan/ntool/nstr"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"strconv" "strconv"
"time" "time"
@ -28,6 +30,10 @@ func WithOption(key string, val any) Option {
return Option{key, val} return Option{key, val}
} }
func WithRoles(codes []string) Option {
return WithOption(KeyRoles, nstr.JoinAny(ndef.CommaStr, codes))
}
func WithID(id string) Option { func WithID(id string) Option {
return WithOption("jti", id) return WithOption("jti", id)
} }

@ -3,7 +3,9 @@ package jwt
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"git.noahlan.cn/noahlan/ntool/ndef"
"git.noahlan.cn/noahlan/ntool/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"git.noahlan.cn/noahlan/ntool/nstr"
) )
// GetCurrentUserId 获取当前用户ID // GetCurrentUserId 获取当前用户ID
@ -20,3 +22,10 @@ func GetCurrentUserId(ctx context.Context) int64 {
} }
return uid return uid
} }
func GetCurrentRoles(ctx context.Context) []string {
if roleStr, ok := ctx.Value(KeyRoles).(string); ok {
return nstr.Split(roleStr, ndef.CommaStr)
}
return []string{}
}

Loading…
Cancel
Save