From 4ae021e0df7bec0f5db888e55cd469e66e977d49 Mon Sep 17 00:00:00 2001 From: Chris Li <c58li@uwaterloo.ca> Date: Wed, 1 Feb 2023 09:53:30 -0500 Subject: [PATCH] Allow user login with email. --- core/api/auth.py | 1 + core/serializers/login.py | 6 ++++++ core/serializers/register.py | 7 +++++-- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/core/api/auth.py b/core/api/auth.py index 218450d..56120f1 100644 --- a/core/api/auth.py +++ b/core/api/auth.py @@ -2,6 +2,7 @@ from django.shortcuts import render from rest_framework import generics from rest_framework.response import Response from knox.models import AuthToken +from django.contrib.auth.backends import AllowAllUsersModelBackend from core.serializers.login import LoginSerializer from core.serializers.register import RegisterSerializer diff --git a/core/serializers/login.py b/core/serializers/login.py index f7d9ed2..9c5f3fe 100644 --- a/core/serializers/login.py +++ b/core/serializers/login.py @@ -1,4 +1,5 @@ from django.contrib.auth import authenticate +from django.contrib.auth.models import User from rest_framework import serializers @@ -7,6 +8,11 @@ class LoginSerializer(serializers.Serializer): password = serializers.CharField() def validate(self, data): + usersByEmail = User.objects.filter(email=data['username'].lower()) + if len(usersByEmail) != 0: + username = usersByEmail[0].username + data['username'] = username + user = authenticate(**data) if not user: raise serializers.ValidationError('Invalid Credentials.') diff --git a/core/serializers/register.py b/core/serializers/register.py index 72400c0..470dd19 100644 --- a/core/serializers/register.py +++ b/core/serializers/register.py @@ -1,8 +1,6 @@ from django.contrib.auth.models import User from rest_framework import serializers -from core.models.profile import Profile - class RegisterSerializer(serializers.ModelSerializer): class Meta: @@ -17,3 +15,8 @@ class RegisterSerializer(serializers.ModelSerializer): validated_data['password'] ) return user + + def validate(self, data): + if len(User.objects.filter(email=data['email'])) != 0: + raise serializers.ValidationError({"email": "A user with that email already exists."}) + return data -- GitLab