2024-02-11 01:31:01 +08:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-09-17 21:57:37 +08:00
|
|
|
"encoding/json"
|
2024-02-11 01:31:01 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"git.apinb.com/bsm-sdk/engine/exception"
|
|
|
|
"git.apinb.com/bsm-sdk/engine/types"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 解析Context中MetaData的数据
|
|
|
|
type ParseOptions struct {
|
|
|
|
RoleValue string // 判断角色的值
|
|
|
|
MustPrivateAllow bool // 是否只允许私有IP访问
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
|
|
|
|
// 解析metada中的信息并验证
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return nil, exception.ErrAuthNotFound
|
|
|
|
}
|
|
|
|
|
2024-09-17 21:57:37 +08:00
|
|
|
var Authorizations []string = md.Get("authorization_claims")
|
2024-02-11 01:31:01 +08:00
|
|
|
if len(Authorizations) == 0 || Authorizations[0] == "" {
|
|
|
|
return nil, exception.ErrAuthNotFound
|
|
|
|
}
|
|
|
|
|
2024-09-17 21:57:37 +08:00
|
|
|
var claims types.JwtClaims
|
|
|
|
err := json.Unmarshal([]byte(Authorizations[0]), &claims)
|
2024-02-11 01:31:01 +08:00
|
|
|
if err != nil {
|
2024-09-17 21:57:37 +08:00
|
|
|
return nil, exception.ErrAuthParseFail
|
2024-02-11 01:31:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if opts != nil {
|
|
|
|
if !strings.Contains(claims.Role, opts.RoleValue) {
|
|
|
|
return nil, exception.ErrPermissionDenied
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-17 21:57:37 +08:00
|
|
|
return &claims, nil
|
2024-02-11 01:31:01 +08:00
|
|
|
|
|
|
|
}
|