46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
from typing import Optional
|
|
from sqlalchemy.orm import Session
|
|
from app.models.user import User
|
|
from app.core.security import verify_password, create_access_token
|
|
from app.core.exceptions import AuthException, ForbiddenException
|
|
from app.schemas.auth import TokenResponse, UserSummary
|
|
from app.config import settings
|
|
|
|
|
|
def authenticate_user(db: Session, username_or_email: str, password: str) -> Optional[User]:
|
|
"""Finds user by username or email and verifies argon2 password hash."""
|
|
user = db.query(User).filter(
|
|
(User.username == username_or_email) | (User.email == username_or_email)
|
|
).first()
|
|
|
|
if not user:
|
|
return None
|
|
if not verify_password(password, user.hashed_password):
|
|
return None
|
|
return user
|
|
|
|
|
|
def login_user(db: Session, username_or_email: str, password: str) -> TokenResponse:
|
|
"""Authenticates credentials and generates signed JWT token."""
|
|
user = authenticate_user(db, username_or_email, password)
|
|
if not user:
|
|
raise AuthException("Incorrect username or password")
|
|
|
|
if not user.is_active:
|
|
raise ForbiddenException("User account is inactive. Please contact your administrator.")
|
|
|
|
token = create_access_token(
|
|
data={
|
|
"sub": str(user.id),
|
|
"username": user.username,
|
|
"role": user.role,
|
|
}
|
|
)
|
|
|
|
return TokenResponse(
|
|
access_token=token,
|
|
token_type="Bearer",
|
|
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
|
user=UserSummary.model_validate(user)
|
|
)
|