Debian Codegraph @

flask_security/confirmable.py

raw
1 """
2 flask_security.confirmable
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security confirmable module
6
7 :copyright: (c) 2012 by Matt Wright.
8 :copyright: (c) 2017 by CERN.
9 :copyright: (c) 2021-2023 by J. Christopher Wagner (jwag).
10 :license: MIT, see LICENSE for more details.
11 """
12
13 from flask import current_app
14
15 from .proxies import _security, _datastore
16 from .signals import confirm_instructions_sent, user_confirmed
17 from .utils import (
18 config_value as cv,
19 get_token_status,
20 hash_data,
21 send_mail,
22 url_for_security,
23 verify_hash,
24 )
25
26
27 def generate_confirmation_link(user):
28 token = generate_confirmation_token(user)
29 return url_for_security("confirm_email", token=token, _external=True), token
30
31
32 def send_confirmation_instructions(user):
33 """Sends the confirmation instructions email for the specified user.
34
35 :param user: The user to send the instructions to
36 """
37
38 confirmation_link, token = generate_confirmation_link(user)
39
40 send_mail(
41 cv("EMAIL_SUBJECT_CONFIRM"),
42 user.email,
43 "confirmation_instructions",
44 user=user,
45 confirmation_link=confirmation_link,
46 confirmation_token=token,
47 )
48
49 confirm_instructions_sent.send(
50 current_app._get_current_object(),
51 _async_wrapper=current_app.ensure_sync,
52 user=user,
53 token=token,
54 confirmation_token=token,
55 )
56
57
58 def generate_confirmation_token(user):
59 """Generates a unique confirmation token for the specified user.
60
61 :param user: The user to work with
62 """
63 data = [str(user.fs_uniquifier), hash_data(user.email)]
64 return _security.confirm_serializer.dumps(data)
65
66
67 def requires_confirmation(user):
68 """Returns `True` if the user requires confirmation."""
69 return (
70 _security.confirmable
71 and not cv("LOGIN_WITHOUT_CONFIRMATION")
72 and user.confirmed_at is None
73 )
74
75
76 def confirm_email_token_status(token):
77 """Returns the expired status, invalid status, and user of a confirmation
78 token. For example::
79
80 expired, invalid, user = confirm_email_token_status('...')
81
82 :param token: The confirmation token
83 """
84 expired, invalid, user, token_data = get_token_status(
85 token, "confirm", "CONFIRM_EMAIL", return_data=True
86 )
87 if not invalid and user:
88 user_id, token_email_hash = token_data
89 invalid = not verify_hash(token_email_hash, user.email)
90 return expired, invalid, user
91
92
93 def confirm_user(user):
94 """Confirms the specified user
95
96 :param user: The user to confirm
97 """
98 if user.confirmed_at is not None:
99 return False
100 user.confirmed_at = _security.datetime_factory()
101 _datastore.put(user)
102 user_confirmed.send(
103 current_app._get_current_object(),
104 _async_wrapper=current_app.ensure_sync,
105 user=user,
106 )
107 return True