-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemail_verification_store.py
More file actions
426 lines (354 loc) · 13.8 KB
/
email_verification_store.py
File metadata and controls
426 lines (354 loc) · 13.8 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Database operations for email verification.
All operations use the main harvest.db database.
"""
import sqlite3
import hashlib
import secrets
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, Tuple
from email_config import OTP_CONFIG
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def hash_ip(ip_address: str, salt: str = "") -> str:
"""Hash IP address for privacy."""
if not ip_address:
return ""
return hashlib.sha256((salt + ip_address).encode()).hexdigest()[:16]
def init_verification_tables(db_path: str) -> bool:
"""
Initialize email verification tables in the database.
Args:
db_path: Path to SQLite database
Returns:
True if successful, False otherwise
"""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
# Email verification codes table
cur.execute("""
CREATE TABLE IF NOT EXISTS email_verifications (
email TEXT PRIMARY KEY,
code_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
attempts INTEGER DEFAULT 0,
last_attempt_at TEXT,
ip_address_hash TEXT
);
""")
# Verified email sessions table
cur.execute("""
CREATE TABLE IF NOT EXISTS verified_sessions (
session_id TEXT PRIMARY KEY,
email TEXT NOT NULL,
verified_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
ip_address_hash TEXT
);
""")
# Indexes for performance
cur.execute("""
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
ON email_verifications(expires_at);
""")
cur.execute("""
CREATE INDEX IF NOT EXISTS idx_verified_sessions_expires
ON verified_sessions(expires_at);
""")
# Rate limiting table
cur.execute("""
CREATE TABLE IF NOT EXISTS email_verification_rate_limit (
email TEXT NOT NULL,
timestamp TEXT NOT NULL,
ip_address_hash TEXT
);
""")
cur.execute("""
CREATE INDEX IF NOT EXISTS idx_rate_limit_email_time
ON email_verification_rate_limit(email, timestamp);
""")
conn.commit()
return True
except Exception as e:
print(f"Error initializing verification tables: {e}")
return False
def check_rate_limit(db_path: str, email: str, ip_address: str = None, salt: str = "") -> Tuple[bool, str]:
"""
Check if email has exceeded rate limit for code requests.
Args:
db_path: Path to SQLite database
email: Email address to check
ip_address: Optional IP address for additional tracking
salt: Salt for IP hashing
Returns:
Tuple of (allowed: bool, message: str)
"""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
# Get rate limit window
window_start = datetime.utcnow() - timedelta(
seconds=OTP_CONFIG["rate_limit_window_seconds"]
)
# Count codes sent in window
cur.execute("""
SELECT COUNT(*) FROM email_verification_rate_limit
WHERE email = ? AND timestamp > ?
""", (email.strip().lower(), window_start.isoformat()))
count = cur.fetchone()[0]
if count >= OTP_CONFIG["rate_limit_codes"]:
return False, f"Rate limit exceeded. Maximum {OTP_CONFIG['rate_limit_codes']} codes per hour."
return True, "Rate limit OK"
except Exception as e:
print(f"Error checking rate limit: {e}")
return True, "Rate limit check failed, allowing"
def record_code_request(db_path: str, email: str, ip_address: str = None, salt: str = "") -> bool:
"""Record a code request for rate limiting."""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
ip_hash = hash_ip(ip_address, salt) if ip_address else None
cur.execute("""
INSERT INTO email_verification_rate_limit
(email, timestamp, ip_address_hash)
VALUES (?, ?, ?)
""", (
email.strip().lower(),
datetime.utcnow().isoformat(),
ip_hash
))
conn.commit()
return True
except Exception as e:
logger.error(f"Error recording code request: {e}")
return False
def store_verification_code(
db_path: str,
email: str,
code_hash: str,
expiry_seconds: int = None,
ip_address: str = None,
salt: str = ""
) -> bool:
"""Store verification code in database."""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
if expiry_seconds is None:
expiry_seconds = OTP_CONFIG["code_expiry_seconds"]
now = datetime.utcnow()
expires = now + timedelta(seconds=expiry_seconds)
ip_hash = hash_ip(ip_address, salt) if ip_address else None
cur.execute("""
INSERT OR REPLACE INTO email_verifications
(email, code_hash, created_at, expires_at, attempts, ip_address_hash)
VALUES (?, ?, ?, ?, 0, ?)
""", (
email.strip().lower(),
code_hash,
now.isoformat(),
expires.isoformat(),
ip_hash
))
conn.commit()
return True
except Exception as e:
logger.error(f"Error storing verification code: {e}")
return False
def verify_code(
db_path: str,
email: str,
code: str,
verify_func
) -> Dict[str, any]:
"""
Verify code for email.
Args:
db_path: Path to database
email: Email address
code: Plain text code to verify
verify_func: Function to verify code hash (from email_service)
Returns:
Dict with 'valid', 'expired', 'attempts_exceeded', 'message' keys
"""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
# Get verification record
cur.execute("""
SELECT code_hash, expires_at, attempts
FROM email_verifications
WHERE email = ?
""", (email.strip().lower(),))
row = cur.fetchone()
if not row:
return {
'valid': False,
'expired': False,
'attempts_exceeded': False,
'message': 'No verification code found for this email'
}
stored_hash, expires_at, attempts = row
# Check expiry
expires_dt = datetime.fromisoformat(expires_at)
if datetime.utcnow() > expires_dt:
return {
'valid': False,
'expired': True,
'attempts_exceeded': False,
'message': 'Verification code has expired'
}
# Check attempts
if attempts >= OTP_CONFIG["max_attempts"]:
return {
'valid': False,
'expired': False,
'attempts_exceeded': True,
'message': f'Maximum verification attempts ({OTP_CONFIG["max_attempts"]}) exceeded'
}
# Increment attempts
cur.execute("""
UPDATE email_verifications
SET attempts = attempts + 1,
last_attempt_at = ?
WHERE email = ?
""", (datetime.utcnow().isoformat(), email.strip().lower()))
# Verify code using constant-time comparison to prevent timing attacks
# The verify_func should internally use secrets.compare_digest()
if verify_func(code, stored_hash):
# Delete verification record (one-time use)
cur.execute("DELETE FROM email_verifications WHERE email = ?",
(email.strip().lower(),))
conn.commit()
logger.info(f"Code verified successfully for email: {email[:3]}***@{email.split('@')[1] if '@' in email else 'unknown'}")
return {
'valid': True,
'expired': False,
'attempts_exceeded': False,
'message': 'Code verified successfully'
}
else:
conn.commit()
remaining = OTP_CONFIG["max_attempts"] - attempts - 1
logger.warning(f"Invalid code attempt for email: {email[:3]}***@{email.split('@')[1] if '@' in email else 'unknown'}, {remaining} attempts remaining")
return {
'valid': False,
'expired': False,
'attempts_exceeded': False,
'message': f'Invalid code. {remaining} attempts remaining'
}
except Exception as e:
print(f"Error verifying code: {e}")
return {
'valid': False,
'expired': False,
'attempts_exceeded': False,
'message': f'Error verifying code: {str(e)}'
}
def create_verified_session(
db_path: str,
session_id: str,
email: str,
expiry_seconds: int = None,
ip_address: str = None,
salt: str = ""
) -> bool:
"""Create verified session for email."""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
if expiry_seconds is None:
expiry_seconds = OTP_CONFIG["session_expiry_seconds"]
now = datetime.utcnow()
expires = now + timedelta(seconds=expiry_seconds)
ip_hash = hash_ip(ip_address, salt) if ip_address else None
cur.execute("""
INSERT OR REPLACE INTO verified_sessions
(session_id, email, verified_at, expires_at, ip_address_hash)
VALUES (?, ?, ?, ?, ?)
""", (
session_id,
email.strip().lower(),
now.isoformat(),
expires.isoformat(),
ip_hash
))
conn.commit()
return True
except Exception as e:
print(f"Error creating verified session: {e}")
return False
def check_verified_session(db_path: str, session_id: str) -> Optional[str]:
"""
Check if session is verified and not expired.
Returns email if valid, None otherwise.
"""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
cur.execute("""
SELECT email, expires_at
FROM verified_sessions
WHERE session_id = ?
""", (session_id,))
row = cur.fetchone()
if not row:
return None
email, expires_at = row
expires_dt = datetime.fromisoformat(expires_at)
if datetime.utcnow() > expires_dt:
# Expired, delete it
cur.execute("DELETE FROM verified_sessions WHERE session_id = ?",
(session_id,))
conn.commit()
return None
return email
except Exception as e:
print(f"Error checking verified session: {e}")
return None
def cleanup_expired_records(db_path: str) -> Dict[str, int]:
"""
Cleanup expired verification codes and sessions.
Returns count of deleted records.
"""
try:
with sqlite3.connect(db_path) as conn:
cur = conn.cursor()
now = datetime.utcnow().isoformat()
# Delete expired verification codes
cur.execute("""
DELETE FROM email_verifications
WHERE expires_at < ?
""", (now,))
verifications_deleted = cur.rowcount
# Delete expired sessions
cur.execute("""
DELETE FROM verified_sessions
WHERE expires_at < ?
""", (now,))
sessions_deleted = cur.rowcount
# Delete old rate limit records
cutoff = (datetime.utcnow() - timedelta(days=7)).isoformat()
cur.execute("""
DELETE FROM email_verification_rate_limit
WHERE timestamp < ?
""", (cutoff,))
rate_limit_deleted = cur.rowcount
conn.commit()
return {
'verifications': verifications_deleted,
'sessions': sessions_deleted,
'rate_limits': rate_limit_deleted
}
except Exception as e:
print(f"Error cleaning up expired records: {e}")
return {'verifications': 0, 'sessions': 0, 'rate_limits': 0}