from datetime import datetime, timedelta, timezone
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
from .two_factor import verify_totp_code # Import verify_totp_code
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password, hashed_password):
password_bytes = plain_password[:72].encode("utf-8")
hashed_bytes = (
hashed_password.encode("utf-8")
if isinstance(hashed_password, str)
else hashed_password
)
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")
async def authenticate_user(
username: str, password: str, two_factor_code: Optional[str] = None
):
user = await User.get_or_none(username=username)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
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,
):
to_encode = data.copy()
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.update({"exp": expire, "2fa_verified": two_factor_verified})
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")
two_factor_verified: bool = payload.get("2fa_verified", False)
if username is None:
raise credentials_exception
token_data = TokenData(
username=username, two_factor_verified=two_factor_verified
)
except JWTError:
raise credentials_exception
user = await User.get_or_none(username=token_data.username)
if user is None:
raise credentials_exception
user.token_data = token_data # Attach token_data to user for easy access
return user
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