sso_rpc.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package sso
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "eta/eta_mini_crm_ht/rpc"
  7. "eta/eta_mini_crm_ht/utils"
  8. "fmt"
  9. "google.golang.org/grpc/metadata"
  10. "sync"
  11. )
  12. var (
  13. once sync.Once
  14. rpcPool utils.ClientPool
  15. SSOServiceImpl *SSOService
  16. )
  17. type SSOService struct {
  18. ssoRPCService
  19. }
  20. type ssoRPCService struct {
  21. rpc.DefaultRpcClient
  22. }
  23. func GetSSOService() *SSOService {
  24. once.Do(func() {
  25. c := ssoRPCService{}
  26. rpcPool = c.GetPool(utils.SSO_URL)
  27. SSOServiceImpl = &SSOService{c}
  28. })
  29. return SSOServiceImpl
  30. }
  31. type UserResp struct {
  32. UserName string
  33. }
  34. func (s *SSOService) SSOLogin(request *LoginRequest) (resp UserResp, err error) {
  35. conn := rpcPool.Get()
  36. defer rpcPool.Put(conn)
  37. ssoLoginService := NewSSOLoginClient(conn)
  38. aesKey, err := utils.GenerateAESKey(16)
  39. if err != nil {
  40. utils.FileLog.Error("生成AES密钥失败:%v", err)
  41. return
  42. }
  43. encryptedCode, err := utils.EncryptWithAES(aesKey, []byte(request.Code))
  44. if err != nil {
  45. utils.FileLog.Error("AES加密失败:%v", err)
  46. return
  47. }
  48. request.Code = base64Encode(encryptedCode)
  49. publicKey, err := utils.ParsePublicKeyFromPEM()
  50. if err != nil {
  51. utils.FileLog.Error("RSA加密失败:%v", err)
  52. return
  53. }
  54. //加密 AES 密钥
  55. encryptedAESKey, err := utils.EncryptWithRSA(publicKey, aesKey)
  56. if err != nil {
  57. utils.FileLog.Error("encrypting AES key: %v", err)
  58. return
  59. }
  60. key := base64Encode(encryptedAESKey)
  61. ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(
  62. "key", key,
  63. ))
  64. ssoResp, err := ssoLoginService.Login(ctx, request)
  65. if err != nil {
  66. utils.FileLog.Error("sso login failed:%v", err)
  67. return
  68. }
  69. if ssoResp.ErrCode != 0 {
  70. err = errors.New(fmt.Sprintf("sso登录失败:%s", ssoResp.ErrMsg))
  71. utils.FileLog.Error("sso登录失败:%v", ssoResp.ErrMsg)
  72. return
  73. }
  74. userinfo := ssoResp.Data
  75. utils.FileLog.Info("sso请求成功")
  76. resp = UserResp{
  77. UserName: userinfo.Username,
  78. }
  79. return
  80. }
  81. func base64Encode(data []byte) string {
  82. return base64.StdEncoding.EncodeToString(data)
  83. }
  84. // Base64Decode 对数据进行 Base64 解码
  85. func base64Decode(data string) ([]byte, error) {
  86. return base64.StdEncoding.DecodeString(data)
  87. }