Spaces:
3SCError404
/
Paused

nexus / core /security.py
dushyantsingh0
backend stabilization
b7980f7
Raw History Blame Contribute Delete
2.86 kB
"""
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 decode_access_token(token: str) -> dict:
"""Decodes and validates a JWT access token."""
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])