Skip to content

feat: implement two-factor authentication (2FA) support with user login and settings integration - #1487

Merged
Calcium-Ion merged 3 commits into
QuantumNous:alphafrom
seefs001:feature/2fa
Aug 4, 2025
Merged

Calcium-Ion merged 3 commits into
QuantumNous:alphafrom
seefs001:feature/2fa

Conversation

@seefs001

@seefs001 seefs001 commented Aug 2, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive two-factor authentication (2FA) support, including setup, enable/disable, backup code management, and enforcement during login.
    • Added user and admin APIs for managing 2FA status, backup codes, and usage statistics.
    • Integrated QR code generation for easy authenticator app setup.
    • Implemented backup code generation, validation, regeneration, and usage tracking for account recovery.
  • User Interface

    • Enhanced login flow with 2FA verification modal requiring authenticator or backup codes.
    • Added 2FA management components in personal settings with modals for setup, enablement, disablement, and backup code regeneration.
    • Provided user feedback via modals, notifications, and copy-to-clipboard features for backup codes.
  • Dependencies

    • Added dependencies for QR code rendering and TOTP generation/validation.

@coderabbitai

coderabbitai Bot commented Aug 2, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This 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

Cohort / File(s) Change Summary
TOTP & Backup Code Utilities
common/totp.go
Implements TOTP secret generation, code validation, backup code generation/validation, normalization, hashing, and QR code data utilities for 2FA.
2FA Controller Logic
controller/twofa.go
Adds Gin controller endpoints for 2FA setup, enable/disable, status, backup code regeneration, login verification, and admin 2FA management with request/response types.
Login Flow Update
controller/user.go
Modifies login to check for 2FA; if enabled, sets a pending session and prompts for 2FA verification before completing login.
2FA Database Models
model/twofa.go
Introduces TwoFA and TwoFABackupCode models with CRUD, validation, usage tracking, lockout logic, and admin stats aggregation for 2FA.
Database Migration Update
model/main.go
Updates migration functions to include new 2FA-related models.
API Route Registration
router/api-router.go
Registers new user and admin endpoints for 2FA management and login verification in the API router.
Dependency Additions
go.mod, web/package.json
Adds backend dependencies for TOTP and QR code generation; adds frontend dependency for QR code rendering.
Login Form 2FA Integration
web/src/components/auth/LoginForm.js
Enhances login form to detect 2FA requirement, show a modal, and handle 2FA completion before finalizing login.
2FA Verification Component
web/src/components/auth/TwoFAVerification.js
New React component for entering and verifying TOTP or backup code during login, with modal/card UI, API calls, and error handling.
Personal Settings Integration
web/src/components/settings/PersonalSetting.js
Adds the new 2FA settings component to the personal settings UI.
2FA Settings Component
web/src/components/settings/TwoFASetting.js
New React component for managing 2FA: setup, enable/disable, backup code regeneration, QR code display, and status overview.

Sequence Diagram(s)

2FA-Enabled Login Flow

sequenceDiagram
    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
Loading

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • Calcium-Ion
  • creamlike1024

Poem

A hop, a skip, a secret code,
Now double locks secure the road.
QR flashes, backup stashes,
Rabbits cheer as danger passes!
Two steps to keep the burrow tight—
Reviewers, check each byte tonight!
🐇🔐✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 = 4 seems low for enterprise use (typically 8-10)
  • MaxFailAttempts = 5 is standard
  • LockoutDuration = 300 (5 minutes) is appropriate

Consider 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 getEnvOrDefault function 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 sessions

The 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 handling

The 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 2FA

Users 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

📥 Commits

Reviewing files that changed from the base of the PR and between e6c8790 and c784a70.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • web/bun.lock is 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.react v4.2.0 is current and secure

The qrcode.react dependency at version ^4.2.0 is 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/otp package 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/rand for 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 Password2Hash function from common/crypto.go to 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 TwoFA and TwoFABackupCode models 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 TwoFASetting component is properly imported from the settings directory.


1045-1046: LGTM! Well-positioned 2FA settings integration.

The TwoFASetting component 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 flow

The 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 security

The 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 flow

After deleting a disabled 2FA record and setting existing = nil at line 56, the condition if existing != nil at 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.

Comment thread common/totp.go Resolved
Comment thread controller/twofa.go Resolved
Comment thread controller/twofa.go Resolved
Comment thread go.mod Resolved
Comment thread model/twofa.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c784a70 and d85eeab.

⛔ Files ignored due to path filters (1)
  • go.sum is 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 ErrTwoFANotEnabled is properly defined as suggested in the previous review.


14-26: Well-designed struct with proper security considerations.

The TwoFA struct 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 TwoFABackupCode struct properly stores hashed backup codes with json:"-" 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:

  1. No existing 2FA settings for the user
  2. 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 (MaxFailAttempts and LockoutDuration) 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 ErrTwoFANotEnabled custom 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.

Comment thread model/twofa.go Resolved
Comment thread model/twofa.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ValidateTOTPAndUpdateUsage to 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, nil

This 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

📥 Commits

Reviewing files that changed from the base of the PR and between d85eeab and 398ae71.

📒 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 ErrTwoFANotEnabled is properly defined as suggested in the previous review, improving error handling consistency.


15-26: LGTM! Well-designed struct with proper security considerations.

The TwoFA struct 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 TwoFABackupCode struct 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:

  1. No duplicate 2FA settings for the user
  2. 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 ErrTwoFANotEnabled custom error and leverages the transactional Delete method.


299-322: LGTM! Well-implemented statistics function.

The function properly handles division by zero and provides useful 2FA adoption metrics for administrators.

Comment thread model/twofa.go
Comment on lines +236 to +262
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
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.

@Calcium-Ion
Calcium-Ion merged commit 9c079d0 into QuantumNous:alpha Aug 4, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Sep 29, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
feat: implement two-factor authentication (2FA) support with user login and settings integration
@coderabbitai coderabbitai Bot mentioned this pull request Jun 27, 2026
11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
feat: implement two-factor authentication (2FA) support with user login and settings integration
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
feat: implement two-factor authentication (2FA) support with user login and settings integration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants