Coverage for backend/app/routers/login.py: 94%
17 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-22 15:38 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-22 15:38 +0000
1"""Authentication route"""
3from datetime import datetime, timezone
4from fastapi import APIRouter, Depends, HTTPException, status
5from fastapi.security import OAuth2PasswordRequestForm
6from sqlalchemy.orm import Session
8from app import utils, models, database, schemas, oauth2
10router = APIRouter(prefix="/login", tags=["Authentication"])
13@router.post("/", status_code=status.HTTP_200_OK, response_model=schemas.Token)
14def login(
15 user_credentials: OAuth2PasswordRequestForm = Depends(),
16 db: Session = Depends(database.get_db),
17) -> dict:
18 """Login a user.
19 :param user_credentials: The user credentials (note: username is the email field).
20 :param db: The database session.
21 :returns: The access token."""
23 # Find the user in the list based on the email provided
24 user = db.query(models.User).filter(user_credentials.username.strip() == models.User.email).first()
25 if user is None:
26 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User not found")
28 # Check that the password corresponds to that user
29 if not utils.verify_password(user_credentials.password, user.password):
30 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Incorrect password")
32 # Update the user last login
33 user.last_login = datetime.now(timezone.utc)
34 db.commit()
36 # Create an access token and return it
37 access_token = oauth2.create_access_token(data={"user_id": user.id})
38 return {"access_token": access_token, "token_type": "bearer"}