Skip to content
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

fix: Add user to AuthFactor serializer #375

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
25 changes: 24 additions & 1 deletion src/api/auth/token_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,28 @@ def _get_audience(self, user_or_pk: t.Union[User, t.Any]):
pk = user_or_pk.pk if isinstance(user_or_pk, User) else user_or_pk
return f"user:{pk}"

def make_token(self, user_or_pk: t.Union[User, t.Any]):
def make_token(self, user_or_pk: t.Union[User, t.Any], new_email: str = ""):
"""Generate a token used to verify user's email address.

https://pyjwt.readthedocs.io/en/stable/usage.html

Args:
user: The user to generate a token for.
new_email: The user's new email address to be verified, if updating
it.

Returns:
A token used to verify user's email address.
"""
print("MAKING TOKEN")
return jwt.encode(
payload={
"exp": (
timezone.now()
+ timedelta(seconds=settings.EMAIL_VERIFICATION_TIMEOUT)
),
"aud": [self._get_audience(user_or_pk)],
"new_email": new_email,
},
key=settings.SECRET_KEY,
algorithm="HS256",
Expand Down Expand Up @@ -78,5 +82,24 @@ def check_token(self, user_or_pk: t.Union[User, t.Any], token: str):

return True

def get_new_email(self, user_or_pk: t.Union[User, t.Any], token: str):
"""Retrieve token's new_email value.

Args:
user: The user to check.
token: The token to check.

Returns:
The token's new_email value.
"""
decoded_jwt = jwt.decode(
jwt=token,
key=settings.SECRET_KEY,
audience=self._get_audience(user_or_pk),
algorithms=["HS256"],
)

return decoded_jwt["new_email"]


email_verification_token_generator = EmailVerificationTokenGenerator()
6 changes: 2 additions & 4 deletions src/api/serializers/auth_factor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@
class AuthFactorSerializer(ModelSerializer[User, AuthFactor]):
class Meta:
model = AuthFactor
fields = [
"id",
"type",
]
fields = ["id", "type", "user"]
extra_kwargs = {
"id": {"read_only": True},
"user": {"read_only": True},
}

# pylint: disable-next=missing-function-docstring
Expand Down
27 changes: 27 additions & 0 deletions src/api/serializers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,33 @@ def update(self, instance, validated_data):
# TODO: Send email in signal to teacher of selected class to
# notify them of join request.

new_email = validated_data.pop("email", None)
if new_email is not None and new_email != instance.email:
send_mail(
settings.DOTDIGITAL_CAMPAIGN_IDS["Email change notification"],
to_addresses=[instance.email],
personalization_values={"NEW_EMAIL_ADDRESS": instance.email},
)

# pylint: disable-next=duplicate-code
verify_email_address_link = settings.SERVICE_BASE_URL + reverse(
"user-verify-email-address",
kwargs={
"pk": instance.pk,
"token": email_verification_token_generator.make_token(
instance.pk, new_email=new_email
),
},
)

send_mail(
settings.DOTDIGITAL_CAMPAIGN_IDS["Verify changed user email"],
to_addresses=[new_email],
personalization_values={
"VERIFICATION_LINK": verify_email_address_link
},
)

return super().update(instance, validated_data)


Expand Down
65 changes: 61 additions & 4 deletions src/api/serializers/user_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import typing as t
from datetime import date
from unittest.mock import Mock, patch
from unittest.mock import Mock, call, patch

from codeforlife.tests import ModelSerializerTestCase
from codeforlife.user.models import (
Expand All @@ -16,10 +16,15 @@
StudentUser,
User,
)
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.db.models import Count
from django.urls import reverse

from ..auth import password_reset_token_generator
from ..auth import (
email_verification_token_generator,
password_reset_token_generator,
)
from .user import (
BaseUserSerializer,
CreateUserSerializer,
Expand Down Expand Up @@ -132,7 +137,7 @@ def test_validate_password__invalid_password(self):
instance=user,
)

def test_update(self):
def test_update__password(self):
"""Updating a user's password saves the password's hash."""
user = User.objects.first()
assert user
Expand Down Expand Up @@ -264,7 +269,7 @@ def test_validate_requesting_to_join_class__no_longer_accepts_requests(
error_code="no_longer_accepts_requests",
)

def test_update(self):
def test_update__requesting_to_join_class(self):
"""Can update the class an independent user is requesting join."""
self.assert_update(
instance=self.indy_user,
Expand All @@ -276,6 +281,58 @@ def test_update(self):
new_data={"new_student": {"pending_class_request": self.class_2}},
)

@patch("src.api.signals.user.send_mail")
def test_update__email(self, send_mail: Mock):
"""Updating the email field sends a verification email."""
user = User.objects.first()
assert user

previous_email = user.email
email = "[email protected]"
assert previous_email != email
user.email = email

with patch.object(
email_verification_token_generator,
"make_token",
return_value=email_verification_token_generator.make_token(
user, new_email=email
),
) as make_token:
user.save()

make_token.assert_called_once_with(user.pk, new_email=email)

send_mail.assert_has_calls(
[
call(
settings.DOTDIGITAL_CAMPAIGN_IDS[
"Email change notification"
],
to_addresses=[previous_email],
personalization_values={"NEW_EMAIL_ADDRESS": email},
),
call(
settings.DOTDIGITAL_CAMPAIGN_IDS[
"Verify changed user email"
],
to_addresses=[email],
personalization_values={
"VERIFICATION_LINK": (
settings.SERVICE_BASE_URL
+ reverse(
"user-verify-email-address",
kwargs={
"pk": user.pk,
"token": make_token.return_value,
},
)
)
},
),
]
)


class TestHandleIndependentUserJoinClassRequestSerializer(
ModelSerializerTestCase[User, IndependentUser]
Expand Down
37 changes: 0 additions & 37 deletions src/api/signals/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,43 +100,6 @@ def user__post_save(
# TODO: add nullable date_of_birth field to user model and send
# verification email to independents in new schema.

elif instance.email != "":
if post_save.check_previous_values(
instance,
{
"email": lambda value: (
isinstance(value, str)
and value.lower() not in ["", instance.email.lower()]
)
},
):
previous_email = post_save.get_previous_value(
instance, "email", str
)

send_mail(
settings.DOTDIGITAL_CAMPAIGN_IDS["Email change notification"],
to_addresses=[previous_email],
personalization_values={"NEW_EMAIL_ADDRESS": instance.email},
)

verify_email_address_link = settings.SERVICE_BASE_URL + reverse(
"user-verify-email-address",
kwargs={
"pk": instance.pk,
"token": email_verification_token_generator.make_token(
instance.pk
),
},
)

send_mail(
settings.DOTDIGITAL_CAMPAIGN_IDS["Verify changed user email"],
to_addresses=[instance.email],
personalization_values={
"VERIFICATION_LINK": verify_email_address_link
},
)
# TODO: remove in new schema
elif (
instance.email == ""
Expand Down
56 changes: 0 additions & 56 deletions src/api/signals/user_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,8 @@
Created on 03/04/2024 at 14:44:42(+01:00).
"""

from unittest.mock import Mock, call, patch

from codeforlife.user.models import TeacherUser, User, UserProfile
from django.conf import settings
from django.test import TestCase
from django.urls import reverse

from ..auth import email_verification_token_generator


# pylint: disable-next=missing-class-docstring
Expand Down Expand Up @@ -40,53 +34,3 @@ def test_pre_save__username(self):

user.save()
assert user.username == email

@patch("src.api.signals.user.send_mail")
def test_post_save__email_change_notification(self, send_mail: Mock):
"""Updating the email field sends a verification email."""
user = TeacherUser.objects.first()
assert user

previous_email = user.email
email = "[email protected]"
assert previous_email != email
user.email = email

with patch.object(
email_verification_token_generator,
"make_token",
return_value=email_verification_token_generator.make_token(user),
) as make_token:
user.save()

make_token.assert_called_once_with(user.pk)

send_mail.assert_has_calls(
[
call(
settings.DOTDIGITAL_CAMPAIGN_IDS[
"Email change notification"
],
to_addresses=[previous_email],
personalization_values={"NEW_EMAIL_ADDRESS": email},
),
call(
settings.DOTDIGITAL_CAMPAIGN_IDS[
"Verify changed user email"
],
to_addresses=[email],
personalization_values={
"VERIFICATION_LINK": (
settings.SERVICE_BASE_URL
+ reverse(
"user-verify-email-address",
kwargs={
"pk": user.pk,
"token": make_token.return_value,
},
)
)
},
),
]
)
10 changes: 10 additions & 0 deletions src/api/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,16 @@ def verify_email_address(self, request: Request, **url_params: str):
serializer.is_valid(raise_exception=True)
serializer.save()

new_email = email_verification_token_generator.get_new_email(
user, url_params["token"]
)
print(new_email)
if new_email != "":
user.email = new_email
user.username = new_email
user.save()
print("user saved!")

return Response(
status=status.HTTP_303_SEE_OTHER,
headers={
Expand Down
Loading