Skip to content

Commit

Permalink
autheitcation through uisername and email both
Browse files Browse the repository at this point in the history
  • Loading branch information
Abdul-Muqadim-Arbisoft committed Aug 29, 2023
1 parent c07497f commit c95da3e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
16 changes: 10 additions & 6 deletions user/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@ class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, email=None, password=None, **kwargs):
UserModel = get_user_model()

# Use email if it's provided; otherwise, fallback to username
email = email or username
# Prioritize email if provided; otherwise, use username
lookup_value = email or username

print(f"Trying to authenticate: {email=}, {password=}")
print(f"Trying to authenticate: {lookup_value=}, {password=}")
try:
user = UserModel.objects.get(email=email)
print("Found a user with the provided email")
if "@" in lookup_value:
user = UserModel.objects.get(email=lookup_value)
print("Found a user with the provided email")
else:
user = UserModel.objects.get(username=lookup_value)
print("Found a user with the provided username")
except UserModel.DoesNotExist:
print("No user found with the provided email")
print("No user found with the provided email/username")
return None
else:
if user.check_password(password):
Expand Down
4 changes: 2 additions & 2 deletions user/templates/user/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<h2>Login</h2>
<form method="post">
{% csrf_token %} <!-- CSRF token for security -->
<label for="email">Email:</label>
<input type="email" name="email" required><br>
<label for="email_or_username">Email OR Username:</label>
<input type="email_or_username" name="email_or_username" required><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
Expand Down
9 changes: 7 additions & 2 deletions user/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,20 @@ def post(request):

class LoginView(View):
"""View to handle user login."""

@staticmethod
def get(request):
return render(request, LOGIN_TEMPLATE)

@staticmethod
def post(request):
email = request.POST['email']
# Retrieve both email and username from the request.
# One of them will be None, and that's okay.
lookup_value = request.POST.get('email_or_username') # Adjust your frontend to have a unified input
password = request.POST['password']
user = authenticate(request, email=email, password=password)

user = authenticate(request, email=lookup_value, username=lookup_value, password=password)

if user:
login(request, user)
return redirect('home')
Expand Down

0 comments on commit c95da3e

Please sign in to comment.