This commit is contained in:
zhaoxiaorong
2025-04-09 10:19:15 +08:00
parent c7f24e3b6d
commit 51ff7d1ffd
3 changed files with 51 additions and 23 deletions

View File

@@ -5,25 +5,18 @@ import (
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/utils"
"google.golang.org/grpc/metadata"
)
type Meta struct {
ID uint `json:"id"`
IDENTITY string `json:"identity"`
EXTEND map[string]string `json:"extend"`
CLIENT string `json:"client"`
ROLE string `json:"role"`
}
// 解析Context中MetaData的数据
type ParseOptions struct {
RoleValue string // 判断角色的值
MustPrivateAllow bool // 是否只允许私有IP访问
}
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) {
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
// 解析metada中的信息并验证
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
@@ -40,34 +33,26 @@ func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) {
return nil, err
}
meta := &Meta{
ID: claims.ID,
IDENTITY: claims.Identity,
CLIENT: claims.Client,
EXTEND: claims.Extend,
ROLE: claims.Role,
}
if opts != nil {
if !meta.CheckRole("role", opts.RoleValue) {
if !checkRole(claims, "role", opts.RoleValue) {
return nil, errcode.ErrPermissionDenied
}
if opts.MustPrivateAllow {
if utils.IsPublicIP(meta.CLIENT) {
if utils.IsPublicIP(claims.Client) {
return nil, errcode.ErrPermissionDenied
}
}
}
return meta, nil
return claims, nil
}
func (m *Meta) CheckRole(roleKey, roleValue string) bool {
func checkRole(claims *types.JwtClaims, roleKey, roleValue string) bool {
if roleValue == "" {
return true
}
if role, exists := m.EXTEND[roleKey]; !exists || role != roleValue {
if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
return false
} else {
return true