forked from mtusi2026/mtusi2026lab2
lab2 complete
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import bcrypt
|
||||
import base64
|
||||
import secrets
|
||||
import os
|
||||
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Request, status
|
||||
from ..exceptions import ApiException
|
||||
from ..db import get_pool
|
||||
from ..utils import get_utc_now, authenticate_user, format_iso
|
||||
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
@router.post("/auth/sessions", status_code=status.HTTP_201_CREATED)
|
||||
async def create_session(request: Request):
|
||||
auth = request.headers.get("Authorization")
|
||||
auth_err_headers = {"WWW-Authenticate": 'Basic realm="messenger"'}
|
||||
|
||||
if not auth or not auth.startswith("Basic "):
|
||||
raise ApiException(401, "unauthorized", "Missing Basic auth", headers=auth_err_headers)
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(auth.split(" ", 1)[1]).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except Exception:
|
||||
raise ApiException(401, "unauthorized", "Invalid Basic format", headers=auth_err_headers)
|
||||
|
||||
pool = get_pool()
|
||||
user = await pool.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username)
|
||||
if not user:
|
||||
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
|
||||
|
||||
|
||||
if not bcrypt.checkpw(password.encode("utf-8"), user["password_hash"].encode("utf-8")):
|
||||
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
|
||||
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = get_utc_now()
|
||||
expires_at = now + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
|
||||
await pool.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at, revoked) VALUES ($1, $2, $3, FALSE)",
|
||||
token, user["id"], expires_at
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_iso(expires_at),
|
||||
"user": {
|
||||
"id": str(user["id"]),
|
||||
"username": user["username"],
|
||||
"display_name": user["display_name"],
|
||||
"created_at": format_iso(user["created_at"])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_current_session(request: Request):
|
||||
await authenticate_user(request)
|
||||
token = request.state.current_token
|
||||
pool = get_pool()
|
||||
await pool.execute("UPDATE sessions SET revoked = TRUE WHERE token = $1", token)
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user