-
-
Notifications
You must be signed in to change notification settings - Fork 313
fix 4056 Enable username-or-email login via allauth configuration and template updates #5329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
fix 4056 Enable username-or-email login via allauth configuration and template updates #5329
Conversation
|
π Hi @armanraymagit! This pull request needs a peer review before it can be merged. Please request a review from a team member who is not:
Once a valid peer review is submitted, this check will pass automatically. Thank you! |
WalkthroughAdds Allauth settings for username-or-email login and unique emails, loads environment variables in a new manage.py main(), updates login template to show non-field errors and relabel the login field, adds extensive login tests, and introduces a management command to deduplicate EmailAddress records. Changes
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~30 minutes
Pre-merge checks and finishing touchesβ Failed checks (1 warning)
β Passed checks (4 passed)
β¨ Finishing touches
π§ͺ Generate unit tests (beta)
π Recent review detailsConfiguration used: Organization UI Review profile: CHILL Plan: Pro Knowledge base: Disabled due to π Files selected for processing (4)
β Files skipped from review due to trivial changes (2)
β° Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
π Additional comments (5)
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. Comment |
π Monthly LeaderboardHi @armanraymagit! Here's how you rank for December 2025:
Leaderboard based on contributions in December 2025. Keep up the great work! π |
There was a problem hiding this comment.
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)
manage.py (1)
6-15: Consider moving the dotenv import to top-level.The import of
load_dotenvis inside themain()function. Per PEP 8, imports should typically be at the top of the file unless there's a specific reason (e.g., avoiding circular imports or optional dependencies).Apply this diff to move the import to the top:
#!/usr/bin/env python import os import sys +from dotenv import load_dotenv def main(): - from dotenv import load_dotenv - load_dotenv() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blt.settings")
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
π Files selected for processing (3)
blt/settings.py(1 hunks)manage.py(1 hunks)website/templates/account/login.html(3 hunks)
β° Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Run Tests
- GitHub Check: docker-test
π Additional comments (4)
manage.py (1)
18-19: LGTM!The refactoring to call
main()within theif __name__ == "__main__":guard is clean and follows Python best practices.blt/settings.py (1)
365-372: LGTM!The django-allauth configuration is well-structured:
- Requires both username and email during signup
- Enforces email uniqueness
- Requires mandatory email verification
This configuration aligns with the PR objectives and provides a secure authentication setup.
website/templates/account/login.html (2)
5-6: LGTM!Splitting the load tags into separate lines is fine and may improve readability, though functionally equivalent to the single-line version.
71-71: LGTM!The label change to "Username or Email" correctly reflects the
ACCOUNT_AUTHENTICATION_METHOD = "username_email"configuration in settings.py and improves user clarity.
β Pre-commit checks failedThe pre-commit hooks found issues that need to be fixed. Please run the following commands locally to fix them: # Install pre-commit if you haven't already
pip install pre-commit
# Run pre-commit on all files
pre-commit run --all-files
# Or run pre-commit on staged files only
pre-commit runAfter running these commands, the pre-commit hooks will automatically fix most issues. π‘ Tip: You can set up pre-commit to run automatically on every commit by running: pre-commit installPre-commit outputFor more information, see the pre-commit documentation. |
blt/settings.py
Outdated
| "NAME": ":memory:", | ||
| } | ||
|
|
||
| ACCOUNT_AUTHENTICATION_METHOD = "username_email" |
This comment was marked as outdated.
This comment was marked as outdated.
Sorry, something went wrong.
|
@coderabbitai please run a full, endβtoβend review of this PR for completeness. Focus on:
|
|
Tip For best results, initiate chat on the files or code changes. π§© Analysis chainπ Script executed: Length of output: 180 π Script executed: Length of output: 15833 π Script executed: Length of output: 3964 π Script executed: Length of output: 1446 π Script executed: Length of output: 5160 π Script executed: Length of output: 8613 π Script executed: Length of output: 1184 π Script executed: Length of output: 3024 π Script executed: Length of output: 2269 π Script executed: Length of output: 7220 π Script executed: Length of output: 1247 π Script executed: Length of output: 46 π Script executed: Length of output: 89 π Script executed: Length of output: 243 π Script executed: Length of output: 1026 π Script executed: Length of output: 169 π Script executed: Length of output: 691 π Script executed: Length of output: 553 π Script executed: Length of output: 3576 π Script executed: Length of output: 3261 π Script executed: Length of output: 111 π Script executed: Length of output: 728 @arnavkirti, I've completed a comprehensive end-to-end review of this PR. Here's my detailed analysis: β Login Flow & Error DisplayThe login flow changes are correctly implemented:
π Critical Issue Found - Template Formatting Error: Line 60 in <strong class="font-bold">Error:</strong>
+ <span class="block sm:inline mt-1">{{ form.non_field_errors|striptags }}</span>Fix required: - + <span class="block sm:inline mt-1">{{ form.non_field_errors|striptags }}</span>
+ <span class="block sm:inline mt-1">{{ form.non_field_errors|striptags }}</span>β Django-allauth Settings CompatibilityThe allauth configuration is fully compatible with version 65.13.1:
ACCOUNT_UNIQUE_EMAIL = True enforces uniqueness at the allauth level, not as a database constraint. This means:
Recommendation: Before deploying, run a query to check for duplicate emails: from django.contrib.auth.models import User
from django.db.models import Count
duplicates = User.objects.values('email').annotate(count=Count('email')).filter(count__gt=1, email__isnull=False).exclude(email='')β Dotenv Loading Architecture - Safe for All EnvironmentsThe dotenv loading in Development (local):
Production/Docker:
Why this is correct:
This follows the 12-factor app methodology correctly.
|
| Aspect | Status | Notes |
|---|---|---|
| Login flow (username/email) | β Correct | Properly configured |
| Allauth settings compatibility | β Compatible | Version 65.13.1 |
| Error display UI | Remove + character on line 60 |
|
| Dotenv architecture | β Safe | Correct for all environments |
| Test coverage | β Missing | Add error display tests |
| Email uniqueness | Check for existing duplicates |
π― Action Items
- Fix the template formatting - Remove the
+character from line 60 - Add test coverage for error message display and email-based login
- Verify no duplicate emails exist in the database before deployment
- Consider adding a data migration or management command to clean up duplicates if found
The overall approach is sound and the architecture choices are correct. Once the formatting issue is fixed and tests are added, this will be ready to merge! π
arnavkirti
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please address the issues pointed out by coderabbitai.
There was a problem hiding this comment.
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)
website/tests/test_deduplicate_emails.py (1)
53-53: QuerySet evaluated multiple times β cache to reduce DB round-trips.
delete_email_addressesis iterated three times (lines 61, 86, 99) and then deleted (line 120), causing 4 separate DB queries per duplicate email. Convert to a list once:π Suggested fix:
- delete_email_addresses = email_addresses.exclude(pk=keep_email_address.pk) + delete_email_addresses = list(email_addresses.exclude(pk=keep_email_address.pk))Then update line 120 to delete by PKs:
- deleted_count, _ = delete_email_addresses.delete() + delete_pks = [ea.pk for ea in delete_email_addresses] + deleted_count, _ = EmailAddress.objects.filter(pk__in=delete_pks).delete()
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
π Files selected for processing (1)
website/tests/test_deduplicate_emails.py(1 hunks)
β° Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Run Tests
- GitHub Check: Analyze (actions)
- GitHub Check: docker-test
π Additional comments (1)
website/tests/test_deduplicate_emails.py (1)
17-128: Core deduplication logic is sound.The ordering strategy (verified β primary β oldest pk), merging of
verified/primaryflags, and atomic transaction wrapper are well-designed. The edge case handling for orphaned emails (no user) and primary demotion is thorough.One minor consistency note: lines 107 and 115 use
keep_email_address.userwhile earlier code (line 72) assignsuser_id. This works but incurs an extra DB fetch; consider usinguser_id=keep_email_address.user_idin the filter for consistency.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
β»οΈ Duplicate comments (1)
website/management/commands/deduplicate_emails.py (1)
34-36: Email addresses logged directly β potential PII compliance concern.Raw email addresses are output throughout this command (lines 36, 46, 68, 77, 89, 102, 123). If stdout is captured to logs in production, this may violate GDPR/CCPA. Consider masking emails or logging only record IDs.
π§Ή Nitpick comments (2)
website/management/commands/deduplicate_emails.py (2)
1-9: Remove unusedloggeror use it consistently.The
loggeris instantiated but never used; all output goes throughself.stdout.write. Either remove the unused import and variable, or use the logger for structured logging alongside stdout messages.π Remove unused logger:
-import logging - from allauth.account.models import EmailAddress from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db import models, transaction -logger = logging.getLogger(__name__) User = get_user_model()
34-34: Consider per-email atomic blocks for partial progress.The current design wraps all processing in a single transaction. If an error occurs on the last email, all prior work is rolled back. For large datasets, consider per-email atomic blocks to allow partial progress and more accurate success/failure reporting.
π Per-email atomic blocks:
-with transaction.atomic(): - for email in duplicate_emails: +for email in duplicate_emails: + try: + with transaction.atomic(): # ... existing processing logic ... + except Exception as e: + self.stdout.write( + self.style.ERROR(f'Failed to process "{email}": {e}') + ) + continue
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
π Files selected for processing (1)
website/management/commands/deduplicate_emails.py(1 hunks)
β° Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Run Tests
- GitHub Check: docker-test
π Additional comments (3)
website/management/commands/deduplicate_emails.py (3)
38-53: LGTM β sensible selection criteria.The ordering by
(-verified, -primary, pk)correctly prioritizes verified and primary addresses, falling back to the oldest record. This is a reasonable strategy for choosing the canonical email.
55-82: Good defensive handling for orphaned email records.The fallback logic to find a user from duplicates and the skip-on-failure path prevents data corruption when encountering EmailAddress records without associated users.
84-117: Verified/primary merging logic is sound.The flag propagation correctly preserves verification status from any duplicate and properly demotes other primary addresses for the same user before promotion.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
π Files selected for processing (1)
website/management/commands/deduplicate_emails.py(1 hunks)
β° Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Run Tests
- GitHub Check: docker-test
π Additional comments (4)
website/management/commands/deduplicate_emails.py (4)
13-24: LGTM β PII masking implementation is solid.The
mask_emailhelper correctly addresses the PII logging concern from previous reviews. Edge cases (empty string, missing @, single-character local parts) are handled appropriately.
37-44: LGTM β Duplicate detection correctly handles case-insensitive emails.The query properly uses
Lower("email")to normalize case before grouping, ensuring "[email protected]" and "[email protected]" are detected as duplicates. This addresses the case-sensitivity concern from previous reviews.
52-52: Transaction wraps entire command, not individual emails.The
transaction.atomic()at line 52 ensures the entire command's changes are atomic β either all emails are deduplicated successfully or none are (on unhandled exceptions). However,continuestatements (lines 101, 152, 162) don't rollback; modifications made before skipping (e.g., user assignment at line 92) remain in the transaction and commit if the command completes.This is appropriate for maintaining consistency across the full deduplication run, but it means the ordering of checks is critical to avoid partial modifications when skipping problematic emails.
164-171: LGTM β Deletion and logging are clean.The deletion logic correctly uses the
delete_email_addressesqueryset (excludes keeper), captures the deletion count, and logs a clear success message with masked email for PII protection.
β Actions performedInitiated docstring generation; will generate only if new commits exist. |
|
Note Docstrings generation - SUCCESS |
Docstrings generation was requested by @armanraymagit. * #5329 (comment) The following files were modified: * `manage.py` * `website/management/commands/deduplicate_emails.py` * `website/tests/test_login.py`
Fixes #4056
Summary by CodeRabbit
New Features
Tests
Chores
Config
βοΈ Tip: You can customize this high-level summary in your review settings.