set_token_logic.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package fastgpt
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/golang-jwt/jwt/v5"
  8. "github.com/suyuan32/simple-admin-core/rpc/types/core"
  9. "net/http"
  10. "strconv"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "wechat-api/internal/svc"
  13. "wechat-api/internal/types"
  14. )
  15. type SetTokenLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. rw http.ResponseWriter
  20. }
  21. func NewSetTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext, rw http.ResponseWriter) *SetTokenLogic {
  22. return &SetTokenLogic{
  23. Logger: logx.WithContext(ctx),
  24. ctx: ctx,
  25. svcCtx: svcCtx,
  26. rw: rw,
  27. }
  28. }
  29. func (l *SetTokenLogic) SetToken(username string) (resp *types.BaseMsgResp, err error) {
  30. claims, err := ParseJWT(username, l.svcCtx.Config.Auth.AccessSecret)
  31. if err != nil {
  32. return nil, fmt.Errorf("invalid token")
  33. }
  34. data, err := l.svcCtx.CoreRpc.GetUserById(context.TODO(), &core.UUIDReq{Id: claims.UserId})
  35. token, err := l.getToken(strconv.FormatUint(*data.DepartmentId, 10))
  36. if err != nil {
  37. return nil, fmt.Errorf("invalid token")
  38. }
  39. //if err != nil {
  40. // return nil, err
  41. //}
  42. // 创建一个新的 Cookie
  43. cookie := &http.Cookie{
  44. Name: "fastgpt_token",
  45. Value: token, // 假设 req.Token 是你要设置的 Cookie 值
  46. Domain: ".gkscrm.com",
  47. SameSite: http.SameSiteNoneMode,
  48. Secure: true, // 如果 SameSite 设置为 None,必须设置 Secure 为 true
  49. HttpOnly: false,
  50. Path: "/",
  51. }
  52. // 设置 Cookie 到响应中
  53. http.SetCookie(l.rw, cookie)
  54. // 返回响应消息
  55. resp = &types.BaseMsgResp{
  56. Code: 0,
  57. Msg: "Cookie set successfully",
  58. }
  59. return
  60. }
  61. func (l *SetTokenLogic) getToken(username string) (string, error) {
  62. // 设置请求的 URL 和请求体
  63. url := "https://agent.gkscrm.com/api/support/user/account/loginByPassword"
  64. payload := map[string]string{
  65. "username": username,
  66. "password": "578fd6dfa3f71a8fadf5dc60d0e7115881db4c36504f83c4a0f4422107162c36",
  67. }
  68. // 将请求体编码为 JSON
  69. jsonPayload, err := json.Marshal(payload)
  70. if err != nil {
  71. return "", err
  72. }
  73. // 创建 HTTP 请求
  74. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
  75. if err != nil {
  76. return "", err
  77. }
  78. req.Header.Set("Content-Type", "application/json")
  79. // 发送请求
  80. client := &http.Client{}
  81. resp, err := client.Do(req)
  82. if err != nil {
  83. return "", err
  84. }
  85. defer resp.Body.Close()
  86. // 检查响应状态码
  87. if resp.StatusCode != http.StatusOK {
  88. return "", fmt.Errorf("failed to login, status code: %d", resp.StatusCode)
  89. }
  90. // 解析响应体
  91. var response map[string]interface{}
  92. err = json.NewDecoder(resp.Body).Decode(&response)
  93. if err != nil {
  94. return "", err
  95. }
  96. // 提取 token
  97. data, ok := response["data"].(map[string]interface{})
  98. if !ok {
  99. return "", fmt.Errorf("invalid response format")
  100. }
  101. token, ok := data["token"].(string)
  102. if !ok {
  103. return "", fmt.Errorf("token not found in response")
  104. }
  105. return token, nil
  106. }
  107. type Claims struct {
  108. RoleId string `json:"roleId"`
  109. UserId string `json:"userId"`
  110. jwt.RegisteredClaims
  111. }
  112. func ParseJWT(tokenString, accessSecret string) (*Claims, error) {
  113. claims := &Claims{}
  114. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  115. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  116. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  117. }
  118. return []byte(accessSecret), nil
  119. })
  120. if err != nil {
  121. return nil, fmt.Errorf("invalid token")
  122. }
  123. if !token.Valid {
  124. return nil, fmt.Errorf("invalid token")
  125. }
  126. return claims, nil
  127. }