SecureVerificationRequired 安全验证中间件 检查用户是否在有效时间内通过了安全验证 如果未验证或验证已过期,返回 401 错误
()
| 20 | // 检查用户是否在有效时间内通过了安全验证 |
| 21 | // 如果未验证或验证已过期,返回 401 错误 |
| 22 | func SecureVerificationRequired() gin.HandlerFunc { |
| 23 | return func(c *gin.Context) { |
| 24 | // 检查用户是否已登录 |
| 25 | userId := c.GetInt("id") |
| 26 | if userId == 0 { |
| 27 | c.JSON(http.StatusUnauthorized, gin.H{ |
| 28 | "success": false, |
| 29 | "message": "未登录", |
| 30 | }) |
| 31 | c.Abort() |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | // 检查 session 中的验证时间戳 |
| 36 | session := sessions.Default(c) |
| 37 | verifiedAtRaw := session.Get(SecureVerificationSessionKey) |
| 38 | |
| 39 | if verifiedAtRaw == nil { |
| 40 | c.JSON(http.StatusForbidden, gin.H{ |
| 41 | "success": false, |
| 42 | "message": "需要安全验证", |
| 43 | "code": "VERIFICATION_REQUIRED", |
| 44 | }) |
| 45 | c.Abort() |
| 46 | return |
| 47 | } |
| 48 | |
| 49 | verifiedAt, ok := verifiedAtRaw.(int64) |
| 50 | if !ok { |
| 51 | // session 数据格式错误 |
| 52 | clearSecureVerificationSession(session) |
| 53 | c.JSON(http.StatusForbidden, gin.H{ |
| 54 | "success": false, |
| 55 | "message": "验证状态异常,请重新验证", |
| 56 | "code": "VERIFICATION_INVALID", |
| 57 | }) |
| 58 | c.Abort() |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | // 检查验证是否过期 |
| 63 | elapsed := time.Now().Unix() - verifiedAt |
| 64 | if elapsed >= SecureVerificationTimeout { |
| 65 | // 验证已过期,清除 session |
| 66 | clearSecureVerificationSession(session) |
| 67 | c.JSON(http.StatusForbidden, gin.H{ |
| 68 | "success": false, |
| 69 | "message": "验证已过期,请重新验证", |
| 70 | "code": "VERIFICATION_EXPIRED", |
| 71 | }) |
| 72 | c.Abort() |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | c.Next() |
| 77 | } |
| 78 | } |
| 79 |
no test coverage detected