core/service/meta.go

61 lines
1.3 KiB
Go
Raw Normal View History

2025-03-29 15:02:49 +08:00
package service
import (
"context"
2025-04-08 15:20:22 +08:00
"git.apinb.com/bsm-sdk/core/crypto/encipher"
2025-03-29 15:02:49 +08:00
"git.apinb.com/bsm-sdk/core/errcode"
2025-04-09 10:19:15 +08:00
"git.apinb.com/bsm-sdk/core/types"
2025-03-29 15:02:49 +08:00
"git.apinb.com/bsm-sdk/core/utils"
"google.golang.org/grpc/metadata"
)
// 解析Context中MetaData的数据
type ParseOptions struct {
RoleValue string // 判断角色的值
MustPrivateAllow bool // 是否只允许私有IP访问
}
2025-04-09 10:19:15 +08:00
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
2025-03-29 15:02:49 +08:00
// 解析metada中的信息并验证
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errcode.ErrJWTAuthNotFound
}
2025-04-08 15:20:22 +08:00
var Authorizations []string = md.Get("authorization")
if len(Authorizations) == 0 || Authorizations[0] == "" {
2025-03-30 13:23:46 +08:00
return nil, errcode.ErrJWTAuthNotFound
}
2025-04-08 15:20:22 +08:00
claims, err := encipher.ParseTokenAes(Authorizations[0])
if err != nil {
return nil, err
}
2025-03-29 15:02:49 +08:00
if opts != nil {
2025-04-09 10:19:15 +08:00
if !checkRole(claims, "role", opts.RoleValue) {
2025-03-29 15:02:49 +08:00
return nil, errcode.ErrPermissionDenied
}
if opts.MustPrivateAllow {
2025-04-09 10:19:15 +08:00
if utils.IsPublicIP(claims.Client) {
2025-03-29 15:02:49 +08:00
return nil, errcode.ErrPermissionDenied
}
}
}
2025-04-09 10:19:15 +08:00
return claims, nil
2025-03-29 15:02:49 +08:00
}
2025-04-09 10:19:15 +08:00
func checkRole(claims *types.JwtClaims, roleKey, roleValue string) bool {
2025-03-29 15:02:49 +08:00
if roleValue == "" {
return true
}
2025-04-09 10:19:15 +08:00
if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
2025-03-29 15:02:49 +08:00
return false
} else {
return true
}
}