File size: 1,766 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Password hashing, access tokens (JWT) and opaque single-use tokens (refresh, password reset)."""

import hashlib
import secrets
from datetime import UTC, datetime, timedelta
from uuid import UUID

import jwt
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError

from app.core.config import get_settings
from app.core.errors import Unauthenticated

_hasher = PasswordHasher()
_ALGORITHM = "HS256"


def hash_password(password: str) -> str:
    return _hasher.hash(password)


def verify_password(password: str, password_hash: str | None) -> bool:
    if not password_hash:
        return False
    try:
        return _hasher.verify(password_hash, password)
    except (VerificationError, InvalidHashError):
        return False


def create_access_token(account_id: UUID) -> tuple[str, int]:
    """Returns (token, expires_in_seconds)."""
    settings = get_settings()
    now = datetime.now(UTC)
    claims = {"sub": str(account_id), "typ": "access", "iat": now,
              "exp": now + timedelta(seconds=settings.access_token_ttl_s)}
    return jwt.encode(claims, settings.jwt_secret, algorithm=_ALGORITHM), settings.access_token_ttl_s


def decode_access_token(token: str) -> UUID:
    try:
        claims = jwt.decode(token, get_settings().jwt_secret, algorithms=[_ALGORITHM])
        if claims.get("typ") != "access":
            raise Unauthenticated()
        return UUID(claims["sub"])
    except (jwt.PyJWTError, KeyError, ValueError) as exc:
        raise Unauthenticated() from exc


def new_opaque_token() -> str:
    return secrets.token_urlsafe(48)


def hash_token(token: str) -> str:
    """Opaque tokens are stored only as SHA-256 hashes."""
    return hashlib.sha256(token.encode()).hexdigest()