-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_routes.py
More file actions
66 lines (52 loc) · 1.95 KB
/
Copy pathuser_routes.py
File metadata and controls
66 lines (52 loc) · 1.95 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
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlmodel import Session, select
from ..schema.base import get_session
from ..schema.user import User, UserCreate, UserPublic
from ..security import authenticate_user, hash_password
SessionDep = Annotated[Session, Depends(get_session)]
user_router = APIRouter(prefix="/api")
basic_auth_security = HTTPBasic()
@user_router.get("/users/{user_id}", response_model=UserPublic)
def get_user(
user_id: int,
session: SessionDep,
credentials: Annotated[HTTPBasicCredentials, Depends(basic_auth_security)],
):
username = credentials.username
password = credentials.password
user = session.exec(select(User).where(User.username == username)).first()
if not authenticate_user(user, password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
user = session.get(User, user_id)
return user
@user_router.get("/users", response_model=UserPublic)
def get_users(
session: SessionDep,
credentials: Annotated[HTTPBasicCredentials, Depends(basic_auth_security)],
):
username = credentials.username
password = credentials.password
user = session.exec(select(User).where(User.username == username)).first()
if not authenticate_user(user, password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
return user
@user_router.post(
"/users",
response_model=UserPublic,
status_code=status.HTTP_201_CREATED,
)
def create_user(user: UserCreate, session: SessionDep):
pwd_data = {"hashed_password": hash_password(user.password)}
db_user = User.model_validate(user, update=pwd_data)
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user