engine/service/context.go

46 lines
1.0 KiB
Go

package service
import (
"context"
"encoding/json"
"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
}
var Authorizations []string = md.Get("authorization_claims")
if len(Authorizations) == 0 || Authorizations[0] == "" {
return nil, exception.ErrAuthNotFound
}
var claims types.JwtClaims
err := json.Unmarshal([]byte(Authorizations[0]), &claims)
if err != nil {
return nil, exception.ErrAuthParseFail
}
if opts != nil {
if !strings.Contains(claims.Role, opts.RoleValue) {
return nil, exception.ErrPermissionDenied
}
}
return &claims, nil
}