github.com/godaddy-x/freego@v1.0.156/rpcx/impl/pub_worker.go (about) 1 package impl 2 3 import ( 4 "context" 5 "github.com/godaddy-x/freego/rpcx" 6 "github.com/godaddy-x/freego/rpcx/pb" 7 "github.com/godaddy-x/freego/utils" 8 "github.com/godaddy-x/freego/utils/jwt" 9 ) 10 11 type PubWorker struct { 12 pb.UnimplementedPubWorkerServer 13 } 14 15 func (self *PubWorker) GenerateId(ctx context.Context, req *pb.GenerateIdReq) (*pb.GenerateIdRes, error) { 16 return &pb.GenerateIdRes{Value: utils.NextIID()}, nil 17 } 18 19 func (self *PubWorker) PublicKey(ctx context.Context, req *pb.PublicKeyReq) (*pb.PublicKeyRes, error) { 20 tls, err := rpcx.GetAuthorizeTLS() 21 if err != nil { 22 return nil, err 23 } 24 _, publicKey := tls.GetPublicKey() 25 return &pb.PublicKeyRes{PublicKey: publicKey}, nil 26 } 27 28 func (self *PubWorker) Authorize(ctx context.Context, req *pb.AuthorizeReq) (*pb.AuthorizeRes, error) { 29 if len(req.Message) == 0 { 30 return nil, utils.Error("message is nil") 31 } 32 rsaObj, err := rpcx.GetAuthorizeTLS() 33 if err != nil { 34 return nil, err 35 } 36 dec, err := rsaObj.Decrypt(req.Message) 37 if err != nil { 38 return nil, err 39 } 40 authObj := &rpcx.AuthObject{} 41 if err := utils.ParseJsonBase64(dec, authObj); err != nil { 42 return nil, err 43 } 44 if len(authObj.AppId) != 32 { 45 return nil, utils.Error("appid invalid") 46 } 47 if !utils.CheckLen(authObj.Nonce, 8, 16) { 48 return nil, utils.Error("nonce invalid") 49 } 50 if utils.MathAbs(utils.UnixSecond()-authObj.Time) > jwt.FIVE_MINUTES { // 判断绝对时间差超过5分钟 51 return nil, utils.Error("time invalid") 52 } 53 appConfig, err := rpcx.GetGRPCAppConfig(authObj.AppId) 54 if err != nil { 55 return nil, err 56 } 57 if len(authObj.Signature) != 44 || utils.HMAC_SHA256(utils.AddStr(authObj.AppId, authObj.Nonce, authObj.Time), appConfig.AppKey, true) != authObj.Signature { 58 return nil, utils.Error("signature invalid") 59 } 60 jwtConfig, err := rpcx.GetGRPCJwtConfig() 61 if err != nil { 62 return nil, err 63 } 64 subject := &jwt.Subject{} 65 subject.Create(authObj.AppId).Dev("GRPC").Expired(jwtConfig.TokenExp) 66 token := subject.Generate(jwt.JwtConfig{TokenTyp: jwtConfig.TokenTyp, TokenAlg: jwtConfig.TokenAlg, TokenKey: jwtConfig.TokenKey}) 67 return &pb.AuthorizeRes{Token: token, Expired: subject.Payload.Exp}, nil 68 }