reflex-magic-link-auth 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ from . import constants
2
+ from .models import MagicLinkAuthRecord, MagicLinkAuthSession
3
+ from .page import magic_link_auth_page
4
+ from .providers import send_magic_link_mailgun
5
+ from .state import MagicLinkAuthState
6
+
7
+ __all__ = [
8
+ "constants",
9
+ "MagicLinkAuthRecord",
10
+ "MagicLinkAuthSession",
11
+ "MagicLinkAuthState",
12
+ "magic_link_auth_page",
13
+ "send_magic_link_mailgun",
14
+ ]
@@ -0,0 +1,6 @@
1
+ import datetime
2
+
3
+ AUTH_ROUTE = "/magic-link-auth"
4
+ DEFAULT_OTP_EXPIRATION_DELTA = datetime.timedelta(minutes=30)
5
+ DEFAULT_AUTH_SESSION_EXPIRATION_DELTA = datetime.timedelta(days=7)
6
+ DEFAULT_OTP_RATE_LIMIT = 5
@@ -0,0 +1,4 @@
1
+ from .record import MagicLinkAuthRecord
2
+ from .session import MagicLinkAuthSession
3
+
4
+ __all__ = ["MagicLinkAuthRecord", "MagicLinkAuthSession"]
@@ -0,0 +1,76 @@
1
+ """The MagicLinkAuthRecord temporarily stores the generated OTP for an email."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import hashlib
7
+
8
+ import bcrypt
9
+ from sqlmodel import Column, DateTime, Field, func, Session, select
10
+
11
+ import reflex as rx
12
+
13
+
14
+ class MagicLinkAuthRecord(rx.Model, table=True):
15
+ email: str
16
+ otp_hash: bytes
17
+ created: datetime.datetime = Field(
18
+ sa_column=Column(
19
+ DateTime(timezone=True),
20
+ server_default=func.now(),
21
+ nullable=False,
22
+ ),
23
+ )
24
+ expiration: datetime.datetime = Field(
25
+ sa_column=Column(
26
+ DateTime(timezone=True), server_default=func.now(), nullable=False
27
+ ),
28
+ )
29
+ client_ip: str = Field(nullable=False)
30
+ # How many times have we regenerated the OTP for this email in the last DEFAULT_OTP_EXPIRATION_DELTA?
31
+ recent_attempts: int = Field(default=0)
32
+
33
+ @staticmethod
34
+ def hash_token(token: str) -> bytes:
35
+ """Hash the token using bcrypt.
36
+
37
+ Args:
38
+ token: The password to hash.
39
+
40
+ Returns:
41
+ The hashed token.
42
+ """
43
+ return bcrypt.hashpw(
44
+ password=token.encode("utf-8"),
45
+ salt=bcrypt.gensalt(),
46
+ )
47
+
48
+ def verify(self, token: str) -> bool:
49
+ """Validate the otp_hash.
50
+
51
+ Args:
52
+ token: The password to check.
53
+
54
+ Returns:
55
+ True if the hashed token matches this user's otp_hash.
56
+ """
57
+ return bcrypt.checkpw(
58
+ password=token.encode("utf-8"),
59
+ hashed_password=self.otp_hash,
60
+ )
61
+
62
+ def persistent_id(self) -> str:
63
+ """Return a unique identifier for the user."""
64
+ return hashlib.sha256(
65
+ self.email.lower().encode("utf-8"),
66
+ ).hexdigest()
67
+
68
+ def update_recent_attempts(self, session: Session, delta: datetime.timedelta):
69
+ """Update the recent_attempts count for this email."""
70
+ self.recent_attempts = session.exec(
71
+ select(func.count()).where(
72
+ MagicLinkAuthRecord.email == self.email.lower(),
73
+ MagicLinkAuthRecord.created
74
+ >= datetime.datetime.now(datetime.timezone.utc) - delta,
75
+ ),
76
+ ).one()
@@ -0,0 +1,48 @@
1
+ """The MagicLinkAuthSession model maps an email to a session_token."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import secrets
7
+
8
+ from sqlmodel import Column, DateTime, Field, func
9
+
10
+ import reflex as rx
11
+
12
+ from .. import constants
13
+ from .record import MagicLinkAuthRecord
14
+
15
+
16
+ class MagicLinkAuthSession(rx.Model, table=True):
17
+ email: str = Field(index=True, nullable=False)
18
+ persistent_id: str = Field(index=True, nullable=False)
19
+ session_token: str = Field(unique=True, index=True, nullable=False)
20
+ created: datetime.datetime = Field(
21
+ sa_column=Column(
22
+ DateTime(timezone=True),
23
+ server_default=func.now(),
24
+ nullable=False,
25
+ ),
26
+ )
27
+ expiration: datetime.datetime = Field(
28
+ sa_column=Column(
29
+ DateTime(timezone=True),
30
+ server_default=func.now(),
31
+ nullable=False,
32
+ ),
33
+ )
34
+
35
+ @classmethod
36
+ def from_record(
37
+ cls,
38
+ record: MagicLinkAuthRecord,
39
+ expiration_delta: datetime.timedelta | None = None,
40
+ ) -> MagicLinkAuthSession:
41
+ if expiration_delta is None:
42
+ expiration_delta = constants.DEFAULT_AUTH_SESSION_EXPIRATION_DELTA
43
+ return cls(
44
+ email=record.email,
45
+ persistent_id=record.persistent_id(),
46
+ session_token=secrets.token_hex(32),
47
+ expiration=datetime.datetime.now(datetime.timezone.utc) + expiration_delta,
48
+ )
@@ -0,0 +1,39 @@
1
+ """Page for handling magic link authentication."""
2
+
3
+ import reflex as rx
4
+
5
+ from . import constants
6
+ from .state import MagicLinkAuthState
7
+
8
+
9
+ class HandleMagicLinkState(MagicLinkAuthState):
10
+ """Validate email and OTP from query params, then redirect."""
11
+
12
+ token_valid: bool = False
13
+
14
+ def on_load(self):
15
+ params = self.router.page.params
16
+ email = params.get("email")
17
+ otp = params.get("otp")
18
+ redir = params.get("redir")
19
+ if email is None or otp is None:
20
+ return
21
+ self.token_valid = self._validate_otp(email, otp)
22
+ if self.token_valid and redir is not None:
23
+ return rx.redirect(redir)
24
+
25
+
26
+ @rx.page(constants.AUTH_ROUTE, on_load=HandleMagicLinkState.on_load)
27
+ def magic_link_auth_page():
28
+ """Simple page component for handling magic link authentication in query params."""
29
+ return rx.vstack(
30
+ rx.cond(
31
+ HandleMagicLinkState.is_hydrated,
32
+ rx.cond(
33
+ HandleMagicLinkState.token_valid,
34
+ rx.heading("Login successful!"),
35
+ rx.heading("Login failed!"),
36
+ ),
37
+ rx.heading("Validating Token..."),
38
+ ),
39
+ )
@@ -0,0 +1,3 @@
1
+ from .mailgun import send_magic_link_mailgun
2
+
3
+ __all__ = ["send_magic_link_mailgun"]
@@ -0,0 +1,53 @@
1
+ import os
2
+ import urllib
3
+
4
+ import httpx
5
+
6
+ import reflex as rx
7
+
8
+ config = rx.config.get_config()
9
+
10
+
11
+ APP_NAME = " ".join(w.capitalize() for w in config.app_name.split("_"))
12
+ API_URL = os.environ.get("MAILGUN_API_URL", "https://api.mailgun.net")
13
+ DOMAIN_NAME = os.environ.get("MAILGUN_DOMAIN_NAME")
14
+ API_KEY = os.environ.get("MAILGUN_API_KEY")
15
+ DEFAULT_SUBJECT = "Magic Login Link"
16
+ DEFAULT_HTML = "Click this link to log in: <a href='{magic_link}'>{magic_link}</a>"
17
+
18
+
19
+ def messages_endpoint():
20
+ if DOMAIN_NAME is None:
21
+ raise ValueError("MAILGUN_DOMAIN_NAME is required to send magic link emails.")
22
+ return urllib.parse.urljoin(API_URL, f"/v3/{DOMAIN_NAME}/messages")
23
+
24
+
25
+ def default_from():
26
+ return f"{APP_NAME} <{config.app_name}@{DOMAIN_NAME}>"
27
+
28
+
29
+ def email_from():
30
+ return os.environ.get("MAGIC_LINK_EMAIL_FROM") or default_from()
31
+
32
+
33
+ def email_subject():
34
+ return os.environ.get("MAGIC_LINK_EMAIL_SUBJECT", DEFAULT_SUBJECT)
35
+
36
+
37
+ def email_html():
38
+ return os.environ.get("MAGIC_LINK_EMAIL_HTML", DEFAULT_HTML)
39
+
40
+
41
+ def send_magic_link_mailgun(email: str, magic_link: str) -> httpx.Response:
42
+ """Send magic link email to user."""
43
+ if API_KEY is None:
44
+ raise ValueError("MAILGUN_API_KEY is required to send magic link emails.")
45
+ data = {
46
+ "from": email_from(),
47
+ "to": email,
48
+ "subject": email_subject(),
49
+ "html": email_html().format(magic_link=magic_link),
50
+ }
51
+ response = httpx.post(messages_endpoint(), data=data, auth=("api", API_KEY))
52
+ response.raise_for_status()
53
+ return response
@@ -0,0 +1,191 @@
1
+ """MagicAuthLinkState generates OTPs and validates login sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import secrets
7
+ import urllib
8
+
9
+ from sqlmodel import delete, func, select, update, Session
10
+
11
+ import reflex as rx
12
+
13
+ from . import constants
14
+ from .models import MagicLinkAuthRecord, MagicLinkAuthSession
15
+
16
+
17
+ class MagicLinkBaseState(rx.State):
18
+ """State for handling dynamic retrieval of the frontend URL."""
19
+
20
+ auth_url: str
21
+
22
+ def get_base_url(self):
23
+ """EventHandler triggers a request for the frontend URL."""
24
+ return rx.call_script(
25
+ "window.location.origin", callback=type(self).get_auth_url_cb
26
+ )
27
+
28
+ def get_auth_url_cb(self, base_url):
29
+ """Callback that accepts and stores the frontend URL for validating OTP."""
30
+ self.auth_url = urllib.parse.urljoin(base_url, constants.AUTH_ROUTE)
31
+
32
+ def _get_magic_link(self, record: MagicLinkAuthRecord, otp: str, redir: str = "/"):
33
+ """Helper function to format the magic link URL."""
34
+ url_parts = urllib.parse.urlparse(self.auth_url)
35
+ return urllib.parse.urlunparse(
36
+ url_parts._replace(
37
+ query=urllib.parse.urlencode(
38
+ {"email": record.email, "otp": otp, "redir": redir},
39
+ ),
40
+ ),
41
+ )
42
+
43
+
44
+ class MagicLinkAuthState(MagicLinkBaseState):
45
+ """State for handling generation and validation of OTP."""
46
+
47
+ session_token: str = rx.LocalStorage(sync=True)
48
+
49
+ def _get_current_record(
50
+ self, session: Session, email: str
51
+ ) -> MagicLinkAuthRecord | None:
52
+ return session.exec(
53
+ MagicLinkAuthRecord.select()
54
+ .where(
55
+ MagicLinkAuthRecord.email == email.lower(),
56
+ MagicLinkAuthRecord.expiration >= func.now(),
57
+ )
58
+ .order_by(MagicLinkAuthRecord.created.desc())
59
+ .limit(1),
60
+ ).one_or_none()
61
+
62
+ def _expire_outstanding_otps(self, session: Session, email: str):
63
+ # Kill unexpired OTPs for this email (only one active at a time).
64
+ session.exec(
65
+ update(MagicLinkAuthRecord)
66
+ .where(
67
+ MagicLinkAuthRecord.email == email.lower(),
68
+ MagicLinkAuthRecord.expiration >= func.now(),
69
+ )
70
+ .values(
71
+ expiration=datetime.datetime.now(datetime.timezone.utc),
72
+ ),
73
+ )
74
+
75
+ def _delete_all_otps(self, session: Session, email: str):
76
+ session.exec(
77
+ delete(MagicLinkAuthRecord).where(
78
+ MagicLinkAuthRecord.email == email.lower()
79
+ )
80
+ )
81
+
82
+ def _get_client_ip(self) -> str:
83
+ return getattr(self.router.headers, "x_forwarded_for", self.router.session.client_ip)
84
+
85
+ def _count_attempts_from_ip(self, session: Session, delta: datetime.timedelta) -> int:
86
+ count = session.exec(
87
+ select(func.count()).where(
88
+ MagicLinkAuthRecord.client_ip == self._get_client_ip(),
89
+ MagicLinkAuthRecord.created
90
+ >= datetime.datetime.now(datetime.timezone.utc) - delta,
91
+ ),
92
+ ).one()
93
+ return count
94
+
95
+ def _generate_otp(
96
+ self,
97
+ email: str,
98
+ expiration_delta: datetime.timedelta | None = None,
99
+ rate_limit: int | None = None,
100
+ ) -> tuple[MagicLinkAuthRecord | None, str | None]:
101
+ if not email:
102
+ return None, None
103
+ if "@" not in email[1:]:
104
+ return None, None
105
+ if expiration_delta is None:
106
+ expiration_delta = constants.DEFAULT_OTP_EXPIRATION_DELTA
107
+ if rate_limit is None:
108
+ rate_limit = constants.DEFAULT_OTP_RATE_LIMIT
109
+ recent_attempts = 0
110
+ with rx.session() as session:
111
+ if self._count_attempts_from_ip(session, expiration_delta) >= rate_limit:
112
+ return None, None
113
+ record = self._get_current_record(session, email)
114
+ if record is not None:
115
+ record.update_recent_attempts(session, expiration_delta)
116
+ if record.recent_attempts >= rate_limit:
117
+ return record, None
118
+ recent_attempts = record.recent_attempts
119
+ self._expire_outstanding_otps(session, email)
120
+ otp = secrets.token_hex(4)
121
+ record = MagicLinkAuthRecord( # type: ignore
122
+ email=email.lower(),
123
+ otp_hash=MagicLinkAuthRecord.hash_token(otp),
124
+ expiration=datetime.datetime.now(datetime.timezone.utc)
125
+ + expiration_delta,
126
+ client_ip=getattr(self.router.headers, "x_forwarded_for", self.router.session.client_ip),
127
+ recent_attempts=recent_attempts + 1,
128
+ )
129
+ session.add(record)
130
+ session.commit()
131
+ session.refresh(record)
132
+ return record, otp
133
+
134
+ def _validate_otp(self, email: str, otp: str) -> bool:
135
+ with rx.session() as session:
136
+ record = self._get_current_record(session, email)
137
+ if record and record.verify(otp):
138
+ # Do not allow OTP reuse for this user.
139
+ self._delete_all_otps(session, email)
140
+ # Establish the session.
141
+ auth_session = MagicLinkAuthSession.from_record(record)
142
+ self.session_token = auth_session.session_token
143
+ session.add(auth_session)
144
+ session.commit()
145
+ return True
146
+ return False
147
+
148
+ @rx.cached_var
149
+ def auth_session(self) -> MagicLinkAuthSession | None:
150
+ with rx.session() as session:
151
+ auth_session_row = session.exec(
152
+ MagicLinkAuthSession.select()
153
+ .where(
154
+ MagicLinkAuthSession.session_token == self.session_token,
155
+ MagicLinkAuthSession.expiration >= func.now(),
156
+ )
157
+ .limit(1),
158
+ ).one_or_none()
159
+ if auth_session_row is not None:
160
+ # Convert to UTC datetime, if necessary (sqlite does not respect timezone=True).
161
+ if auth_session_row.expiration.tzinfo is None:
162
+ auth_session_row.expiration = auth_session_row.expiration.replace(
163
+ tzinfo=datetime.timezone.utc
164
+ )
165
+ if auth_session_row.created.tzinfo is None:
166
+ auth_session_row.created = auth_session_row.created.replace(
167
+ tzinfo=datetime.timezone.utc
168
+ )
169
+ return auth_session_row
170
+
171
+ @rx.var
172
+ def session_is_valid(self) -> bool:
173
+ return (
174
+ self.auth_session is not None
175
+ and self.auth_session.expiration
176
+ >= datetime.datetime.now(datetime.timezone.utc)
177
+ )
178
+
179
+ def logout(self):
180
+ with rx.session() as session:
181
+ session.exec(
182
+ update(MagicLinkAuthSession)
183
+ .where(
184
+ MagicLinkAuthSession.session_token == self.session_token,
185
+ )
186
+ .values(
187
+ expiration=datetime.datetime.now(datetime.timezone.utc),
188
+ ),
189
+ )
190
+ session.commit()
191
+ self.session_token = ""
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.1
2
+ Name: reflex-magic-link-auth
3
+ Version: 0.0.2
4
+ Summary: Reflex custom component magic-link-auth
5
+ Author-email: Masen Furer <m_github@0x26.net>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/masenf/reflex-magic-link-auth
8
+ Keywords: reflex,reflex-custom-components
9
+ Classifier: Development Status :: 4 - Beta
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: reflex >=0.4.2
13
+ Requires-Dist: bcrypt
14
+ Requires-Dist: httpx
15
+ Provides-Extra: dev
16
+ Requires-Dist: build ; extra == 'dev'
17
+ Requires-Dist: twine ; extra == 'dev'
18
+
19
+ # reflex-magic-link-auth
20
+
21
+ Generate and verify "magic link" one time passwords for user authentication without
22
+ complex registration flows.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install reflex-magic-link-auth
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ See
33
+ [`magic_link_auth_demo/magic_link_auth_demo.py`](magic_link_auth_demo/magic_link_auth_demo.py)
34
+ for a complete example.
35
+
36
+ ### 1. Collect the User email
37
+
38
+ You can use a simple form with a single input field and button, like the
39
+ example, or present a form prompting for more information, such as a name,
40
+ address, zip code, etc. Any additional data should be associated with the
41
+ provided email as the main key for the account.
42
+
43
+ ### 2. Substate from MagicLinkAuthState
44
+
45
+ The substate which handles the authentication form submission should be
46
+ a substate of `reflex_magic_link_auth.MagicLinkAuthState` (alternatively, it
47
+ may get an instance of this state via `.get_state` API).
48
+
49
+ ### 3. Generate the OTP
50
+
51
+ When the user submits the form, generate a one time password by calling
52
+ `._generate_otp` and providing the email address.
53
+
54
+ This function returns a 2-tuple:
55
+
56
+ * The latest record associated with the email address
57
+ * The one time password in plaintext
58
+
59
+ If the record is None, then the email address was invalid, or some other problem
60
+ occured (ensure database migration has been applied).
61
+
62
+ If the record is returned, but the OTP is None, then the user has exceeded the
63
+ configured rate limit and cannot receive a new token for a while.
64
+
65
+ ### 4. Send the Magic Link
66
+
67
+ Either on page `on_load` or some component `on_mount` should trigger
68
+ `reflex_magic_link_auth.MagicLinkAuthState.get_base_url` to ensure the state
69
+ knows the correct frontend URL when formatting the magic links.
70
+
71
+ Pass the `record` and `otp` to
72
+ `reflex_magic_link_auth.MagicLinkAuthState._get_magic_link` to get a URL that,
73
+ when accessed will log the user in to the app.
74
+
75
+ While this component contains an example mailgun provider, generally it is
76
+ up to you to actually email the link to the user.
77
+
78
+ ### 5. User Accesses the Magic Link
79
+
80
+ The user clicks the link in their email, and the page mounted at
81
+ `reflex_magic_link_auth.constants.AUTH_ROUTE` will validate the token and
82
+ redirect to the URL specified in the query param `redir`.
83
+
84
+ ### 6. Verifying Access
85
+
86
+ Any event handlers which depend on user session validity should check the computed var
87
+ `reflex_magic_link_auth.MagicLinkAuthState.session_is_valid` to determine if the user is
88
+ logged in and the session has not expired.
89
+
90
+ A persistent external identifier hashed over the email address is provided at
91
+ `reflex_magic_link_auth.MagicLinkAuthState.auth_session.persistent_id`. When interoperating
92
+ with other user information systems, this ID can be used to uniquely identifer a user
93
+ originating from reflex-magic-link-auth.
94
+
95
+ ### 7. Logout
96
+
97
+ To log the user out, trigger the event handler
98
+ `reflex_magic_link_auth.MagicLinkAuthState.logout`.
@@ -0,0 +1,13 @@
1
+ reflex_magic_link_auth/__init__.py,sha256=SnubTOUV4CSdre8C0cd2YyJCs1WymUFZgLczsI7Z4SM,382
2
+ reflex_magic_link_auth/constants.py,sha256=cYjxYKJgCLPyDhyeDivG5PUrYY_XQ4dtdZMfQT9rp7w,205
3
+ reflex_magic_link_auth/page.py,sha256=CCRmDpT7XmnV4qBP7FetxBYgj6-z29yXTgnyxXJgE7Q,1175
4
+ reflex_magic_link_auth/state.py,sha256=nsCa0ePz4204LVEZNJ5sDMxwwLcNJDlVAO5rEFymcws,7200
5
+ reflex_magic_link_auth/models/__init__.py,sha256=qLZTYHgp9vXusbWur6m77NG678Ct_4AJXnKaP2hQzAs,141
6
+ reflex_magic_link_auth/models/record.py,sha256=SvXIrHVoAp_97DfbnwXEk4uSbC6bX9hseAiQihNdWAs,2216
7
+ reflex_magic_link_auth/models/session.py,sha256=BWcgHvWGEHWmsk5s_foinu1KCKTurI7Xsrmtuw5hupU,1434
8
+ reflex_magic_link_auth/providers/__init__.py,sha256=uj_4AE2rAIU_HcgDBMeCDK0FZYuPzvMZpHYnyPT-_HM,84
9
+ reflex_magic_link_auth/providers/mailgun.py,sha256=l_f9fIS9f2p2efxl6t8agaSEYTU145BjV2oZV2Ju7Kw,1542
10
+ reflex_magic_link_auth-0.0.2.dist-info/METADATA,sha256=XEBZUrsxbGLFGS6IpQtEBV6aBw6cPQp-3ukg9SrLUus,3430
11
+ reflex_magic_link_auth-0.0.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
12
+ reflex_magic_link_auth-0.0.2.dist-info/top_level.txt,sha256=X1zgDsXAvZEYFUZ1S3-Cud6AqgXgXFfVnWFlTznjLvQ,23
13
+ reflex_magic_link_auth-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ reflex_magic_link_auth