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-13 23:22:05 +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")
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
2025-11-09 23:29:07 +01:00
|
|
|
def verify_password(plain_password, hashed_password):
|
2025-11-13 23:22:05 +01:00
|
|
|
password_bytes = plain_password[:72].encode("utf-8")
|
|
|
|
|
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)
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
2025-11-09 23:29:07 +01:00
|
|
|
def get_password_hash(password):
|
2025-11-13 23:22:05 +01:00
|
|
|
password_bytes = password[:72].encode("utf-8")
|
|
|
|
|
return bcrypt.hashpw(password_bytes, bcrypt.gensalt()).decode("utf-8")
|
2025-11-09 23:29:07 +01:00
|
|
|
|
2025-11-13 23:22:05 +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):
|
2025-11-13 23:22:05 +01:00
|
|
|
return None # 2FA code is incorrect
|
2025-11-10 01:58:41 +01:00
|
|
|
return {"user": user, "2fa_required": False}
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
|
|
|
|
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:22:05 +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-13 23:22:05 +01:00
|
|
|
encoded_jwt = jwt.encode(
|
|
|
|
|
to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM
|
|
|
|
|
)
|
2025-11-09 23:29:07 +01:00
|
|
|
return encoded_jwt
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
2025-11-09 23:29:07 +01:00
|
|
|
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:
|
2025-11-13 23:22:05 +01:00
|
|
|
payload = jwt.decode(
|
|
|
|
|
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
|
|
|
|
)
|
2025-11-09 23:29:07 +01:00
|
|
|
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-13 23:22:05 +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-13 23:22:05 +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
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
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
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
2025-11-10 01:58:41 +01:00
|
|
|
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:
|
2025-11-13 23:22:05 +01:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="2FA required and not verified",
|
|
|
|
|
)
|
2025-11-10 01:58:41 +01:00
|
|
|
return current_user
|
|
|
|
|
|
2025-11-13 23:22:05 +01:00
|
|
|
|
|
|
|
|
async def get_current_admin_user(
|
|
|
|
|
current_user: User = Depends(get_current_verified_user),
|
|
|
|
|
):
|
2025-11-10 01:58:41 +01:00
|
|
|
if not current_user.is_superuser:
|
2025-11-13 23:22:05 +01:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions"
|
|
|
|
|
)
|
2025-11-10 01:58:41 +01:00
|
|
|
return current_user
|