secure_verification.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package controller
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/model"
  8. "github.com/gin-contrib/sessions"
  9. "github.com/gin-gonic/gin"
  10. )
  11. const (
  12. // SecureVerificationSessionKey means the user has fully passed secure verification.
  13. SecureVerificationSessionKey = "secure_verified_at"
  14. secureVerificationMethodSessionKey = "secure_verified_method"
  15. secureVerificationMethod2FA = "2fa"
  16. secureVerificationMethodPasskey = "passkey"
  17. // PasskeyReadySessionKey means WebAuthn finished and /api/verify can finalize step-up verification.
  18. PasskeyReadySessionKey = "secure_passkey_ready_at"
  19. // SecureVerificationTimeout 验证有效期(秒)
  20. SecureVerificationTimeout = 300 // 5分钟
  21. // PasskeyReadyTimeout passkey ready 标记有效期(秒)
  22. PasskeyReadyTimeout = 60
  23. )
  24. type UniversalVerifyRequest struct {
  25. Method string `json:"method"` // "2fa" 或 "passkey"
  26. Code string `json:"code,omitempty"`
  27. }
  28. type VerificationStatusResponse struct {
  29. Verified bool `json:"verified"`
  30. ExpiresAt int64 `json:"expires_at,omitempty"`
  31. }
  32. // UniversalVerify 通用验证接口
  33. // 支持 2FA 和 Passkey 验证,验证成功后在 session 中记录时间戳
  34. func UniversalVerify(c *gin.Context) {
  35. userId := c.GetInt("id")
  36. if userId == 0 {
  37. c.JSON(http.StatusUnauthorized, gin.H{
  38. "success": false,
  39. "message": "未登录",
  40. })
  41. return
  42. }
  43. var req UniversalVerifyRequest
  44. if err := c.ShouldBindJSON(&req); err != nil {
  45. common.ApiError(c, fmt.Errorf("参数错误: %v", err))
  46. return
  47. }
  48. // 获取用户信息
  49. user := &model.User{Id: userId}
  50. if err := user.FillUserById(); err != nil {
  51. common.ApiError(c, fmt.Errorf("获取用户信息失败: %v", err))
  52. return
  53. }
  54. if user.Status != common.UserStatusEnabled {
  55. common.ApiError(c, fmt.Errorf("该用户已被禁用"))
  56. return
  57. }
  58. // 检查用户的验证方式
  59. twoFA, _ := model.GetTwoFAByUserId(userId)
  60. has2FA := twoFA != nil && twoFA.IsEnabled
  61. passkey, passkeyErr := model.GetPasskeyByUserID(userId)
  62. hasPasskey := passkeyErr == nil && passkey != nil
  63. if !has2FA && !hasPasskey {
  64. common.ApiError(c, fmt.Errorf("用户未启用2FA或Passkey"))
  65. return
  66. }
  67. // 根据验证方式进行验证
  68. var verified bool
  69. var verifyMethod string
  70. var err error
  71. switch req.Method {
  72. case "2fa":
  73. if !has2FA {
  74. common.ApiError(c, fmt.Errorf("用户未启用2FA"))
  75. return
  76. }
  77. if req.Code == "" {
  78. common.ApiError(c, fmt.Errorf("验证码不能为空"))
  79. return
  80. }
  81. verified = validateTwoFactorAuth(twoFA, req.Code)
  82. verifyMethod = "2FA"
  83. case "passkey":
  84. if !hasPasskey {
  85. common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
  86. return
  87. }
  88. // Passkey branch only trusts the short-lived marker written by PasskeyVerifyFinish.
  89. verified, err = consumePasskeyReady(c)
  90. if err != nil {
  91. common.ApiError(c, fmt.Errorf("Passkey 验证状态异常: %v", err))
  92. return
  93. }
  94. if !verified {
  95. common.ApiError(c, fmt.Errorf("请先完成 Passkey 验证"))
  96. return
  97. }
  98. verifyMethod = "Passkey"
  99. default:
  100. common.ApiError(c, fmt.Errorf("不支持的验证方式: %s", req.Method))
  101. return
  102. }
  103. if !verified {
  104. common.ApiError(c, fmt.Errorf("验证失败,请检查验证码"))
  105. return
  106. }
  107. // 验证成功,在 session 中记录时间戳
  108. now, err := setSecureVerificationSession(c, req.Method)
  109. if err != nil {
  110. common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
  111. return
  112. }
  113. // 记录日志
  114. model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("通用安全验证成功 (验证方式: %s)", verifyMethod))
  115. c.JSON(http.StatusOK, gin.H{
  116. "success": true,
  117. "message": "验证成功",
  118. "data": gin.H{
  119. "verified": true,
  120. "expires_at": now + SecureVerificationTimeout,
  121. },
  122. })
  123. }
  124. func setSecureVerificationSession(c *gin.Context, method string) (int64, error) {
  125. session := sessions.Default(c)
  126. session.Delete(PasskeyReadySessionKey)
  127. now := time.Now().Unix()
  128. session.Set(SecureVerificationSessionKey, now)
  129. session.Set(secureVerificationMethodSessionKey, method)
  130. if err := session.Save(); err != nil {
  131. return 0, err
  132. }
  133. return now, nil
  134. }
  135. func consumePasskeyReady(c *gin.Context) (bool, error) {
  136. session := sessions.Default(c)
  137. readyAtRaw := session.Get(PasskeyReadySessionKey)
  138. if readyAtRaw == nil {
  139. return false, nil
  140. }
  141. readyAt, ok := readyAtRaw.(int64)
  142. if !ok {
  143. session.Delete(PasskeyReadySessionKey)
  144. _ = session.Save()
  145. return false, fmt.Errorf("无效的 Passkey 验证状态")
  146. }
  147. session.Delete(PasskeyReadySessionKey)
  148. if err := session.Save(); err != nil {
  149. return false, err
  150. }
  151. // Expired ready markers cannot be reused.
  152. if time.Now().Unix()-readyAt >= PasskeyReadyTimeout {
  153. return false, nil
  154. }
  155. return true, nil
  156. }