-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_factor_auth.py
More file actions
323 lines (252 loc) · 11.3 KB
/
Copy pathtwo_factor_auth.py
File metadata and controls
323 lines (252 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""Two-Factor Authentication service supporting TOTP and email-based 2FA."""
from __future__ import annotations
import secrets
from typing import Literal
import pyotp
from src.core.config.setting import get_settings
from src.core.email.service import EmailService
from src.modules.user.domain.entities.user import User
from src.modules.user.domain.repositories.user_repository import UserRepository
from src.shared.unit_of_work import UnitOfWork
class TwoFactorAuthService:
"""Service for managing two-factor authentication.
Supports:
- TOTP (Time-based One-Time Password) for authenticator apps like Google Authenticator, Authy, etc.
- Email-based 2FA codes
"""
def __init__(
self,
user_repository: UserRepository,
unit_of_work: UnitOfWork,
email_service: EmailService | None = None,
):
self._user_repository = user_repository
self._unit_of_work = unit_of_work
self._email_service = email_service
self._settings = get_settings()
async def setup_totp(self, user_id: int) -> dict[str, str]:
"""Set up TOTP for a user.
Returns:
dict with 'secret', 'uri', and 'qr_code_data' keys
"""
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user or not user.security:
raise ValueError("User not found")
# Generate a new secret
secret = pyotp.random_base32()
# Create TOTP URI for QR code generation
issuer = self._settings.JWT_ISSUER or "TodoApp"
uri = pyotp.totp.TOTP(secret).provisioning_uri(
name=user.email, issuer_name=issuer
)
# Store the secret temporarily (not enabled yet)
user.security.two_factor_secret = secret
user.security.two_factor_enabled = False
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return {
"secret": secret,
"uri": uri,
"qr_code_data": f"otpauth://totp/{issuer}:{user.email}?secret={secret}&issuer={issuer}",
}
async def verify_totp_setup(self, user_id: int, code: str) -> dict[str, list[str]]:
"""Verify TOTP setup and enable 2FA.
Args:
user_id: The user's ID
code: The TOTP code from the authenticator app
Returns:
dict with 'backup_codes' key containing recovery codes
"""
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user or not user.security:
raise ValueError("User not found")
if not user.security.two_factor_secret:
raise ValueError("TOTP not set up. Call setup_totp first.")
# Verify the code
totp = pyotp.TOTP(user.security.two_factor_secret)
if not totp.verify(code, valid_window=1):
raise ValueError("Invalid TOTP code")
# Generate backup codes
backup_codes = [secrets.token_hex(4) for _ in range(10)]
# Enable 2FA and store backup codes
user.security.two_factor_enabled = True
user.security.two_factor_backup_codes = ",".join(backup_codes)
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return {"backup_codes": backup_codes}
async def disable_totp(self, user_id: int, code: str) -> bool:
"""Disable TOTP 2FA for a user.
Args:
user_id: The user's ID
code: Current TOTP code or backup code for verification
Returns:
True if successfully disabled
"""
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user or not user.security:
raise ValueError("User not found")
if not user.security.two_factor_enabled:
raise ValueError("2FA is not enabled")
# Verify code
verified = False
# Check if it's a backup code
if user.security.two_factor_backup_codes:
backup_codes = user.security.two_factor_backup_codes.split(",")
if code in backup_codes:
backup_codes.remove(code)
user.security.two_factor_backup_codes = ",".join(backup_codes)
verified = True
# Check if it's a TOTP code
if not verified and user.security.two_factor_secret:
totp = pyotp.TOTP(user.security.two_factor_secret)
if totp.verify(code, valid_window=1):
verified = True
if not verified:
raise ValueError("Invalid verification code")
# Disable 2FA
user.security.two_factor_enabled = False
user.security.two_factor_secret = None
user.security.two_factor_backup_codes = None
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return True
async def send_email_2fa_code(self, user_id: int) -> bool:
"""Send a 2FA code via email.
Args:
user_id: The user's ID
Returns:
True if email was sent successfully
"""
if self._email_service is None:
raise ValueError("Email service not configured")
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user:
raise ValueError("User not found")
# Generate a 6-digit code
code = secrets.token_hex(3)[:6]
# Store the code temporarily in security settings (with expiry info)
# In production, you'd want to store this in Redis with TTL
if not user.security:
raise ValueError("User security not found")
# Store code with timestamp (format: "code:timestamp")
import time
user.security.two_factor_secret = f"email_code:{code}:{int(time.time())}"
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
# Send email
html_body = f"""
<html>
<body>
<h2>Your Verification Code</h2>
<p>Your verification code is: <strong>{code}</strong></p>
<p>This code will expire in 10 minutes.</p>
<p>If you didn't request this code, please ignore this email.</p>
</body>
</html>
"""
await self._email_service.send_email(
to=user.email,
subject="Your Verification Code",
html_body=html_body,
)
return True
async def verify_email_2fa_code(self, user_id: int, code: str) -> bool:
"""Verify an email-based 2FA code.
Args:
user_id: The user's ID
code: The code received via email
Returns:
True if code is valid
"""
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user or not user.security:
raise ValueError("User not found")
stored = user.security.two_factor_secret
if not stored or not stored.startswith("email_code:"):
raise ValueError("No pending email verification code")
parts = stored.split(":")
if len(parts) != 3:
raise ValueError("Invalid code format")
stored_code = parts[1]
timestamp = int(parts[2])
import time
current_time = int(time.time())
# Code expires after 10 minutes
if current_time - timestamp > 600:
raise ValueError("Code has expired")
if stored_code != code:
raise ValueError("Invalid code")
# Clear the stored code
user.security.two_factor_secret = None
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return True
async def verify_2fa_code(
self, user: User, code: str, method: Literal["totp", "email", "backup"] = "totp"
) -> bool:
"""Verify a 2FA code using the specified method.
Args:
user: The user entity
code: The verification code
method: The verification method ('totp', 'email', or 'backup')
Returns:
True if verification successful
"""
if not user.security:
raise ValueError("User security not found")
if method == "totp":
if (
not user.security.two_factor_secret
or not user.security.two_factor_enabled
):
raise ValueError("TOTP 2FA is not enabled")
totp = pyotp.TOTP(user.security.two_factor_secret)
return bool(totp.verify(code, valid_window=1))
elif method == "backup":
if not user.security.two_factor_backup_codes:
raise ValueError("No backup codes available")
backup_codes = user.security.two_factor_backup_codes.split(",")
if code in backup_codes:
# Remove used backup code
backup_codes.remove(code)
user.security.two_factor_backup_codes = ",".join(backup_codes)
async with self._unit_of_work:
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return True
return False
elif method == "email":
return await self.verify_email_2fa_code(user.id, code)
return False
async def regenerate_backup_codes(
self, user_id: int, verify_code: str
) -> dict[str, list[str]]:
"""Regenerate backup codes for a user.
Args:
user_id: The user's ID
verify_code: Current TOTP code for verification
Returns:
dict with 'backup_codes' key containing new recovery codes
"""
async with self._unit_of_work:
user = await self._user_repository.get_by_id_with_relations(user_id)
if not user or not user.security:
raise ValueError("User not found")
if not user.security.two_factor_enabled:
raise ValueError("2FA must be enabled to regenerate backup codes")
# Verify TOTP code
if user.security.two_factor_secret:
totp = pyotp.TOTP(user.security.two_factor_secret)
if not totp.verify(verify_code, valid_window=1):
raise ValueError("Invalid TOTP code")
# Generate new backup codes
backup_codes = [secrets.token_hex(4) for _ in range(10)]
user.security.two_factor_backup_codes = ",".join(backup_codes)
await self._user_repository.save_security(user.security)
await self._unit_of_work.commit()
return {"backup_codes": backup_codes}