-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.py
More file actions
79 lines (61 loc) · 2.39 KB
/
auth.py
File metadata and controls
79 lines (61 loc) · 2.39 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
"""
SkyModderAI - Authentication Utilities
Helper functions for authentication, OAuth state management, and session handling.
This module is designed to avoid circular imports.
"""
from __future__ import annotations
import logging
import secrets
from typing import Any, Optional
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
logger = logging.getLogger(__name__)
def make_state_token(secret_key: str, salt: str, next_url: str = "") -> str:
"""
Generate a signed state token for OAuth.
Args:
secret_key: Application secret key
salt: Salt for the token
next_url: URL to redirect to after OAuth completion
Returns:
Signed state token string
"""
s = URLSafeTimedSerializer(secret_key, salt=salt)
return s.dumps({"rnd": secrets.token_hex(16), "next": next_url[:200]})
def verify_state_token(
secret_key: str, salt: str, state: Optional[str], max_age: int = 600
) -> Optional[dict[str, Any]]:
"""
Verify the state token from OAuth.
Args:
secret_key: Application secret key
salt: Salt for the token
state: State token to verify
max_age: Maximum age of token in seconds
Returns:
Decoded token data if valid, None otherwise
"""
if not state:
return None
s = URLSafeTimedSerializer(secret_key, salt=salt)
try:
return s.loads(state, max_age=max_age) # type: ignore[no-any-return]
except (BadSignature, SignatureExpired):
return None
except Exception as e:
logger.warning(f"Unexpected error verifying state token: {e}")
return None
# Aliases for compatibility with existing code
def generate_verification_token(secret_key: str, email: str) -> str:
"""Generate a verification token for email confirmation."""
s = URLSafeTimedSerializer(secret_key, salt="email-verification")
return s.dumps(email)
def verify_verification_token(token: str, secret_key: str, max_age: int = 86400) -> Optional[str]:
"""Verify an email verification token. Returns email if valid."""
s = URLSafeTimedSerializer(secret_key, salt="email-verification")
try:
return s.loads(token, max_age=max_age) # type: ignore[no-any-return]
except (BadSignature, SignatureExpired):
return None
except Exception as e:
logger.warning(f"Unexpected error verifying verification token: {e}")
return None