| 1 |
""" |
| 2 |
flask_security.change_email |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Flask-Security Change Email module |
| 6 |
|
| 7 |
:copyright: (c) 2024-2024 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
|
| 10 |
Allow user to change their email address. |
| 11 |
If CHANGE_EMAIL_CONFIRM is set then the user will receive an email |
| 12 |
at the new email address with a token that can be used to verify and change |
| 13 |
emails. Upon success - if CHANGE_EMAIL_NOTIFY_OLD is set, an email will be sent |
| 14 |
to the old email address. |
| 15 |
""" |
| 16 |
|
| 17 |
from __future__ import annotations |
| 18 |
|
| 19 |
import typing as t |
| 20 |
|
| 21 |
from flask import after_this_request, request |
| 22 |
from flask import current_app |
| 23 |
from flask_login import current_user |
| 24 |
from wtforms import SubmitField |
| 25 |
|
| 26 |
from .decorators import auth_required |
| 27 |
from .forms import ( |
| 28 |
Form, |
| 29 |
UniqueEmailFormMixin, |
| 30 |
build_form_from_request, |
| 31 |
form_errors_munge, |
| 32 |
get_form_field_label, |
| 33 |
) |
| 34 |
from .proxies import _security, _datastore |
| 35 |
from .quart_compat import get_quart_status |
| 36 |
from .signals import change_email_instructions_sent, change_email_confirmed |
| 37 |
from .utils import ( |
| 38 |
base_render_json, |
| 39 |
check_and_get_token_status, |
| 40 |
config_value as cv, |
| 41 |
do_flash, |
| 42 |
get_message, |
| 43 |
get_url, |
| 44 |
get_within_delta, |
| 45 |
hash_data, |
| 46 |
send_mail, |
| 47 |
url_for_security, |
| 48 |
verify_hash, |
| 49 |
view_commit, |
| 50 |
) |
| 51 |
|
| 52 |
if t.TYPE_CHECKING: # pragma: no cover |
| 53 |
from flask.typing import ResponseValue |
| 54 |
|
| 55 |
if get_quart_status(): # pragma: no cover |
| 56 |
from quart import redirect |
| 57 |
else: |
| 58 |
from flask import redirect |
| 59 |
|
| 60 |
|
| 61 |
class ChangeEmailForm(Form, UniqueEmailFormMixin): |
| 62 |
submit = SubmitField(label=get_form_field_label("submit")) |
| 63 |
|
| 64 |
def __init__(self, *args, **kwargs): |
| 65 |
super().__init__(*args, **kwargs) |
| 66 |
self.existing_email_user = None |
| 67 |
|
| 68 |
|
| 69 |
@auth_required( |
| 70 |
lambda: cv("API_ENABLED_METHODS"), |
| 71 |
within=lambda: cv("FRESHNESS"), |
| 72 |
grace=lambda: cv("FRESHNESS_GRACE_PERIOD"), |
| 73 |
) |
| 74 |
def change_email() -> ResponseValue: |
| 75 |
"""Start Change Email for an existing authenticated user""" |
| 76 |
payload: dict[str, t.Any] |
| 77 |
|
| 78 |
form: ChangeEmailForm = t.cast( |
| 79 |
ChangeEmailForm, build_form_from_request("change_email_form") |
| 80 |
) |
| 81 |
|
| 82 |
if form.validate_on_submit(): |
| 83 |
_send_instructions(current_user, form.email.data) |
| 84 |
if not _security._want_json(request): |
| 85 |
do_flash(*get_message("CHANGE_EMAIL_SENT", email=form.email.data)) |
| 86 |
# Drop through.. |
| 87 |
|
| 88 |
# All paths get here |
| 89 |
if ( |
| 90 |
request.method == "POST" |
| 91 |
and cv("RETURN_GENERIC_RESPONSES") |
| 92 |
and form.existing_email_user |
| 93 |
): |
| 94 |
# Don't let an existing user enumerate registered emails |
| 95 |
fields_to_squash: dict[str, dict[str, str]] = dict(email=dict()) |
| 96 |
form_errors_munge(form, fields_to_squash) |
| 97 |
if not form.errors: |
| 98 |
# only error is existing email - make it appear the same as if it worked |
| 99 |
# except that we don't send anything - while we could inform the email |
| 100 |
# that someone is trying to take it over - that could allow a user to |
| 101 |
# annoy another user. |
| 102 |
if not _security._want_json(request): |
| 103 |
do_flash(*get_message("CHANGE_EMAIL_SENT", email=form.email.data)) |
| 104 |
# TODO - should we have a signal so we can tell application what is |
| 105 |
# is going on (otherwise it is pretty much a black-hole). |
| 106 |
# drop through - will return a successful response. |
| 107 |
|
| 108 |
if _security._want_json(request): |
| 109 |
form.user = current_user |
| 110 |
payload = dict(current_email=current_user.email) |
| 111 |
return base_render_json(form, additional=payload) |
| 112 |
|
| 113 |
return _security.render_template( |
| 114 |
cv("CHANGE_EMAIL_TEMPLATE"), |
| 115 |
change_email_form=form, |
| 116 |
current_email=current_user.email, |
| 117 |
**_security._run_ctx_processor("change_email"), |
| 118 |
) |
| 119 |
|
| 120 |
|
| 121 |
def change_email_confirm(token): |
| 122 |
""" |
| 123 |
View function which handles a change email confirmation request. |
| 124 |
This is always a GET from an email - so for 'spa' must always redirect. |
| 125 |
""" |
| 126 |
expired, invalid, user, new_email = _verify_token_status(token) |
| 127 |
|
| 128 |
if invalid or expired: |
| 129 |
if expired: |
| 130 |
m, c = get_message( |
| 131 |
"CHANGE_EMAIL_EXPIRED", |
| 132 |
within=cv("CHANGE_EMAIL_WITHIN"), |
| 133 |
) |
| 134 |
else: |
| 135 |
m, c = get_message("API_ERROR") |
| 136 |
if cv("REDIRECT_BEHAVIOR") == "spa": |
| 137 |
return redirect(get_url(cv("CHANGE_EMAIL_ERROR_VIEW"), qparams={c: m})) |
| 138 |
do_flash(m, c) |
| 139 |
return redirect( |
| 140 |
get_url(cv("CHANGE_EMAIL_ERROR_VIEW")) or url_for_security("change_email") |
| 141 |
) |
| 142 |
|
| 143 |
_update_user_email(user, new_email) |
| 144 |
after_this_request(view_commit) |
| 145 |
m, c = get_message("CHANGE_EMAIL_CONFIRMED") |
| 146 |
if cv("REDIRECT_BEHAVIOR") == "spa": |
| 147 |
return redirect( |
| 148 |
get_url( |
| 149 |
cv("POST_CHANGE_EMAIL_VIEW"), |
| 150 |
qparams=user.get_redirect_qparams({c: m}), |
| 151 |
) |
| 152 |
) |
| 153 |
do_flash(m, c) |
| 154 |
return redirect( |
| 155 |
get_url(cv("POST_CHANGE_EMAIL_VIEW")) or get_url(cv("POST_LOGIN_VIEW")) |
| 156 |
) |
| 157 |
|
| 158 |
|
| 159 |
def _generate_token(user, new_email): |
| 160 |
"""Generates a unique confirmation token for the specified user. |
| 161 |
|
| 162 |
:param user: The user to work with |
| 163 |
:param new_email: The requested email |
| 164 |
""" |
| 165 |
data = [str(user.fs_uniquifier), hash_data(user.email), new_email] |
| 166 |
return _security.change_email_serializer.dumps(data) |
| 167 |
|
| 168 |
|
| 169 |
def _generate_link(user, new_email): |
| 170 |
token = _generate_token(user, new_email) |
| 171 |
return url_for_security("change_email_confirm", token=token, _external=True), token |
| 172 |
|
| 173 |
|
| 174 |
def _send_instructions(user, new_email): |
| 175 |
"""Sends the change email instructions email for the specified user. |
| 176 |
|
| 177 |
:param user: The user to send the instructions to |
| 178 |
:param new_email: The requested new email |
| 179 |
""" |
| 180 |
|
| 181 |
link, token = _generate_link(user, new_email) |
| 182 |
|
| 183 |
send_mail( |
| 184 |
cv("CHANGE_EMAIL_SUBJECT"), |
| 185 |
new_email, |
| 186 |
"change_email_instructions", |
| 187 |
user=user, |
| 188 |
link=link, |
| 189 |
token=token, |
| 190 |
) |
| 191 |
|
| 192 |
change_email_instructions_sent.send( |
| 193 |
current_app._get_current_object(), |
| 194 |
_async_wrapper=current_app.ensure_sync, |
| 195 |
user=user, |
| 196 |
new_email=new_email, |
| 197 |
token=token, |
| 198 |
) |
| 199 |
|
| 200 |
|
| 201 |
def _verify_token_status(token): |
| 202 |
"""Verify token and contents. |
| 203 |
In general, we return pretty generic results - including checking the requested |
| 204 |
new_email is still available (and if not return 'invalid'). |
| 205 |
""" |
| 206 |
expired, invalid, state = check_and_get_token_status( |
| 207 |
token, "change_email", get_within_delta("CHANGE_EMAIL_WITHIN") |
| 208 |
) |
| 209 |
if invalid or expired: |
| 210 |
return expired, invalid, None, None |
| 211 |
fid, hashed_email, new_email = state |
| 212 |
user = _datastore.find_user(fs_uniquifier=fid) |
| 213 |
if not user or not verify_hash(hashed_email, user.email): |
| 214 |
return False, True, None, None |
| 215 |
|
| 216 |
# verify that new_email is still available |
| 217 |
if _datastore.find_user(email=new_email): |
| 218 |
return False, True, user, None |
| 219 |
return expired, invalid, user, new_email |
| 220 |
|
| 221 |
|
| 222 |
def _update_user_email(user, new_email): |
| 223 |
old_email = user.email |
| 224 |
user.email = new_email |
| 225 |
user.confirmed_at = _security.datetime_factory() |
| 226 |
_datastore.put(user) |
| 227 |
change_email_confirmed.send( |
| 228 |
current_app._get_current_object(), |
| 229 |
_async_wrapper=current_app.ensure_sync, |
| 230 |
user=user, |
| 231 |
old_email=old_email, |
| 232 |
) |