engine/service/context.go

45 lines
1006 B
Go

package service
import (
"context"
"strings"
"git.apinb.com/bsm-sdk/engine/encipher"
"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")
if len(Authorizations) == 0 || Authorizations[0] == "" {
return nil, exception.ErrAuthNotFound
}
claims, err := encipher.ParseTokenAes(Authorizations[0])
if err != nil {
return nil, err
}
if opts != nil {
if !strings.Contains(claims.Role, opts.RoleValue) {
return nil, exception.ErrPermissionDenied
}
}
return claims, nil
}