-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
86 lines (75 loc) · 2.83 KB
/
main.py
File metadata and controls
86 lines (75 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from fastapi import FastAPI, Response, Depends, HTTPException, status, Request
from fastapi.security import APIKeyCookie
import bcrypt
from auth import COOKIE_NAME, generate_secure_session_id
from db import delete_session, get_session, get_user, save_session
from dto import LoginRequest
app = FastAPI()
cookie_sec = APIKeyCookie(name=COOKIE_NAME, auto_error=False)
@app.post("/login")
async def login(response: Response, credentials: LoginRequest = Depends()):
username = credentials.username
password = credentials.password
user = get_user(username)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
if not bcrypt.checkpw(password.encode("utf-8"), user.get("password")):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
session_id = generate_secure_session_id(username)
save_session(username, session_id)
# Set the token in an HttpOnly cookie
response.set_cookie(
key=COOKIE_NAME,
value=session_id,
httponly=True, # Prevents JavaScript access
# secure=True, # Only sent over HTTPS
max_age=3600, # Cookie valid for 1 hour
)
return {"message": "Login successful"}
@app.post("/logout")
def logout(request: Request, response: Response):
cookie = request.cookies.get(COOKIE_NAME)
if not cookie:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
user = delete_session(cookie)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
response.delete_cookie(key=COOKIE_NAME)
return {"message": "Logout successful"}
def get_current_user(request: Request, session_id: str = Depends(cookie_sec)):
if not session_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
user = get_session(session_id)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid session id",
headers={"WWW-Authenticate": "Bearer"},
)
return {
"username": user.get("username"),
"id": user.get("id"),
} # Return the user object
@app.get("/profile")
def read_profile(user: dict = Depends(get_current_user)):
return {"message": f"Welcome {user['username']}"}