Basic user model and login authentication :]
This commit is contained in:
parent
a87ed0b0f3
commit
859d2e7a98
8 changed files with 315 additions and 4 deletions
45
app/routers/user_route.py
Normal file
45
app/routers/user_route.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
from datetime import timedelta
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
|
||||
from app.config import Settings
|
||||
from app.logic.user_logic import (
|
||||
authenticate_user,
|
||||
create_access_token,
|
||||
get_current_user,
|
||||
)
|
||||
from app.models.token import Token
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def get_default():
|
||||
return {"message": "Root for Users API"}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def read_me(current_user: Annotated[User, Depends(get_current_user)]):
|
||||
return current_user
|
||||
|
||||
|
||||
@router.post("/token")
|
||||
async def login_for_access_token(
|
||||
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
|
||||
) -> Token:
|
||||
user = authenticate_user(form_data.username, form_data.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
access_token_expires = timedelta(minutes=Settings.access_token_expire_minutes)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.username},
|
||||
expires_delta=access_token_expires,
|
||||
)
|
||||
return Token(access_token=access_token, token_type="bearer")
|
||||
Loading…
Reference in a new issue