forked from mtusi2026/mtusi2026lab4
lab4
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
from sessions import SessionStore
|
||||
|
||||
PASSWORD_MIN = 12
|
||||
PASSWORD_MAX = 128
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def now_iso():
|
||||
return datetime.now(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def validate_password(password):
|
||||
if not isinstance(password, str):
|
||||
return False
|
||||
length = len(password)
|
||||
return PASSWORD_MIN <= length <= PASSWORD_MAX
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
|
||||
|
||||
def parse_basic_auth(header_value):
|
||||
if not header_value or not header_value.startswith('Basic '):
|
||||
return None
|
||||
encoded = header_value[6:].strip()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded, validate=True).decode('utf-8')
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
return None
|
||||
if ':' not in decoded:
|
||||
return None
|
||||
username, password = decoded.split(':', 1)
|
||||
if not username:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer_token(header_value):
|
||||
if not header_value or not header_value.startswith('Bearer '):
|
||||
return None
|
||||
token = header_value[7:].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def session_ttl_seconds():
|
||||
try:
|
||||
ttl = int(os.environ.get('SESSION_TTL_SECONDS', '3600'))
|
||||
except ValueError:
|
||||
ttl = 3600
|
||||
return max(1, ttl)
|
||||
|
||||
|
||||
def create_session(store: SessionStore, user_id):
|
||||
token = secrets.token_urlsafe(32)
|
||||
ttl = session_ttl_seconds()
|
||||
expires_at = (
|
||||
datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
store.create(token, user_id, ttl)
|
||||
return token, expires_at
|
||||
Reference in New Issue
Block a user