TokenAuthReadOnly 宽松版本的令牌认证中间件,用于只读查询接口。 只验证令牌 key 是否存在,不检查令牌状态、过期时间和额度。 即使令牌已过期、已耗尽或已禁用,也允许访问。 仍然检查用户是否被封禁。
()
| 222 | // 即使令牌已过期、已耗尽或已禁用,也允许访问。 |
| 223 | // 仍然检查用户是否被封禁。 |
| 224 | func TokenAuthReadOnly() func(c *gin.Context) { |
| 225 | return func(c *gin.Context) { |
| 226 | key := c.Request.Header.Get("Authorization") |
| 227 | if key == "" { |
| 228 | c.JSON(http.StatusUnauthorized, gin.H{ |
| 229 | "success": false, |
| 230 | "message": common.TranslateMessage(c, i18n.MsgTokenNotProvided), |
| 231 | }) |
| 232 | c.Abort() |
| 233 | return |
| 234 | } |
| 235 | if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") { |
| 236 | key = strings.TrimSpace(key[7:]) |
| 237 | } |
| 238 | key = strings.TrimPrefix(key, "sk-") |
| 239 | parts := strings.Split(key, "-") |
| 240 | key = parts[0] |
| 241 | |
| 242 | token, err := model.GetTokenByKey(key, false) |
| 243 | if err != nil { |
| 244 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 245 | c.JSON(http.StatusUnauthorized, gin.H{ |
| 246 | "success": false, |
| 247 | "message": common.TranslateMessage(c, i18n.MsgTokenInvalid), |
| 248 | }) |
| 249 | } else { |
| 250 | common.SysLog("TokenAuthReadOnly GetTokenByKey database error: " + err.Error()) |
| 251 | c.JSON(http.StatusInternalServerError, gin.H{ |
| 252 | "success": false, |
| 253 | "message": common.TranslateMessage(c, i18n.MsgDatabaseError), |
| 254 | }) |
| 255 | } |
| 256 | c.Abort() |
| 257 | return |
| 258 | } |
| 259 | |
| 260 | userCache, err := model.GetUserCache(token.UserId) |
| 261 | if err != nil { |
| 262 | common.SysLog(fmt.Sprintf("TokenAuthReadOnly GetUserCache error for user %d: %v", token.UserId, err)) |
| 263 | c.JSON(http.StatusInternalServerError, gin.H{ |
| 264 | "success": false, |
| 265 | "message": common.TranslateMessage(c, i18n.MsgDatabaseError), |
| 266 | }) |
| 267 | c.Abort() |
| 268 | return |
| 269 | } |
| 270 | if userCache.Status != common.UserStatusEnabled { |
| 271 | c.JSON(http.StatusForbidden, gin.H{ |
| 272 | "success": false, |
| 273 | "message": common.TranslateMessage(c, i18n.MsgAuthUserBanned), |
| 274 | }) |
| 275 | c.Abort() |
| 276 | return |
| 277 | } |
| 278 | |
| 279 | c.Set("id", token.UserId) |
| 280 | c.Set("token_id", token.Id) |
| 281 | c.Set("token_key", token.Key) |
no test coverage detected