84 lines
3.5 KiB
Python
Raw Normal View History

2025-11-13 23:05:26 +01:00
from datetime import datetime, timedelta, timezone
2025-11-09 23:29:07 +01:00
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
import bcrypt
from .schemas import TokenData
from .settings import settings
from .models import User
2025-11-10 01:58:41 +01:00
from .two_factor import verify_totp_code # Import verify_totp_code
2025-11-09 23:29:07 +01:00
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password, hashed_password):
password_bytes = plain_password[:72].encode('utf-8')
2025-11-10 15:46:40 +01:00
hashed_bytes = hashed_password.encode('utf-8') if isinstance(hashed_password, str) else hashed_password
2025-11-09 23:29:07 +01:00
return bcrypt.checkpw(password_bytes, hashed_bytes)
def get_password_hash(password):
password_bytes = password[:72].encode('utf-8')
return bcrypt.hashpw(password_bytes, bcrypt.gensalt()).decode('utf-8')
2025-11-10 01:58:41 +01:00
async def authenticate_user(username: str, password: str, two_factor_code: Optional[str] = None):
2025-11-09 23:29:07 +01:00
user = await User.get_or_none(username=username)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
2025-11-10 01:58:41 +01:00
if user.is_2fa_enabled:
if not two_factor_code:
return {"user": user, "2fa_required": True}
if not verify_totp_code(user.two_factor_secret, two_factor_code):
return None # 2FA code is incorrect
return {"user": user, "2fa_required": False}
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None, two_factor_verified: bool = False):
2025-11-09 23:29:07 +01:00
to_encode = data.copy()
if expires_delta:
2025-11-13 23:05:26 +01:00
expire = datetime.now(timezone.utc) + expires_delta
2025-11-09 23:29:07 +01:00
else:
2025-11-13 23:05:26 +01:00
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
2025-11-10 01:58:41 +01:00
to_encode.update({"exp": expire, "2fa_verified": two_factor_verified})
2025-11-09 23:29:07 +01:00
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
username: str = payload.get("sub")
2025-11-10 01:58:41 +01:00
two_factor_verified: bool = payload.get("2fa_verified", False)
2025-11-09 23:29:07 +01:00
if username is None:
raise credentials_exception
2025-11-10 01:58:41 +01:00
token_data = TokenData(username=username, two_factor_verified=two_factor_verified)
2025-11-09 23:29:07 +01:00
except JWTError:
raise credentials_exception
user = await User.get_or_none(username=token_data.username)
if user is None:
raise credentials_exception
2025-11-10 01:58:41 +01:00
user.token_data = token_data # Attach token_data to user for easy access
2025-11-09 23:29:07 +01:00
return user
2025-11-10 01:58:41 +01:00
async def get_current_active_user(current_user: User = Depends(get_current_user)):
if not current_user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
async def get_current_verified_user(current_user: User = Depends(get_current_user)):
if current_user.is_2fa_enabled and not current_user.token_data.two_factor_verified:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="2FA required and not verified")
return current_user
async def get_current_admin_user(current_user: User = Depends(get_current_verified_user)):
if not current_user.is_superuser:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions")
return current_user