fastapi-svelte-template/backend/todo/routes/auth.py

42 lines
1.4 KiB
Python
Raw Normal View History

2023-05-31 16:37:56 +01:00
"""This module contains endpoints for operations related to user authentication."""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from todo.database.engine import get_db
from todo.utils.exceptions import NotFoundException, create_exception_dict as fmt
import todo.auth.auth as auth
from todo.crud.users import read_user_by_email_with_password
from todo.schemas.users import UserLogin as UserLoginSchema
from todo.schemas.auth import AuthResponseToken
router = APIRouter(
prefix="/auth",
tags=["authentication"]
)
tag_metadata = {
"name": "authentication",
"description": "Operations related to user authentication."
}
2023-06-17 18:30:47 +01:00
@router.post("/login/", response_model=AuthResponseToken)
2023-05-31 16:37:56 +01:00
def login(credentials: UserLoginSchema, db: Session = Depends(get_db)):
"""Returns a JWT for the user whose credentials were provided.
The JWT can be submitted as a Bearer token on subsequent requests to authenticate
the user.
"""
try:
user = read_user_by_email_with_password(db, credentials.email)
except NotFoundException:
raise HTTPException(401, fmt("Invalid email or password."))
if not auth.AuthHandler().verify_password(credentials.password, user.password):
raise HTTPException(401, fmt("Invalid email or password."))
return AuthResponseToken(token=auth.AuthHandler().encode_token(user.id))