Spaces:
Sleeping
Sleeping
File size: 6,972 Bytes
453520f | 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 | """
Security utilities for EVG Ultimate Team.
Provides functions for password hashing, token generation, and authentication.
"""
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.config import get_settings
settings = get_settings()
# =============================================================================
# Password Hashing
# =============================================================================
# Password context for hashing and verification
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
"""
Hash a password using bcrypt.
Args:
password: Plain text password
Returns:
Hashed password string
Example:
>>> hashed = hash_password("my_password")
>>> print(hashed)
$2b$12$...
"""
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify a password against a hashed password.
Args:
plain_password: Plain text password to verify
hashed_password: Hashed password to compare against
Returns:
True if password matches, False otherwise
Example:
>>> hashed = hash_password("my_password")
>>> verify_password("my_password", hashed)
True
>>> verify_password("wrong_password", hashed)
False
"""
return pwd_context.verify(plain_password, hashed_password)
# =============================================================================
# JWT Token Generation and Verification
# =============================================================================
# Algorithm for JWT encoding/decoding
ALGORITHM = "HS256"
# Token expiration time (7 days for this event)
ACCESS_TOKEN_EXPIRE_DAYS = 7
def create_access_token(
data: dict,
expires_delta: Optional[timedelta] = None
) -> str:
"""
Create a JWT access token.
Args:
data: Dictionary of data to encode in the token
expires_delta: Optional custom expiration time
Returns:
Encoded JWT token string
Example:
>>> token = create_access_token({"sub": "user_5", "is_admin": False})
>>> print(token)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
"""
to_encode = data.copy()
# Set expiration time
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire})
# Encode and return token
encoded_jwt = jwt.encode(
to_encode,
settings.secret_key,
algorithm=ALGORITHM
)
return encoded_jwt
def decode_access_token(token: str) -> Optional[dict]:
"""
Decode and verify a JWT access token.
Args:
token: JWT token string to decode
Returns:
Decoded token data as dictionary, or None if invalid
Example:
>>> token = create_access_token({"sub": "user_5"})
>>> payload = decode_access_token(token)
>>> print(payload["sub"])
user_5
"""
try:
payload = jwt.decode(
token,
settings.secret_key,
algorithms=[ALGORITHM]
)
return payload
except JWTError:
return None
def verify_token(token: str) -> dict:
"""
Verify a JWT access token and return payload.
Args:
token: JWT token string to verify
Returns:
Decoded token data as dictionary
Raises:
JWTError: If token is invalid or expired
Example:
>>> token = create_access_token({"sub": "user_5"})
>>> payload = verify_token(token)
>>> print(payload["sub"])
user_5
"""
payload = jwt.decode(
token,
settings.secret_key,
algorithms=[ALGORITHM]
)
return payload
# =============================================================================
# Admin Authentication
# =============================================================================
def verify_admin_credentials(username: str, password: str) -> bool:
"""
Verify admin credentials against environment configuration.
Args:
username: Admin username
password: Admin password
Returns:
True if credentials are valid, False otherwise
Example:
>>> verify_admin_credentials("clement", "evg2026_admin")
True
>>> verify_admin_credentials("clement", "wrong_password")
False
"""
return (
username.lower() == settings.admin_username.lower() and
password == settings.admin_password
)
# =============================================================================
# Token Payload Helpers
# =============================================================================
def create_participant_token_data(participant_id: int, username: str, is_groom: bool = False) -> dict:
"""
Create token payload for a participant.
Args:
participant_id: Participant's ID
username: Participant's username
is_groom: Whether participant is the groom
Returns:
Dictionary with token payload data
Example:
>>> data = create_participant_token_data(5, "Hugo F.")
>>> token = create_access_token(data)
"""
return {
"sub": f"participant_{participant_id}",
"user_id": participant_id,
"username": username,
"is_admin": False,
"is_groom": is_groom,
"type": "participant"
}
def create_admin_token_data(admin_id: int, username: str) -> dict:
"""
Create token payload for an admin.
Args:
admin_id: Admin's ID (can be 0 for the main admin)
username: Admin's username
Returns:
Dictionary with token payload data
Example:
>>> data = create_admin_token_data(0, "clement")
>>> token = create_access_token(data)
"""
return {
"sub": f"admin_{admin_id}",
"user_id": admin_id,
"username": username,
"is_admin": True,
"is_groom": False,
"type": "admin"
}
def extract_user_id_from_payload(payload: dict) -> Optional[int]:
"""
Extract user ID from token payload.
Args:
payload: Decoded JWT payload
Returns:
User ID if present, None otherwise
Example:
>>> payload = {"user_id": 5}
>>> extract_user_id_from_payload(payload)
5
"""
return payload.get("user_id")
def is_admin_token(payload: dict) -> bool:
"""
Check if token payload represents an admin user.
Args:
payload: Decoded JWT payload
Returns:
True if admin, False otherwise
Example:
>>> payload = {"is_admin": True}
>>> is_admin_token(payload)
True
"""
return payload.get("is_admin", False)
|