MCPcopy Create free account
hub / github.com/aiprodcoder/MIXAPI / ValidateUserToken

Function ValidateUserToken

model/token.go:83–139  ·  view source on GitHub ↗
(key string)

Source from the content-addressed store, hash-verified

81}
82
83func ValidateUserToken(key string) (token *Token, err error) {
84 log.Println("===========", key)
85 if key == "" {
86 return nil, errors.New("未提供令牌")
87 }
88 token, err = GetTokenByKey(key, false)
89 if err == nil {
90 if token.Status == common.TokenStatusExhausted {
91 keyPrefix := key[:3]
92 keySuffix := key[len(key)-3:]
93 return token, errors.New("该令牌额度已用尽 TokenStatusExhausted[sk-" + keyPrefix + "***" + keySuffix + "]")
94 } else if token.Status == common.TokenStatusExpired {
95 return token, errors.New("该令牌已过期")
96 }
97 if token.Status != common.TokenStatusEnabled {
98 return token, errors.New("该令牌状态不可用")
99 }
100 if token.ExpiredTime != -1 && token.ExpiredTime < common.GetTimestamp() {
101 if !common.RedisEnabled {
102 token.Status = common.TokenStatusExpired
103 err := token.SelectUpdate()
104 if err != nil {
105 common.SysError("failed to update token status" + err.Error())
106 }
107 }
108 return token, errors.New("该令牌已过期")
109 }
110 if !token.UnlimitedQuota && token.RemainQuota <= 0 {
111 if !common.RedisEnabled {
112 // in this case, we can make sure the token is exhausted
113 token.Status = common.TokenStatusExhausted
114 err := token.SelectUpdate()
115 if err != nil {
116 common.SysError("failed to update token status" + err.Error())
117 }
118 }
119 keyPrefix := key[:3]
120 keySuffix := key[len(key)-3:]
121 return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
122 }
123
124 // 检查总使用次数限制
125 if token.TotalUsageLimit != nil && *token.TotalUsageLimit > 0 && token.TotalUsageCount >= *token.TotalUsageLimit {
126 keyPrefix := key[:3]
127 keySuffix := key[len(key)-3:]
128 return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌总使用次数已用完,限制次数: %d,已使用次数: %d", keyPrefix, keySuffix, *token.TotalUsageLimit, token.TotalUsageCount))
129 }
130
131 // 检查访问频率限制
132 if err := CheckRateLimit(token); err != nil {
133 return token, err
134 }
135
136 return token, nil
137 }
138 return nil, errors.New("无效的令牌")
139}
140

Callers 1

TokenAuthFunction · 0.92

Calls 6

GetTimestampFunction · 0.92
SysErrorFunction · 0.92
GetTokenByKeyFunction · 0.85
CheckRateLimitFunction · 0.85
ErrorMethod · 0.80
SelectUpdateMethod · 0.45

Tested by

no test coverage detected