token.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package utils
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. // TokenUserInfo 从token验证API返回的用户信息
  12. type TokenUserInfo struct {
  13. AccountID string `json:"accountID"`
  14. ID int64 `json:"id"`
  15. Name string `json:"name"`
  16. UserCode string `json:"userCode"`
  17. ContactNumber string `json:"contactNumber"`
  18. TokenType string `json:"token_type"`
  19. Exp int64 `json:"exp"`
  20. Iat int64 `json:"iat"`
  21. }
  22. // VerifyToken 验证token并返回用户信息
  23. func VerifyToken(token string) (*TokenUserInfo, error) {
  24. if token == "" {
  25. return nil, fmt.Errorf("token不能为空")
  26. }
  27. authAPIURL := GetConfigString("auth_api_url", "")
  28. jsonData, _ := json.Marshal(map[string]string{"token": token})
  29. req, err := http.NewRequest("POST", authAPIURL, bytes.NewBuffer(jsonData))
  30. if err != nil {
  31. return nil, fmt.Errorf("创建请求失败: %v", err)
  32. }
  33. req.Header.Set("Content-Type", "application/json")
  34. req.Header.Set("Authorization", "Bearer "+token)
  35. client := &http.Client{Timeout: 10 * time.Second}
  36. resp, err := client.Do(req)
  37. if err != nil {
  38. return nil, fmt.Errorf("请求token验证API失败: %v", err)
  39. }
  40. defer resp.Body.Close()
  41. body, err := io.ReadAll(resp.Body)
  42. if err != nil {
  43. return nil, fmt.Errorf("读取响应失败: %v", err)
  44. }
  45. if resp.StatusCode != http.StatusOK {
  46. return nil, fmt.Errorf("token验证失败,状态码: %d", resp.StatusCode)
  47. }
  48. var userInfo TokenUserInfo
  49. if err := json.Unmarshal(body, &userInfo); err != nil {
  50. return nil, fmt.Errorf("解析响应失败: %v", err)
  51. }
  52. if userInfo.Exp > 0 && time.Now().Unix() > userInfo.Exp {
  53. return nil, fmt.Errorf("token已过期")
  54. }
  55. return &userInfo, nil
  56. }
  57. // GetUserInfoFromToken 从请求头中获取token并验证
  58. func GetUserInfoFromToken(headerFunc func(string) string) (*TokenUserInfo, error) {
  59. token := headerFunc("token")
  60. if token == "" {
  61. token = headerFunc("Token")
  62. }
  63. if token == "" {
  64. token = headerFunc("Authorization")
  65. if strings.HasPrefix(token, "Bearer ") {
  66. token = token[7:]
  67. }
  68. }
  69. if token == "" {
  70. return nil, fmt.Errorf("请求头中未找到token")
  71. }
  72. return VerifyToken(token)
  73. }
  74. // GetUserInfoFromContext 从Context中获取已验证的用户信息
  75. func GetUserInfoFromContext(input interface{}) (*TokenUserInfo, error) {
  76. if input == nil {
  77. return nil, fmt.Errorf("未找到用户信息")
  78. }
  79. userInfo, ok := input.(*TokenUserInfo)
  80. if !ok {
  81. return nil, fmt.Errorf("用户信息类型错误")
  82. }
  83. if userInfo == nil {
  84. return nil, fmt.Errorf("用户信息为空")
  85. }
  86. return userInfo, nil
  87. }