Skip to content

Commit

Permalink
[LanceAdd]简化权限校验
Browse files Browse the repository at this point in the history
  • Loading branch information
shanyujie committed Sep 20, 2024
1 parent aeb76af commit eac2904
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 123 deletions.
92 changes: 26 additions & 66 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package auth

import (
"context"
"errors"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/util/gutil"
"strings"
)

Expand Down Expand Up @@ -43,99 +41,61 @@ func doTokenRequired(r *ghttp.Request) error {
return gerror.NewCode(UrlPrefixError)
}
cacheMode := GetCacheMode()
currentUser := doVerifyToken(r.GetCtx(), token, cacheMode)
if currentUser == nil {
currentUserId := doVerifyToken(r.GetCtx(), token, cacheMode)
if currentUserId == 0 {
return gerror.NewCode(IllegalTokensError)
}
r.SetCtxVar(CtxUserId, currentUser.UserId)
r.SetCtxVar(CtxUserId, currentUserId)
return nil
}

func doVerifyToken(ctx context.Context, token string, mode string) *CurrentUser {
func doVerifyToken(ctx context.Context, token string, mode string) int64 {
if strings.TrimSpace(token) == "" {
return nil
return 0
}
var (
user *CurrentUser
err error
userId int64
err error
)
switch mode {
case CacheModeRedis:
user, err = doExistsTokenFromRedis(ctx, token)
userId, err = doExistsTokenFromRedis(ctx, token)
case CacheModeMemory:
user, err = doExistsTokenFromMemory(ctx, token)
case CacheModeNone:
user, err = doVerifyTokenByUnSignVerify(ctx, token)
userId, err = doExistsTokenFromMemory(ctx, token)
default:
g.Log().Errorf(ctx, "illegal cache mode: %s", mode)
return nil
return 0
}
if err != nil {
g.Log().Error(ctx, err)
return nil
return 0
}
if user != nil {
return user
if userId > 0 {
return userId
}
return nil
return 0
}

func doExistsTokenFromRedis(ctx context.Context, token string) (*CurrentUser, error) {
func doExistsTokenFromRedis(ctx context.Context, token string) (int64, error) {
key := CachePrefixUserToken + ":" + token
tmp, err := redisOps().Get(ctx, key)
if err != nil {
return nil, err
}
if tmp.IsNil() {
return nil, nil
}
content := &SimpleTokenContent{}
err = tmp.Scan(content)
value, err := redisOps().Get(ctx, key)
if err != nil {
return nil, err
return 0, err
}
if gutil.IsEmpty(content.UserId) {
return nil, nil
if value.IsNil() {
return 0, nil
}
if !content.IsValidate() {
return nil, nil
}
return &CurrentUser{UserId: content.UserId}, nil
return value.Int64(), nil
}

func doExistsTokenFromMemory(ctx context.Context, token string) (*CurrentUser, error) {
func doExistsTokenFromMemory(ctx context.Context, token string) (int64, error) {
key := CachePrefixUserToken + ":" + token
tmp, err := gcache.Get(ctx, key)
if err != nil {
return nil, err
}
content := &SimpleTokenContent{}
err = tmp.Scan(content)
value, err := gcache.Get(ctx, key)
if err != nil {
return nil, err
}
if gutil.IsEmpty(content.UserId) {
return nil, nil
}
if !content.IsValidate() {
return nil, nil
}
return &CurrentUser{UserId: content.UserId}, nil
}
func doVerifyTokenByUnSignVerify(ctx context.Context, token string) (*CurrentUser, error) {
if unSignToken == nil {
g.Log().Error(ctx, "func unSignToken do not init")
return nil, errors.New("func signToken do not init")
}
content, err := unSignToken(ctx, token)
if err != nil {
return nil, err
}
if gutil.IsEmpty(content.UserId) {
return nil, nil
return 0, err
}
if !content.IsValidate() {
return nil, nil
if value.IsNil() {
return 0, nil
}
return &CurrentUser{UserId: content.UserId}, nil
return value.Int64(), nil
}
1 change: 0 additions & 1 deletion auth/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const (
const (
CacheModeRedis = "REDIS"
CacheModeMemory = "MEMORY"
CacheModeNone = "NONE"
)

const (
Expand Down
2 changes: 1 addition & 1 deletion auth/define.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type RuleConfig struct {
sync.RWMutex
RedisName string `json:"redisName" dc:"redis名称"`
Issuer string `json:"issuer" v:"required" dc:"Token签发者"`
CacheMode string `json:"cacheMode" v:"required|in:redis,memory,none" d:"no" dc:"token是否使用缓存以及缓存的方式"`
CacheMode string `json:"cacheMode" v:"required|in:redis,memory" d:"no" dc:"token是否使用缓存以及缓存的方式"`
ExpireDt int64 `json:"expireDt" v:"required-unless:cacheMode" dc:"缓存有效时间"`
Rule []Rule `json:"rule" dc:"权限路由集合"`
}
Expand Down
10 changes: 0 additions & 10 deletions auth/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ var (
ruleMap *sync.Map
getGroupCodes func(ctx context.Context, userId int64) ([]string, error)
getPermissionCodes func(ctx context.Context, userId int64) ([]string, error)
signToken func(ctx context.Context, s *SimpleTokenContent) (string, error)
unSignToken func(ctx context.Context, content string) (*SimpleTokenContent, error)
getPlatform func(ctx context.Context) string
)

Expand All @@ -39,14 +37,6 @@ func SetGetPermissionCodes(f func(ctx context.Context, userId int64) ([]string,
getPermissionCodes = f
}

func SetSignTokenFunc(f func(ctx context.Context, s *SimpleTokenContent) (string, error)) {
signToken = f
}

func SetUnSignTokenFunc(f func(ctx context.Context, content string) (*SimpleTokenContent, error)) {
unSignToken = f
}

func SetGetPlatformFunc(f func(ctx context.Context) string) {
getPlatform = f
}
Expand Down
30 changes: 5 additions & 25 deletions auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@ import (
"context"
"errors"
"fmt"
"github.com/google/uuid"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/util/gutil"
)

func Login(ctx context.Context, userId int64) (string, error) {
if signToken == nil {
g.Log().Error(ctx, "func signToken do not init")
return "", errors.New("func signToken do not init")
}
if gutil.IsEmpty(userId) {
return "", errors.New("userId empty")
}
Expand All @@ -24,8 +21,6 @@ func Login(ctx context.Context, userId int64) (string, error) {
return GenerateTokenToRedis(ctx, userId)
case CacheModeMemory:
return GenerateTokenToMemory(ctx, userId)
case CacheModeNone:
return GenerateToken(ctx, userId)
default:
return "", errors.New("invalid cache mode")
}
Expand All @@ -44,13 +39,9 @@ func Logout(ctx context.Context, userId int64) (string, error) {
}

func GenerateTokenToRedis(ctx context.Context, userId int64) (string, error) {
content := NewSimpleTokenContent(userId)
token, err := signToken(ctx, content)
if err != nil {
return "", err
}
token := uuid.New().String()
cacheKey := CachePrefixUserToken + ":" + token
err = redisOps().SetEX(ctx, cacheKey, content, GetCacheExpireDt())
err := redisOps().SetEX(ctx, cacheKey, userId, GetCacheExpireDt())
if err != nil {
return "", err
}
Expand All @@ -67,13 +58,9 @@ func GenerateTokenToRedis(ctx context.Context, userId int64) (string, error) {
}

func GenerateTokenToMemory(ctx context.Context, userId int64) (string, error) {
content := NewSimpleTokenContent(userId)
token, err := signToken(ctx, content)
if err != nil {
return "", err
}
token := uuid.New().String()
cacheKey := CachePrefixUserToken + ":" + token
err = gcache.Set(ctx, cacheKey, content, GetCacheExpireDtDuration())
err := gcache.Set(ctx, cacheKey, userId, GetCacheExpireDtDuration())
if err != nil {
return "", err
}
Expand All @@ -97,13 +84,6 @@ func GenerateTokenToMemory(ctx context.Context, userId int64) (string, error) {
}
return token, nil
}

func GenerateToken(ctx context.Context, userId int64) (string, error) {
content := NewSimpleTokenContent(userId)
token, err := signToken(ctx, content)
return token, err
}

func ClearUserTokenInRedis(ctx context.Context, userId int64) error {
arrayCacheKey := fmt.Sprintf("%s:%d", CachePrefixUserTokenArray, userId)

Expand Down
8 changes: 3 additions & 5 deletions auth/permission.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ func doPermissionRequired(r *ghttp.Request) error {
value := r.GetCtxVar(CtxUserId)
var userId int64
if value.IsNil() {
currentUser := doVerifyToken(r.GetCtx(), token, cacheMode)
if currentUser == nil {
currentUserId := doVerifyToken(r.GetCtx(), token, cacheMode)
if currentUserId == 0 {
return gerror.NewCode(IllegalTokensError)
}
r.SetCtxVar(CtxUserId, currentUser.UserId)
r.SetCtxVar(CtxUserId, currentUserId)
} else {
userId = value.Int64()
}
Expand Down Expand Up @@ -80,8 +80,6 @@ func doVerifyAuth(ctx context.Context, userId int64, permissions []RulePermissio
return doAuthFromRedis(ctx, userId, permissions)
case CacheModeMemory:
return doAuthFromMemory(ctx, userId, permissions)
case CacheModeNone:
return doAuthFromDb(ctx, userId, permissions)
}
return false
}
Expand Down
15 changes: 0 additions & 15 deletions encoding/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,6 @@ func ReInitJwtEncodingKeys() {
doLoadJwt(newJwtCfg, newKeys)
g.Log().Infof(ctx, "[Success] ReLoad Security Config")
}

rsaCfg.Lock()
defer rsaCfg.Unlock()
rsaKeys.Lock()
defer rsaKeys.Unlock()
newRsaCfg := &RsaConfig{}
doLoadRsaConfig(ctx, newRsaCfg)
rsaKeys = &RsaKeys{}
doLoadRsaKeys(rsaCfg, rsaKeys)
rsaCfgEqual := doRsaCfgCompare(newRsaCfg, rsaCfg)
if !rsaCfgEqual {
rsaCfg = newRsaCfg
newRsaKeys := &RsaKeys{}
doLoadRsaKeys(rsaCfg, newRsaKeys)
}
}

func ReInitRsaEncodingKeys() {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.22
require (
github.com/gogf/gf/v2 v2.7.3
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
)

require (
Expand Down

0 comments on commit eac2904

Please sign in to comment.