Skip to content

Add reset password functionality #34

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

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions sigma/authentication/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,37 @@ def to_representation(self, instance):
return {"access_token": str(refresh.access_token), "user": ProfileSerializer(instance).data}


class ResetPasswordSerializer(serializers.Serializer):
email = serializers.EmailField(write_only=True)
new_password = serializers.CharField(write_only=True)

def validate_email(self, value):
"""This is for validating email"""

user = User.objects.filter(email=value).first()

if user is None:
raise serializers.ValidationError("User doesn't exist", code="Not Found")

return value

def validate_new_password(self, value):
"""This is for validating new password"""

user = self.context["request"].user
Copy link
Collaborator

Choose a reason for hiding this comment

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

I doubt this is possible, since the user isn't authenticated


if user.check_password(value):
raise serializers.ValidationError(
"New password can't be same as Old password", code="Invalid Password"
)
try:
password_validator(value)
except ValidationError as err:
raise serializers.ValidationError(err.messages, code="Invalid Password")

return value


class ChangePasswordSerializer(serializers.Serializer):
old_password = serializers.CharField(write_only=True)
new_password = serializers.CharField(write_only=True)
Expand Down
14 changes: 10 additions & 4 deletions sigma/authentication/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from django.urls import path

from sigma.authentication.views import ChangePasswordAPIView, LoginInAPIView, RegisterAdminAPIView
from sigma.authentication.views import (
ChangePasswordAPIView,
LoginInAPIView,
RegisterAdminAPIView,
ResetPasswordAPIView,
)

app_name = "authentication"

urlpatterns = [
path("register/admin/", RegisterAdminAPIView.as_view(), name="register_admin"),
path("login/", LoginInAPIView.as_view(), name="login"),
path("password/change/", ChangePasswordAPIView.as_view(), name="change_password"),
path("register/admin", RegisterAdminAPIView.as_view(), name="register_admin"),
path("login", LoginInAPIView.as_view(), name="login"),
path("password/change", ChangePasswordAPIView.as_view(), name="change_password"),
path("password/reset", ResetPasswordAPIView.as_view(), name="reset_password"),
]
19 changes: 18 additions & 1 deletion sigma/authentication/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
ChangePasswordSerializer,
LogInSerializer,
RegisterUserSerializer,
ResetPasswordSerializer,
)


Expand All @@ -31,13 +32,29 @@ def post(self, request, *args, **kwargs):
return Response(serializer.data)


class ResetPasswordAPIView(generics.GenericAPIView):
serializer_class = ResetPasswordSerializer
permission_classes = (permissions.AllowAny,)

def put(self, request, *args, **kwargs):
user = self.request.user
Copy link
Collaborator

Choose a reason for hiding this comment

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

I doubt this will work too, as the user is unauthenticated


serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)

user.set_password(serializer.validated_data["new_password"])
user.save(update_fields=["password"])

return Response({"message": "Password Successfully updated"}, status=status.HTTP_200_OK)


class ChangePasswordAPIView(generics.GenericAPIView):
serializer_class = ChangePasswordSerializer
permission_classes = [
permissions.IsAuthenticated,
]

def post(self, request, *args, **kwargs):
def put(self, request, *args, **kwargs):
user = self.request.user

serializer = self.get_serializer(data=request.data)
Expand Down
41 changes: 38 additions & 3 deletions sigma/quiz/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
# Generated by Django 4.2 on 2024-06-18 19:23
# Generated by Django 4.2 on 2024-07-20 12:39

import uuid

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = []
dependencies = [
("school", "0001_initial"),
]

operations = [
migrations.CreateModel(
Expand All @@ -25,7 +28,39 @@ class Migration(migrations.Migration):
("updated_at", models.DateTimeField(auto_now=True)),
("title", models.CharField(max_length=100)),
("description", models.TextField(blank=True, max_length=255, null=True)),
("date", models.DateField()),
("date", models.DateField(unique=True)),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="SchoolRegisteredForQuiz",
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4, editable=False, primary_key=True, serialize=False
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"quiz",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="schoolquiz",
to="quiz.quiz",
),
),
(
"school",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="registered_school",
to="school.school",
),
),
],
options={
"abstract": False,
Expand Down
18 changes: 0 additions & 18 deletions sigma/quiz/migrations/0002_alter_quiz_date.py

This file was deleted.

49 changes: 0 additions & 49 deletions sigma/quiz/migrations/0003_schoolregisteredforquiz.py

This file was deleted.

37 changes: 35 additions & 2 deletions sigma/round/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 4.2 on 2024-06-19 13:36
# Generated by Django 4.2 on 2024-07-20 12:39

import uuid

Expand All @@ -11,7 +11,8 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
("quiz", "0002_alter_quiz_date"),
("quiz", "0001_initial"),
("school", "0001_initial"),
]

operations = [
Expand Down Expand Up @@ -42,6 +43,38 @@ class Migration(migrations.Migration):
),
],
),
migrations.CreateModel(
name="RoundForSchool",
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4, editable=False, primary_key=True, serialize=False
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"round",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="round_for_schools",
to="round.round",
),
),
(
"school",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="rounds_for_school",
to="school.school",
),
),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="Question",
fields=[
Expand Down
49 changes: 0 additions & 49 deletions sigma/round/migrations/0002_roundforschool.py

This file was deleted.

2 changes: 1 addition & 1 deletion sigma/school/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 4.2 on 2024-06-16 12:25
# Generated by Django 4.2 on 2024-07-20 12:39

import uuid

Expand Down
2 changes: 1 addition & 1 deletion sigma/users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 4.2 on 2024-06-16 12:25
# Generated by Django 4.2 on 2024-07-20 12:39

import uuid

Expand Down
37 changes: 37 additions & 0 deletions tests/authentication/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
ChangePasswordSerializer,
LogInSerializer,
RegisterUserSerializer,
ResetPasswordSerializer,
)
from tests.authentication.factories import User, UserModelFactory

Expand Down Expand Up @@ -122,6 +123,42 @@ def test_invalid_email(self):
self.assertIn("email", context.exception.detail)


class ResetPasswordSerializerTests(APITestCase):

def setUp(self):
self.user = UserModelFactory(email="[email protected]")
self.user.set_password("old_password")
self.user.save()

def test_error_raised_for_short_length_of_password(self):
"""Test error raised for short length of password"""

request = MagicMock()
request.user = self.user

data = {"old_password": "old_password", "new_password": "new"}
serializer = ResetPasswordSerializer(data=data, context={"request": request})
self.assertFalse(serializer.is_valid())
self.assertEqual(
serializer.errors["new_password"][0],
ErrorDetail(
string="This password is too short. It must contain at least 8 characters.",
code="Invalid Password",
),
)

def test_error_not_raised_when_valid_data_are_provided(self):
"""Test user password changed when valid data are provided"""

request = MagicMock()
request.user = self.user

data = {"email": request.user.email, "new_password": "new_password"}

serializer = ResetPasswordSerializer(data=data, context={"request": request})
self.assertTrue(serializer.is_valid())


class ChangePasswordSerializerTests(APITestCase):

def setUp(self):
Expand Down
Loading
Loading