Spaces:
Paused
Paused
File size: 3,636 Bytes
5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 0243ced 5eb4857 | 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 | """
Security utilities: password hashing and JWT token generation.
"""
from datetime import datetime, timedelta, timezone
from typing import Any, Union
from uuid import uuid4
from jose import jwt
from passlib.context import CryptContext
from core.config import get_settings
settings = get_settings()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verifies a plain password against a hashed one."""
try:
return pwd_context.verify(plain_password, hashed_password)
except ValueError:
return False
def get_password_hash(password: str) -> str:
"""Hashes a password using bcrypt."""
return pwd_context.hash(password)
def create_access_token(subject: Union[str, Any], workspace_id: Union[str, Any] = None, role: str = None, expires_delta: timedelta = None) -> str:
"""Creates a short-lived JWT access token with a unique jti for revocation support."""
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {
"exp": expire,
"sub": str(subject),
"jti": str(uuid4()),
"workspace_id": str(workspace_id) if workspace_id else None,
"role": role,
"type": "access"
}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def create_refresh_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str:
"""Creates a long-lived JWT refresh token with a unique jti for revocation support."""
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
to_encode = {"exp": expire, "sub": str(subject), "jti": str(uuid4()), "type": "refresh"}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def create_reset_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str:
"""Creates a short-lived password reset token with type 'reset'. Cannot be used as an access token."""
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
to_encode = {"exp": expire, "sub": str(subject), "jti": str(uuid4()), "type": "reset"}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def create_ws_ticket(subject: Union[str, Any], workspace_id: Union[str, Any] = None, role: str = None) -> str:
"""
Creates a 60-second single-use WebSocket authentication ticket.
Clients call POST /auth/ws-ticket/ immediately before opening a WebSocket
connection so they always authenticate with a fresh credential even when
their long-lived access token is near expiry.
"""
expire = datetime.now(timezone.utc) + timedelta(seconds=60)
to_encode = {
"exp": expire,
"sub": str(subject),
"jti": str(uuid4()),
"workspace_id": str(workspace_id) if workspace_id else None,
"role": role,
"type": "ws_ticket",
}
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def decode_access_token(token: str) -> dict:
"""Decodes and validates a JWT access token."""
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|