aboutsummaryrefslogtreecommitdiff
path: root/api/routes/auth_routes.py
diff options
context:
space:
mode:
authorParker <contact@pkrm.dev>2024-11-10 16:36:16 -0600
committerParker <contact@pkrm.dev>2024-11-10 16:36:16 -0600
commit691aa744a0398f185b3ca98a36fbd83806c7786c (patch)
tree7840f31c30bb6eda903abd6bbf4dbfb2ac590966 /api/routes/auth_routes.py
parent8941213c8d94f3ad84e07e467e78105dc7fed734 (diff)
TOO MUCH STUFF
Diffstat (limited to 'api/routes/auth_routes.py')
-rw-r--r--api/routes/auth_routes.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/api/routes/auth_routes.py b/api/routes/auth_routes.py
new file mode 100644
index 0000000..c51557f
--- /dev/null
+++ b/api/routes/auth_routes.py
@@ -0,0 +1,46 @@
+from fastapi import Depends, APIRouter, status, HTTPException
+from fastapi.security import OAuth2PasswordRequestForm
+from fastapi.responses import Response, JSONResponse
+from datetime import timedelta
+from typing import Annotated
+
+from api.util.authentication import (
+ create_access_token,
+ authenticate_user,
+)
+from api.util.db_dependency import get_db
+
+
+router = APIRouter(prefix="/auth", tags=["auth"])
+
+
+@router.post("/token", summary="Authenticate and get an access token")
+async def login_for_access_token(
+ form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
+ response: Response,
+ db=Depends(get_db),
+):
+ """
+ Return an access token for the user, if the given authentication details are correct
+ """
+ user = authenticate_user(db, 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=1)
+ access_token = create_access_token(
+ data={"sub": user.id, "username": user.username},
+ expires_delta=access_token_expires,
+ )
+ response = JSONResponse(content={"success": True})
+ response.set_cookie(
+ key="access_token",
+ value=access_token,
+ httponly=True, # Prevents client-side access
+ # secure=True, # Cookies are only sent over HTTPS
+ )
+ return response