Repository navigation
feat: implement two-factor authentication (2FA) support with user login and settings integration - #1487
Conversation
…in and settings integration
WalkthroughThis change set introduces comprehensive two-factor authentication (2FA) support across backend and frontend. It adds TOTP and backup code logic, database models, API endpoints, controller logic, and new React components for 2FA setup, verification, and management. Login flow, user settings, and administrative operations are updated to integrate and enforce 2FA. Changes
Sequence Diagram(s)2FA-Enabled Login FlowsequenceDiagram
participant User
participant LoginForm (FE)
participant TwoFAVerification (FE)
participant API
participant Session
User->>LoginForm (FE): Submit username/password
LoginForm (FE)->>API: POST /api/user/login
API->>Session: Validate credentials
alt 2FA enabled
API->>LoginForm (FE): { require_2fa: true }
LoginForm (FE)->>TwoFAVerification (FE): Show 2FA modal
User->>TwoFAVerification (FE): Enter TOTP/backup code
TwoFAVerification (FE)->>API: POST /api/user/login/2fa
API->>Session: Validate code
alt Code valid
API->>TwoFAVerification (FE): Success, user data
TwoFAVerification (FE)->>LoginForm (FE): onSuccess
LoginForm (FE)->>User: Navigate to dashboard
else Code invalid
API->>TwoFAVerification (FE): Error
TwoFAVerification (FE)->>User: Show error
end
else 2FA not enabled
API->>LoginForm (FE): Success, user data
LoginForm (FE)->>User: Navigate to dashboard
end
2FA Setup Flow (User Settings)sequenceDiagram
participant User
participant TwoFASetting (FE)
participant API
User->>TwoFASetting (FE): Click "Enable 2FA"
TwoFASetting (FE)->>API: POST /api/user/2fa/setup
API->>TwoFASetting (FE): { secret, QRCodeData, backupCodes }
TwoFASetting (FE)->>User: Show QR code, secret, backup codes
User->>TwoFASetting (FE): Enter TOTP code from authenticator app
TwoFASetting (FE)->>API: POST /api/user/2fa/enable
API->>TwoFASetting (FE): Success/failure
TwoFASetting (FE)->>User: Show result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
common/totp.go (2)
14-22: Review security parameters for production readiness.The security constants look reasonable but should be verified:
BackupCodeCount = 4seems low for enterprise use (typically 8-10)MaxFailAttempts = 5is standardLockoutDuration = 300(5 minutes) is appropriateConsider making these configurable via environment variables for different deployment scenarios:
const ( - BackupCodeCount = 4 // 生成备用码数量 + defaultBackupCodeCount = 4 // 默认生成备用码数量 ) +func getBackupCodeCount() int { + return common.GetEnvOrDefault("BACKUP_CODE_COUNT", defaultBackupCodeCount) +}
122-128: Unused utility function.The
getEnvOrDefaultfunction is defined but not used in this file. Consider removing it or using it for configurable parameters.-// getEnvOrDefault 获取环境变量或默认值 -func getEnvOrDefault(key, defaultValue string) string { - if value, exists := os.LookupEnv(key); exists { - return value - } - return defaultValue -}controller/user.go (1)
67-89: Consider adding session expiration for pending 2FA sessionsThe implementation correctly handles 2FA verification flow. However, pending sessions should have an expiration time to prevent indefinite session persistence.
Consider adding a timestamp to track when the pending session was created:
// 检查是否启用2FA if model.IsTwoFAEnabled(user.Id) { // 设置pending session,等待2FA验证 session := sessions.Default(c) session.Set("pending_username", user.Username) session.Set("pending_user_id", user.Id) + session.Set("pending_timestamp", time.Now().Unix()) err := session.Save()Then validate the timestamp in the 2FA verification endpoint to ensure the session hasn't expired.
web/src/components/settings/TwoFASetting.js (2)
169-176: Improve clipboard API error handlingThe current implementation shows an error message but doesn't provide a fallback option for users.
const copyBackupCodes = () => { const codesText = backupCodes.join('\n'); navigator.clipboard.writeText(codesText).then(() => { showSuccess('备用码已复制到剪贴板'); }).catch(() => { - showError('复制失败,请手动复制'); + // Fallback for browsers that don't support clipboard API + const textArea = document.createElement('textarea'); + textArea.value = codesText; + textArea.style.position = 'fixed'; + textArea.style.left = '-999999px'; + document.body.appendChild(textArea); + textArea.select(); + try { + document.execCommand('copy'); + showSuccess('备用码已复制到剪贴板'); + } catch (err) { + showError('复制失败,请手动复制'); + } + document.body.removeChild(textArea); }); };
338-357: Consider requiring user confirmation before enabling 2FAUsers should confirm they've saved the backup codes before enabling 2FA to prevent lockouts.
Add a checkbox confirmation before the enable button:
<Form onSubmit={handleEnable2FA}> <Form.Input field="code" placeholder="请输入6位验证码" value={verificationCode} onChange={setVerificationCode} size="large" style={{ marginBottom: 16 }} maxLength={6} /> + <Checkbox style={{ marginBottom: 16 }}> + 我已保存备用码到安全的地方 + </Checkbox> <Button htmlType="submit" type="primary" loading={loading} size="large" block > 完成设置并启用两步验证 </Button> </Form>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
go.sumis excluded by!**/*.sumweb/bun.lockis excluded by!**/*.lock
📒 Files selected for processing (12)
common/totp.go(1 hunks)controller/twofa.go(1 hunks)controller/user.go(1 hunks)go.mod(2 hunks)model/main.go(2 hunks)model/twofa.go(1 hunks)router/api-router.go(3 hunks)web/package.json(1 hunks)web/src/components/auth/LoginForm.js(6 hunks)web/src/components/auth/TwoFAVerification.js(1 hunks)web/src/components/settings/PersonalSetting.js(2 hunks)web/src/components/settings/TwoFASetting.js(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
model/main.go (1)
model/twofa.go (2)
TwoFA(13-24)TwoFABackupCode(27-35)
controller/user.go (1)
model/twofa.go (1)
IsTwoFAEnabled(56-62)
web/src/components/settings/TwoFASetting.js (1)
web/src/helpers/utils.js (3)
showError(113-142)showWarning(144-146)showSuccess(148-150)
web/src/components/settings/PersonalSetting.js (1)
web/src/components/settings/TwoFASetting.js (1)
TwoFASetting(27-522)
common/totp.go (3)
model/twofa.go (1)
ValidateBackupCode(167-197)common/crypto.go (1)
Password2Hash(22-26)common/constants.go (1)
SystemName(14-14)
router/api-router.go (2)
middleware/rate-limit.go (1)
CriticalRateLimit(103-105)controller/twofa.go (8)
Verify2FALogin(398-480)Get2FAStatus(276-309)Setup2FA(33-134)Enable2FA(137-201)Disable2FA(204-273)RegenerateBackupCodes(312-395)Admin2FAStats(483-495)AdminDisable2FA(498-547)
🔇 Additional comments (31)
web/package.json (1)
24-24: Approve dependency addition –qrcode.reactv4.2.0 is current and secureThe
qrcode.reactdependency at version^4.2.0is the latest release and has no known vulnerabilities according to Snyk’s database. It correctly supports QR code generation for the frontend TOTP setup in your 2FA implementation.No further changes needed.
go.mod (1)
83-83: LGTM! Standard OTP library added.The
github.com/pquerna/otppackage is the standard and well-maintained Go library for TOTP functionality. Version 1.5.0 is appropriate for 2FA implementation.common/totp.go (9)
24-34: LGTM! Secure TOTP secret generation.The TOTP configuration follows RFC 6238 standards:
- 30-second period is standard
- 6-digit codes are user-friendly
- SHA1 algorithm is widely supported by authenticator apps
36-46: Good input validation and cleaning.The TOTP validation properly cleans input by removing spaces and validates the 6-digit format before calling the underlying library.
48-61: Secure backup code generation implementation.The function correctly generates multiple backup codes and handles errors appropriately. The approach of generating codes individually allows for proper error handling.
63-79: Strong random backup code generation.The implementation uses
crypto/randfor cryptographically secure random generation and includes proper character set validation. The XXXX-XXXX format improves usability.
81-97: Robust backup code validation.The validation function properly normalizes input (removes separators, converts to uppercase) and validates both length and character set. This prevents common input errors.
99-106: LGTM! Consistent backup code normalization.The normalization function ensures consistent formatting for storage and comparison.
108-112: Secure backup code hashing.Correctly uses the existing
Password2Hashfunction fromcommon/crypto.goto hash backup codes before storage, maintaining consistency with password handling.
130-145: Excellent numeric code validation.The function properly validates 6-digit numeric codes with clear error messages and input sanitization.
147-153: Well-formatted QR code URI generation.The function generates proper
otpauth://URIs following the Google Authenticator URI format specification. The account name formatting is user-friendly.model/main.go (2)
254-255: LGTM! Database migration properly updated.The new 2FA models are correctly added to the database migration. Both
TwoFAandTwoFABackupCodemodels are included to support the 2FA functionality.
282-283: LGTM! Fast migration path also updated.The concurrent migration function (
migrateDBFast) is also properly updated with the new 2FA models, ensuring consistency across both migration paths.web/src/components/settings/PersonalSetting.js (2)
39-39: LGTM! Correct import for 2FA component.The
TwoFASettingcomponent is properly imported from the settings directory.
1045-1046: LGTM! Well-positioned 2FA settings integration.The
TwoFASettingcomponent is appropriately placed in the security settings section between password management and the danger zone, providing a logical flow for security-related settings.web/src/components/auth/LoginForm.js (1)
167-172: LGTM! Well-integrated 2FA verification flowThe 2FA integration is properly implemented:
- Correctly handles the 2FA requirement response from the backend
- Clean modal implementation with appropriate callbacks
- Proper state management and user feedback
Also applies to: 292-305, 565-591
router/api-router.go (1)
47-47: LGTM! Well-structured 2FA routes with appropriate securityThe routing configuration properly implements:
- Critical rate limiting on the 2FA login verification endpoint
- Proper authentication middleware for user and admin routes
- Clear RESTful API design
Also applies to: 72-76, 91-92
controller/twofa.go (6)
137-201: LGTM!The Enable2FA function correctly validates the TOTP code and enables 2FA with proper error handling.
204-273: LGTM!The Disable2FA function properly validates authentication before allowing 2FA to be disabled, supporting both TOTP and backup codes.
276-309: LGTM!The Get2FAStatus function provides comprehensive status information with proper nil handling and error logging.
312-395: LGTM!The backup code regeneration properly validates TOTP authentication and securely generates new codes.
483-495: LGTM!Simple and effective implementation for retrieving 2FA statistics.
50-106: Logical error in 2FA record creation flowAfter deleting a disabled 2FA record and setting
existing = nilat line 56, the conditionif existing != nilat line 98 will always be false, making the update path unreachable. The entire block from lines 98-105 is dead code.Simplify the logic to always create a new record after deletion:
- // 创建或更新2FA记录(暂未启用) + // 创建2FA记录(暂未启用) twoFA := &model.TwoFA{ UserId: userId, Secret: key.Secret(), IsEnabled: false, } - if existing != nil { - // 更新现有记录 - twoFA.Id = existing.Id - err = twoFA.Update() - } else { - // 创建新记录 - err = twoFA.Create() - } + // 创建新记录 + err = twoFA.Create()Likely an incorrect or invalid review comment.
model/twofa.go (8)
13-24: LGTM!Well-structured 2FA model with appropriate security considerations for the secret field.
38-53: LGTM!Proper error handling that distinguishes between missing 2FA settings and actual database errors.
65-85: LGTM!The Create method properly validates uniqueness and user existence before creating 2FA settings.
96-108: LGTM!Appropriate use of hard deletion for security-sensitive 2FA data and associated backup codes.
118-128: LGTM!Proper implementation of failed attempt tracking with automatic lockout mechanism.
167-197: LGTM!Secure backup code validation with proper normalization, hash comparison, and one-time use enforcement.
229-255: LGTM!Comprehensive TOTP validation with lock checking, failure tracking, and usage updates.
292-315: LGTM!Clean implementation of 2FA statistics with proper percentage calculation and formatting.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
model/twofa.go (1)
293-317: Consider using a struct for the return value.While the current implementation works well, consider defining a struct for the statistics to improve type safety and documentation.
Add this struct definition near the top of the file:
// TwoFAStats represents 2FA usage statistics type TwoFAStats struct { TotalUsers int64 `json:"total_users"` EnabledUsers int64 `json:"enabled_users"` EnabledRate string `json:"enabled_rate"` }Then update the function:
-func GetTwoFAStats() (map[string]interface{}, error) { +func GetTwoFAStats() (*TwoFAStats, error) { var totalUsers, enabledUsers int64 // 总用户数 if err := DB.Model(&User{}).Count(&totalUsers).Error; err != nil { return nil, err } // 启用2FA的用户数 if err := DB.Model(&TwoFA{}).Where("is_enabled = true").Count(&enabledUsers).Error; err != nil { return nil, err } enabledRate := float64(0) if totalUsers > 0 { enabledRate = float64(enabledUsers) / float64(totalUsers) * 100 } - return map[string]interface{}{ - "total_users": totalUsers, - "enabled_users": enabledUsers, - "enabled_rate": fmt.Sprintf("%.1f%%", enabledRate), - }, nil + return &TwoFAStats{ + TotalUsers: totalUsers, + EnabledUsers: enabledUsers, + EnabledRate: fmt.Sprintf("%.1f%%", enabledRate), + }, nil }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (5)
common/totp.go(1 hunks)controller/twofa.go(1 hunks)go.mod(2 hunks)model/twofa.go(1 hunks)web/src/components/auth/TwoFAVerification.js(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- go.mod
- web/src/components/auth/TwoFAVerification.js
- common/totp.go
- controller/twofa.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
model/twofa.go (4)
model/main.go (1)
DB(63-63)common/totp.go (6)
MaxFailAttempts(20-20)LockoutDuration(21-21)HashBackupCode(109-112)ValidateBackupCode(82-97)NormalizeBackupCode(100-106)ValidateTOTPCode(37-46)common/crypto.go (1)
ValidatePasswordAndHash(28-31)common/logger.go (1)
SysError(55-58)
🔇 Additional comments (16)
model/twofa.go (16)
1-13: LGTM! Good implementation of the custom error.The package declaration and imports are well-organized. The custom error
ErrTwoFANotEnabledis properly defined as suggested in the previous review.
14-26: Well-designed struct with proper security considerations.The
TwoFAstruct is properly designed with:
- Correct use of
json:"-"tag for the Secret field to prevent exposure- Appropriate use of pointer types for optional timestamps
- Proper indexing and unique constraint on UserId
- Soft delete support
28-37: Secure backup code storage structure.The
TwoFABackupCodestruct properly stores hashed backup codes withjson:"-"tag to prevent exposure and includes usage tracking.
39-55: Good error handling and validation.The function properly validates input and distinguishes between "no 2FA configured" (returns nil) and actual errors.
57-64: Clean helper function for 2FA status check.Simple and effective implementation that gracefully handles errors.
66-87: Thorough validation before creation.The function properly validates:
- No existing 2FA settings for the user
- User exists in the database
Good defensive programming.
89-95: Appropriate use of GORM Save method.The function correctly validates the ID and uses
Save()to update all fields, which is suitable for this use case.
112-117: Clean implementation of failure reset.The function properly resets both the failure counter and lockout status.
119-130: Good use of configurable security parameters.The function properly uses constants from the common package (
MaxFailAttemptsandLockoutDuration) making the security policy configurable.
132-138: Correct lockout status check.The function properly handles the nil case and performs accurate time comparison.
168-199: Secure backup code validation with proper usage tracking.The function:
- Validates format before database lookup
- Uses normalized codes for consistent comparison
- Properly marks codes as used
- Returns generic error message for security
201-206: Clean implementation for counting unused backup codes.Simple and effective query with safe type conversion.
208-220: Proper use of custom error and clean disable logic.The function correctly uses the
ErrTwoFANotEnabledcustom error and delegates to the Delete method for cleanup.
222-228: Good security practice resetting counters on enable.The function properly resets failed attempts and lockout status when enabling 2FA.
230-257: Robust TOTP validation with proper usage tracking.The function:
- Correctly checks lockout status first
- Updates failure counters appropriately
- Logs but doesn't fail on update errors (good for auth flow)
- Updates usage timestamp on success
259-291: Consistent implementation with TOTP validation.The function follows the same pattern as TOTP validation, ensuring consistent behavior across authentication methods.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
model/twofa.go (3)
98-113: LGTM! Transaction ensures atomic deletion as suggested.The implementation properly uses a transaction to ensure both backup codes and 2FA settings are deleted atomically, addressing the previous review comment.
144-171: LGTM! Transaction ensures atomic backup code creation as suggested.The implementation properly uses a transaction to ensure backup codes are created atomically, preventing partial updates on errors as requested in the previous review.
265-296: Same error handling concern as ValidateTOTPAndUpdateUsage.This method has the same pattern of logging update errors without failing the operation.
Apply the same error handling strategy chosen for
ValidateTOTPAndUpdateUsageto maintain consistency.
🧹 Nitpick comments (1)
model/twofa.go (1)
174-204: Consider optimizing backup code validation for better performance.The current implementation loads all unused backup codes into memory. For users with many backup codes, this could be optimized.
Consider validating codes one at a time in the database to reduce memory usage:
- // 查找未使用的备用码 - var backupCodes []TwoFABackupCode - if err := DB.Where("user_id = ? AND is_used = false", userId).Find(&backupCodes).Error; err != nil { - return false, err - } - - // 验证备用码 - for _, bc := range backupCodes { - if common.ValidatePasswordAndHash(normalizedCode, bc.CodeHash) { - // 标记为已使用 - now := time.Now() - bc.IsUsed = true - bc.UsedAt = &now - - if err := DB.Save(&bc).Error; err != nil { - return false, err - } - - return true, nil - } - } + // 使用事务确保原子性 + var found bool + err := DB.Transaction(func(tx *gorm.DB) error { + var backupCodes []TwoFABackupCode + if err := tx.Where("user_id = ? AND is_used = false", userId).Find(&backupCodes).Error; err != nil { + return err + } + + for _, bc := range backupCodes { + if common.ValidatePasswordAndHash(normalizedCode, bc.CodeHash) { + now := time.Now() + if err := tx.Model(&bc).Updates(map[string]interface{}{ + "is_used": true, + "used_at": &now, + }).Error; err != nil { + return err + } + found = true + return nil + } + } + return nil + }) + + if err != nil { + return false, err + } + return found, nilThis also adds transaction support to ensure the code isn't used twice in concurrent requests.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
controller/twofa.go(1 hunks)model/twofa.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- controller/twofa.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
model/twofa.go (4)
model/main.go (1)
DB(63-63)common/totp.go (6)
MaxFailAttempts(20-20)LockoutDuration(21-21)HashBackupCode(109-112)ValidateBackupCode(82-97)NormalizeBackupCode(100-106)ValidateTOTPCode(37-46)common/crypto.go (1)
ValidatePasswordAndHash(28-31)common/logger.go (1)
SysError(55-58)
🔇 Additional comments (8)
model/twofa.go (8)
1-13: LGTM! Good implementation of the custom error.The custom error
ErrTwoFANotEnabledis properly defined as suggested in the previous review, improving error handling consistency.
15-26: LGTM! Well-designed struct with proper security considerations.The
TwoFAstruct is properly designed with:
- Secret field hidden from JSON serialization
- Appropriate use of soft deletes
- Good tracking of failed attempts and lockout state
29-37: LGTM! Secure backup code storage implementation.The
TwoFABackupCodestruct properly stores hashed backup codes and tracks their usage status, following security best practices.
40-55: LGTM! Clean error handling pattern.The function properly distinguishes between "2FA not configured" (returns nil) and actual database errors, which is a good pattern for optional settings.
67-87: LGTM! Robust validation before 2FA creation.The method properly validates:
- No duplicate 2FA settings for the user
- User exists before creating 2FA record
This prevents data integrity issues.
123-133: LGTM! Automatic lockout mechanism implemented correctly.The method properly implements the lockout logic using configurable constants from the common package.
214-225: LGTM! Proper use of custom error.The function correctly uses the
ErrTwoFANotEnabledcustom error and leverages the transactionalDeletemethod.
299-322: LGTM! Well-implemented statistics function.The function properly handles division by zero and provides useful 2FA adoption metrics for administrators.
| func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { | ||
| // 检查是否被锁定 | ||
| if t.IsLocked() { | ||
| return false, fmt.Errorf("账户已被锁定,请在%v后重试", t.LockedUntil.Format("2006-01-02 15:04:05")) | ||
| } | ||
|
|
||
| // 验证TOTP码 | ||
| if !common.ValidateTOTPCode(t.Secret, code) { | ||
| // 增加失败次数 | ||
| if err := t.IncrementFailedAttempts(); err != nil { | ||
| common.SysError("更新2FA失败次数失败: " + err.Error()) | ||
| } | ||
| return false, nil | ||
| } | ||
|
|
||
| // 验证成功,重置失败次数并更新最后使用时间 | ||
| now := time.Now() | ||
| t.FailedAttempts = 0 | ||
| t.LockedUntil = nil | ||
| t.LastUsedAt = &now | ||
|
|
||
| if err := t.Update(); err != nil { | ||
| common.SysError("更新2FA使用记录失败: " + err.Error()) | ||
| } | ||
|
|
||
| return true, nil | ||
| } |
There was a problem hiding this comment.
Consider returning update errors instead of just logging them.
The current implementation logs update errors but still returns success. This could lead to security issues if the failed attempts counter isn't properly updated.
Consider this approach:
if err := t.Update(); err != nil {
- common.SysError("更新2FA使用记录失败: " + err.Error())
+ common.SysError("更新2FA使用记录失败: " + err.Error())
+ // Consider returning error to ensure consistency
+ return false, fmt.Errorf("验证成功但更新记录失败: %w", err)
}Alternatively, use a transaction to ensure both validation and update succeed atomically.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { | |
| // 检查是否被锁定 | |
| if t.IsLocked() { | |
| return false, fmt.Errorf("账户已被锁定,请在%v后重试", t.LockedUntil.Format("2006-01-02 15:04:05")) | |
| } | |
| // 验证TOTP码 | |
| if !common.ValidateTOTPCode(t.Secret, code) { | |
| // 增加失败次数 | |
| if err := t.IncrementFailedAttempts(); err != nil { | |
| common.SysError("更新2FA失败次数失败: " + err.Error()) | |
| } | |
| return false, nil | |
| } | |
| // 验证成功,重置失败次数并更新最后使用时间 | |
| now := time.Now() | |
| t.FailedAttempts = 0 | |
| t.LockedUntil = nil | |
| t.LastUsedAt = &now | |
| if err := t.Update(); err != nil { | |
| common.SysError("更新2FA使用记录失败: " + err.Error()) | |
| } | |
| return true, nil | |
| } | |
| func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { | |
| // 检查是否被锁定 | |
| if t.IsLocked() { | |
| return false, fmt.Errorf("账户已被锁定,请在%v后重试", t.LockedUntil.Format("2006-01-02 15:04:05")) | |
| } | |
| // 验证TOTP码 | |
| if !common.ValidateTOTPCode(t.Secret, code) { | |
| // 增加失败次数 | |
| if err := t.IncrementFailedAttempts(); err != nil { | |
| common.SysError("更新2FA失败次数失败: " + err.Error()) | |
| } | |
| return false, nil | |
| } | |
| // 验证成功,重置失败次数并更新最后使用时间 | |
| now := time.Now() | |
| t.FailedAttempts = 0 | |
| t.LockedUntil = nil | |
| t.LastUsedAt = &now | |
| if err := t.Update(); err != nil { | |
| common.SysError("更新2FA使用记录失败: " + err.Error()) | |
| // Consider returning error to ensure consistency | |
| return false, fmt.Errorf("验证成功但更新记录失败: %w", err) | |
| } | |
| return true, nil | |
| } |
🤖 Prompt for AI Agents
In model/twofa.go lines 236 to 262, the method ValidateTOTPAndUpdateUsage logs
errors from updating usage or incrementing failed attempts but still returns
success, which can cause security issues. Modify the function to return these
update errors instead of just logging them, so the caller is aware of any
failure in updating the state. Ensure that if IncrementFailedAttempts or Update
returns an error, the function returns false with that error, preventing false
success indications. Optionally, consider wrapping the validation and update
steps in a transaction to guarantee atomicity.
feat: implement two-factor authentication (2FA) support with user login and settings integration
feat: implement two-factor authentication (2FA) support with user login and settings integration
feat: implement two-factor authentication (2FA) support with user login and settings integration
Summary by CodeRabbit
New Features
User Interface
Dependencies