| 1 |
from datetime import timedelta |
| 2 |
from http import HTTPStatus |
| 3 |
from unittest.mock import Mock |
| 4 |
|
| 5 |
from django.contrib.auth import SESSION_KEY, get_user_model |
| 6 |
from django.core.cache import cache |
| 7 |
from django.urls import reverse |
| 8 |
from django.utils.timezone import now |
| 9 |
|
| 10 |
import pytest |
| 11 |
from pytest_django.asserts import ( |
| 12 |
assertRedirects, |
| 13 |
assertTemplateNotUsed, |
| 14 |
assertTemplateUsed, |
| 15 |
) |
| 16 |
|
| 17 |
from allauth.account import app_settings |
| 18 |
from allauth.account.adapter import DefaultAccountAdapter |
| 19 |
from allauth.account.models import ( |
| 20 |
EmailAddress, |
| 21 |
EmailConfirmation, |
| 22 |
EmailConfirmationHMAC, |
| 23 |
) |
| 24 |
from allauth.account.signals import user_logged_in |
| 25 |
|
| 26 |
|
| 27 |
class SignupRedirectEmailVerificationAdapter(DefaultAccountAdapter): |
| 28 |
SIGNUP_REDIRECT_URL = "/foobar" |
| 29 |
|
| 30 |
def get_signup_redirect_url(self, request): |
| 31 |
return self.SIGNUP_REDIRECT_URL |
| 32 |
|
| 33 |
|
| 34 |
@pytest.mark.parametrize( |
| 35 |
"adapter,query,expected_location", |
| 36 |
[ |
| 37 |
(None, "", app_settings.SIGNUP_REDIRECT_URL), |
| 38 |
(None, "?next=/foo", "/foo"), |
| 39 |
( |
| 40 |
"tests.apps.account.test_email_verification.SignupRedirectEmailVerificationAdapter", |
| 41 |
"", |
| 42 |
SignupRedirectEmailVerificationAdapter.SIGNUP_REDIRECT_URL, |
| 43 |
), |
| 44 |
], |
| 45 |
) |
| 46 |
def test_login_on_verification( |
| 47 |
adapter, client, db, query, expected_location, password_factory, settings |
| 48 |
): |
| 49 |
settings.ACCOUNT_EMAIL_VERIFICATION = app_settings.EmailVerificationMethod.MANDATORY |
| 50 |
settings.ACCOUNT_EMAIL_CONFIRMATION_HMAC = True |
| 51 |
settings.ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True |
| 52 |
if adapter: |
| 53 |
settings.ACCOUNT_ADAPTER = adapter |
| 54 |
password = password_factory() |
| 55 |
resp = client.post( |
| 56 |
reverse("account_signup"), |
| 57 |
data={ |
| 58 |
"username": "john", |
| 59 |
"email": "[email protected]", |
| 60 |
"password1": password, |
| 61 |
"password2": password, |
| 62 |
}, |
| 63 |
) |
| 64 |
assert resp.status_code == HTTPStatus.FOUND |
| 65 |
assert resp["location"] == reverse("account_email_verification_sent") |
| 66 |
|
| 67 |
resp = client.get(resp["location"]) |
| 68 |
assert resp.status_code == HTTPStatus.OK |
| 69 |
|
| 70 |
email = EmailAddress.objects.get(email="[email protected]") |
| 71 |
key = EmailConfirmationHMAC(email).key |
| 72 |
|
| 73 |
receiver_mock = Mock() # we've logged if signal was called |
| 74 |
user_logged_in.connect(receiver_mock) |
| 75 |
|
| 76 |
resp = client.post(reverse("account_confirm_email", args=[key]) + query) |
| 77 |
assert resp["location"] == expected_location |
| 78 |
email = EmailAddress.objects.get(pk=email.pk) |
| 79 |
assert email.verified |
| 80 |
|
| 81 |
receiver_mock.assert_called_once_with( |
| 82 |
sender=get_user_model(), |
| 83 |
request=resp.wsgi_request, |
| 84 |
response=resp, |
| 85 |
user=email.user, |
| 86 |
signal=user_logged_in, |
| 87 |
) |
| 88 |
|
| 89 |
user_logged_in.disconnect(receiver_mock) |
| 90 |
|
| 91 |
|
| 92 |
def test_email_verification_failed(settings, user_factory, client): |
| 93 |
settings.ACCOUNT_EMAIL_CONFIRMATION_HMAC = False |
| 94 |
user_factory(email_verified=True, email="[email protected]") |
| 95 |
unverified_user = user_factory(email_verified=False, email="[email protected]") |
| 96 |
email_address = EmailAddress.objects.get_for_user( |
| 97 |
unverified_user, unverified_user.email |
| 98 |
) |
| 99 |
assert not email_address.verified |
| 100 |
confirmation = EmailConfirmation.objects.create( |
| 101 |
email_address=email_address, |
| 102 |
key="dummy", |
| 103 |
sent=now(), |
| 104 |
) |
| 105 |
resp = client.post(reverse("account_confirm_email", args=[confirmation.key])) |
| 106 |
assertTemplateUsed(resp, "account/messages/email_confirmation_failed.txt") |
| 107 |
|
| 108 |
|
| 109 |
def test_email_verification_mandatory(settings, db, client, mailoutbox, enable_cache): |
| 110 |
settings.ACCOUNT_EMAIL_CONFIRMATION_HMAC = False |
| 111 |
settings.ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 10 |
| 112 |
settings.ACCOUNT_EMAIL_VERIFICATION = app_settings.EmailVerificationMethod.MANDATORY |
| 113 |
# Signup |
| 114 |
resp = client.post( |
| 115 |
reverse("account_signup"), |
| 116 |
{ |
| 117 |
"username": "johndoe", |
| 118 |
"email": "[email protected]", |
| 119 |
"password1": "johndoe", |
| 120 |
"password2": "johndoe", |
| 121 |
}, |
| 122 |
follow=True, |
| 123 |
) |
| 124 |
assert resp.status_code == HTTPStatus.OK |
| 125 |
assert mailoutbox[0].to == ["[email protected]"] |
| 126 |
assert mailoutbox[0].body.find("http://") > 0 |
| 127 |
assert len(mailoutbox) == 1 |
| 128 |
assertTemplateUsed( |
| 129 |
resp, |
| 130 |
f"account/verification_sent.{app_settings.TEMPLATE_EXTENSION}", |
| 131 |
) |
| 132 |
# Attempt to login, unverified |
| 133 |
for attempt in [1, 2]: |
| 134 |
resp = client.post( |
| 135 |
reverse("account_login"), |
| 136 |
{"login": "johndoe", "password": "johndoe"}, |
| 137 |
follow=True, |
| 138 |
) |
| 139 |
# is_active is controlled by the admin to manually disable |
| 140 |
# users. I don't want this flag to flip automatically whenever |
| 141 |
# users verify their email addresses. |
| 142 |
assert ( |
| 143 |
get_user_model().objects.filter(username="johndoe", is_active=True).exists() |
| 144 |
) |
| 145 |
|
| 146 |
assertTemplateUsed( |
| 147 |
resp, |
| 148 |
f"account/verification_sent.{app_settings.TEMPLATE_EXTENSION}", |
| 149 |
) |
| 150 |
# Attempt 1: no mail is sent due to cool-down , |
| 151 |
# but there was already a mail in the outbox. |
| 152 |
assert len(mailoutbox) == attempt |
| 153 |
assert ( |
| 154 |
EmailConfirmation.objects.filter( |
| 155 |
email_address__email="[email protected]" |
| 156 |
).count() |
| 157 |
== attempt |
| 158 |
) |
| 159 |
# Wait for cooldown -- wipe cache (incl. rate limits) |
| 160 |
cache.clear() |
| 161 |
# if we don't wipe the session, login will redirect to pending stage... |
| 162 |
client.logout() |
| 163 |
|
| 164 |
# Verify, and re-attempt to login. |
| 165 |
confirmation = EmailConfirmation.objects.filter( |
| 166 |
email_address__user__username="johndoe" |
| 167 |
)[:1].get() |
| 168 |
resp = client.get(reverse("account_confirm_email", args=[confirmation.key])) |
| 169 |
assertTemplateUsed(resp, f"account/email_confirm.{app_settings.TEMPLATE_EXTENSION}") |
| 170 |
client.post(reverse("account_confirm_email", args=[confirmation.key])) |
| 171 |
resp = client.post( |
| 172 |
reverse("account_login"), |
| 173 |
{"login": "johndoe", "password": "johndoe"}, |
| 174 |
) |
| 175 |
assertRedirects(resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) |
| 176 |
|
| 177 |
|
| 178 |
def test_optional_email_verification(settings, client, db, mailoutbox): |
| 179 |
settings.ACCOUNT_SIGNUP_REDIRECT_URL = "/accounts/welcome/" |
| 180 |
settings.ACCOUNT_EMAIL_VERIFICATION = app_settings.EmailVerificationMethod.OPTIONAL |
| 181 |
settings.ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False |
| 182 |
# Signup |
| 183 |
client.get(reverse("account_signup")) |
| 184 |
resp = client.post( |
| 185 |
reverse("account_signup"), |
| 186 |
{ |
| 187 |
"username": "johndoe", |
| 188 |
"email": "[email protected]", |
| 189 |
"password1": "johndoe", |
| 190 |
}, |
| 191 |
) |
| 192 |
# Logged in |
| 193 |
assertRedirects( |
| 194 |
resp, settings.ACCOUNT_SIGNUP_REDIRECT_URL, fetch_redirect_response=False |
| 195 |
) |
| 196 |
assert mailoutbox[0].to == ["[email protected]"] |
| 197 |
assert len(mailoutbox) == 1 |
| 198 |
# Logout & login again |
| 199 |
client.logout() |
| 200 |
# Wait for cooldown |
| 201 |
EmailConfirmation.objects.update(sent=now() - timedelta(days=1)) |
| 202 |
# Signup |
| 203 |
resp = client.post( |
| 204 |
reverse("account_login"), |
| 205 |
{"login": "johndoe", "password": "johndoe"}, |
| 206 |
) |
| 207 |
assertRedirects(resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) |
| 208 |
assert mailoutbox[0].to == ["[email protected]"] |
| 209 |
# There was an issue that we sent out email confirmation mails |
| 210 |
# on each login in case of optional verification. Make sure |
| 211 |
# this is not the case: |
| 212 |
assert len(mailoutbox) == 1 |
| 213 |
|
| 214 |
|
| 215 |
def test_email_verification_hmac(settings, client, user_factory, mailoutbox, rf): |
| 216 |
settings.ACCOUNT_EMAIL_CONFIRMATION_HMAC = True |
| 217 |
user = user_factory(email_verified=False) |
| 218 |
email = EmailAddress.objects.get_for_user(user, user.email) |
| 219 |
confirmation = EmailConfirmationHMAC(email) |
| 220 |
request = rf.get("/") |
| 221 |
confirmation.send(request=request) |
| 222 |
assert len(mailoutbox) == 1 |
| 223 |
client.post(reverse("account_confirm_email", args=[confirmation.key])) |
| 224 |
email = EmailAddress.objects.get(pk=email.pk) |
| 225 |
assert email.verified |
| 226 |
|
| 227 |
|
| 228 |
def test_email_verification_hmac_timeout( |
| 229 |
settings, user_factory, client, mailoutbox, rf |
| 230 |
): |
| 231 |
settings.ACCOUNT_EMAIL_CONFIRMATION_HMAC = True |
| 232 |
settings.ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 0 |
| 233 |
user = user_factory(email_verified=False) |
| 234 |
email = EmailAddress.objects.get_for_user(user, user.email) |
| 235 |
confirmation = EmailConfirmationHMAC(email) |
| 236 |
request = rf.get("/") |
| 237 |
confirmation.send(request=request) |
| 238 |
assert len(mailoutbox) == 1 |
| 239 |
client.post(reverse("account_confirm_email", args=[confirmation.key])) |
| 240 |
email = EmailAddress.objects.get(pk=email.pk) |
| 241 |
assert not email.verified |
| 242 |
|
| 243 |
|
| 244 |
def test_verify_email_with_another_user_logged_in( |
| 245 |
settings, user_factory, client, mailoutbox |
| 246 |
): |
| 247 |
"""Test the email verification view. If User B clicks on an email |
| 248 |
verification link while logged in as User A, ensure User A gets |
| 249 |
logged out.""" |
| 250 |
settings.ACCOUNT_LOGIN_METHODS = {app_settings.AuthenticationMethod.EMAIL} |
| 251 |
user = user_factory(email_verified=False) |
| 252 |
client.force_login(user) |
| 253 |
client.post(reverse("account_email"), {"email": user.email, "action_send": ""}) |
| 254 |
assert len(mailoutbox) == 1 |
| 255 |
assert mailoutbox[0].to == [user.email] |
| 256 |
client.logout() |
| 257 |
body = mailoutbox[0].body |
| 258 |
assert body.find("http://") > 0 |
| 259 |
|
| 260 |
user2 = user_factory(email_verified=False, password="doe") |
| 261 |
resp = client.post( |
| 262 |
reverse("account_login"), |
| 263 |
{ |
| 264 |
"login": user2.email, |
| 265 |
"password": "doe", |
| 266 |
}, |
| 267 |
) |
| 268 |
assert user2 == resp.context["user"] |
| 269 |
|
| 270 |
url = body[body.find("/accounts/confirm-email/") :].split()[0] |
| 271 |
resp = client.post(url) |
| 272 |
|
| 273 |
assertTemplateUsed(resp, "account/messages/logged_out.txt") |
| 274 |
assertTemplateUsed(resp, "account/messages/email_confirmed.txt") |
| 275 |
|
| 276 |
assertRedirects(resp, settings.LOGIN_URL, fetch_redirect_response=False) |
| 277 |
|
| 278 |
|
| 279 |
def test_verify_email_with_same_user_logged_in( |
| 280 |
settings, user_factory, client, mailoutbox |
| 281 |
): |
| 282 |
"""If the user clicks on an email verification link while logged in, ensure |
| 283 |
the user stays logged in. |
| 284 |
""" |
| 285 |
settings.ACCOUNT_LOGIN_METHODS = {app_settings.AuthenticationMethod.EMAIL} |
| 286 |
user = user_factory(email_verified=False) |
| 287 |
client.force_login(user) |
| 288 |
client.post(reverse("account_email"), {"email": user.email, "action_send": ""}) |
| 289 |
assert len(mailoutbox) == 1 |
| 290 |
assert mailoutbox[0].to == [user.email] |
| 291 |
|
| 292 |
body = mailoutbox[0].body |
| 293 |
assert body.find("http://") > 0 |
| 294 |
|
| 295 |
url = body[body.find("/accounts/confirm-email/") :].split()[0] |
| 296 |
resp = client.post(url) |
| 297 |
|
| 298 |
assertTemplateNotUsed(resp, "account/messages/logged_out.txt") |
| 299 |
assertTemplateUsed(resp, "account/messages/email_confirmed.txt") |
| 300 |
|
| 301 |
assertRedirects(resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) |
| 302 |
|
| 303 |
assert user == resp.wsgi_request.user |
| 304 |
|
| 305 |
|
| 306 |
def test_verify_logs_out_user(auth_client, settings, user, user_factory): |
| 307 |
""" |
| 308 |
When a user is signed in, and you follow an email confirmation link of |
| 309 |
another user within the same browser/session, be sure to sign out the signed |
| 310 |
in user. |
| 311 |
""" |
| 312 |
settings.ACCOUNT_CONFIRM_EMAIL_ON_GET = False |
| 313 |
confirming_user = user_factory(email_verified=False) |
| 314 |
assert auth_client.session[SESSION_KEY] == str(user.pk) |
| 315 |
email = EmailAddress.objects.get(user=confirming_user, verified=False) |
| 316 |
auth_client.get( |
| 317 |
reverse( |
| 318 |
"account_confirm_email", kwargs={"key": EmailConfirmationHMAC(email).key} |
| 319 |
) |
| 320 |
) |
| 321 |
assert not auth_client.session.get(SESSION_KEY) |
| 322 |
|
| 323 |
|
| 324 |
def test_email_verification_login_redirect(client, db, settings, password_factory): |
| 325 |
settings.ACCOUNT_EMAIL_VERIFICATION = app_settings.EmailVerificationMethod.MANDATORY |
| 326 |
password = password_factory() |
| 327 |
resp = client.post( |
| 328 |
reverse("account_signup"), |
| 329 |
{ |
| 330 |
"username": "johndoe", |
| 331 |
"email": "[email protected]", |
| 332 |
"password1": password, |
| 333 |
"password2": password, |
| 334 |
}, |
| 335 |
) |
| 336 |
assert resp.status_code == HTTPStatus.FOUND |
| 337 |
assert resp["location"] == reverse("account_email_verification_sent") |
| 338 |
resp = client.get(reverse("account_login")) |
| 339 |
assert resp.status_code == HTTPStatus.OK |
| 340 |
|
| 341 |
|
| 342 |
def test_email_verification_redirect_url(client, db, settings, user_password): |
| 343 |
settings.ACCOUNT_EMAIL_VERIFICATION = app_settings.EmailVerificationMethod.MANDATORY |
| 344 |
settings.ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "/foobar" |
| 345 |
settings.ACCOUNT_CONFIRM_EMAIL_ON_GET = True |
| 346 |
email = "[email protected]" |
| 347 |
resp = client.post( |
| 348 |
reverse("account_signup"), |
| 349 |
{ |
| 350 |
"username": "johndoe", |
| 351 |
"email": email, |
| 352 |
"password1": user_password, |
| 353 |
"password2": user_password, |
| 354 |
}, |
| 355 |
) |
| 356 |
assert resp.status_code == HTTPStatus.FOUND |
| 357 |
assert resp["location"] == reverse("account_email_verification_sent") |
| 358 |
confirmation = EmailConfirmationHMAC(EmailAddress.objects.get(email=email)) |
| 359 |
resp = client.get(reverse("account_confirm_email", args=[confirmation.key])) |
| 360 |
assert resp.status_code == HTTPStatus.FOUND |
| 361 |
assert resp["location"] == "/foobar" |
| 362 |
|
| 363 |
|
| 364 |
def test_verified_email_decorator__unverified(auth_client): |
| 365 |
EmailAddress.objects.all().update(verified=False) |
| 366 |
resp = auth_client.get(reverse("tests_account_check_verified_email")) |
| 367 |
assert resp.status_code == HTTPStatus.OK |
| 368 |
assertTemplateUsed(resp, "account/verified_email_required.html") |
| 369 |
|
| 370 |
|
| 371 |
def test_verified_email_decorator__verified(auth_client): |
| 372 |
EmailAddress.objects.all().update(verified=True) |
| 373 |
resp = auth_client.get(reverse("tests_account_check_verified_email")) |
| 374 |
assert resp.status_code == HTTPStatus.OK |
| 375 |
assert resp.content == b"VERIFIED" |