kiwi-vpn/api/kiwi_vpn_api/routers/user.py

68 lines
1.8 KiB
Python
Raw Normal View History

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
2022-03-18 23:04:28 +00:00
from sqlalchemy.orm import Session
2022-03-19 02:22:49 +00:00
from ..config import Config
2022-03-18 23:45:09 +00:00
from ..db import Connection, schemas
2022-03-15 16:25:07 +00:00
2022-03-18 23:04:28 +00:00
router = APIRouter(prefix="/user")
2022-03-18 23:45:09 +00:00
SCHEME = OAuth2PasswordBearer(
tokenUrl=f".{router.prefix}/auth",
2022-03-18 23:45:09 +00:00
)
class Token(BaseModel):
access_token: str
token_type: str
2022-03-18 23:04:28 +00:00
@router.post("/auth", response_model=Token)
2022-03-18 23:45:09 +00:00
async def login(
2022-03-18 23:04:28 +00:00
form_data: OAuth2PasswordRequestForm = Depends(),
2022-03-19 02:38:32 +00:00
config: Config = Depends(Config.load),
2022-03-18 23:04:28 +00:00
db: Session = Depends(Connection.get),
):
2022-03-19 02:38:32 +00:00
user = schemas.User.login(
db=db,
name=form_data.username,
password=form_data.password,
2022-03-19 02:28:18 +00:00
crypt_context=await config.crypto.crypt_context,
)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
2022-03-19 02:38:32 +00:00
access_token = await config.jwt.create_token(user.name)
return {"access_token": access_token, "token_type": "bearer"}
async def dep_get_current_user(
token: str = Depends(SCHEME),
db: Session = Depends(Connection.get),
2022-03-19 02:38:32 +00:00
config: Config = Depends(Config.load),
):
2022-03-19 02:38:32 +00:00
username = await config.jwt.decode_token(token)
user = schemas.User.from_db(db, username)
return user
@router.get("/current", response_model=schemas.User)
async def get_current_user(
current_user: schemas.User = Depends(dep_get_current_user),
):
2022-03-19 03:37:24 +00:00
if current_user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return current_user