From 0dda8560d2d1018bb3c0f1dbcc31128b81913d96 Mon Sep 17 00:00:00 2001 From: NoahLan <6995syu@163.com> Date: Tue, 17 Oct 2023 11:36:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20jwt=E6=B7=BB=E5=8A=A0roles=E6=B3=A8?= =?UTF-8?q?=E5=85=A5=E5=92=8C=E8=8E=B7=E5=8F=96=E5=BD=93=E5=89=8D=E7=94=A8?= =?UTF-8?q?=E6=88=B7roles=E7=9A=84=E6=96=B9=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/jwt/jwt.go | 6 ++++++ core/jwt/util.go | 9 +++++++++ 2 files changed, 15 insertions(+) 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{} +}