Spaces:
Sleeping
Sleeping
# fastapi_crud/app/routers/user.py | |
from fastapi import APIRouter, Depends, HTTPException | |
from sqlalchemy.orm import Session | |
from fastapi.security import OAuth2PasswordRequestForm | |
from app import crud, schemas, database, auth | |
router = APIRouter() | |
def create_user(user: schemas.UserCreate, db: Session = Depends(database.get_db)): | |
db_user = crud.get_user_by_username(db, username=user.username) | |
if db_user: | |
raise HTTPException(status_code=400, detail="Username already registered") | |
return crud.create_user(db=db, user=user) | |
# status_code=status.HTTP_401_UNAUTHORIZED | |
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(database.get_db)): | |
user = auth.authenticate_user(db, form_data.username, form_data.password) | |
if not user: | |
raise HTTPException( | |
status_code=401, | |
detail="Incorrect username or password", | |
headers={"WWW-Authenticate": "Bearer"}, | |
) | |
access_token = auth.create_access_token(data={"sub": user.username}) | |
return {"access_token": access_token, "token_type": "bearer"} | |
async def read_users_me(current_user: schemas.User = Depends(auth.get_current_user)): | |
return current_user | |