| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- package utils
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "strings"
- "time"
- )
- // TokenUserInfo 从token验证API返回的用户信息
- type TokenUserInfo struct {
- AccountID string `json:"accountID"`
- ID int64 `json:"id"`
- Name string `json:"name"`
- UserCode string `json:"userCode"`
- ContactNumber string `json:"contactNumber"`
- TokenType string `json:"token_type"`
- Exp int64 `json:"exp"`
- Iat int64 `json:"iat"`
- }
- // VerifyToken 验证token并返回用户信息
- func VerifyToken(token string) (*TokenUserInfo, error) {
- if token == "" {
- return nil, fmt.Errorf("token不能为空")
- }
- authAPIURL := GetConfigString("auth_api_url", "")
- jsonData, _ := json.Marshal(map[string]string{"token": token})
- req, err := http.NewRequest("POST", authAPIURL, bytes.NewBuffer(jsonData))
- if err != nil {
- return nil, fmt.Errorf("创建请求失败: %v", err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", "Bearer "+token)
- client := &http.Client{Timeout: 10 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("请求token验证API失败: %v", err)
- }
- defer resp.Body.Close()
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("读取响应失败: %v", err)
- }
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("token验证失败,状态码: %d", resp.StatusCode)
- }
- var userInfo TokenUserInfo
- if err := json.Unmarshal(body, &userInfo); err != nil {
- return nil, fmt.Errorf("解析响应失败: %v", err)
- }
- if userInfo.Exp > 0 && time.Now().Unix() > userInfo.Exp {
- return nil, fmt.Errorf("token已过期")
- }
- return &userInfo, nil
- }
- // GetUserInfoFromToken 从请求头中获取token并验证
- func GetUserInfoFromToken(headerFunc func(string) string) (*TokenUserInfo, error) {
- token := headerFunc("token")
- if token == "" {
- token = headerFunc("Token")
- }
- if token == "" {
- token = headerFunc("Authorization")
- if strings.HasPrefix(token, "Bearer ") {
- token = token[7:]
- }
- }
- if token == "" {
- return nil, fmt.Errorf("请求头中未找到token")
- }
- return VerifyToken(token)
- }
- // GetUserInfoFromContext 从Context中获取已验证的用户信息
- func GetUserInfoFromContext(input interface{}) (*TokenUserInfo, error) {
- if input == nil {
- return nil, fmt.Errorf("未找到用户信息")
- }
- userInfo, ok := input.(*TokenUserInfo)
- if !ok {
- return nil, fmt.Errorf("用户信息类型错误")
- }
- if userInfo == nil {
- return nil, fmt.Errorf("用户信息为空")
- }
- return userInfo, nil
- }
|