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

65 lines
1.7 KiB
Python
Raw Normal View History

from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import jwt
from pydantic import BaseModel
2022-03-18 23:04:28 +00:00
from sqlalchemy.orm import Session
2022-03-18 23:04:28 +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}/token",
)
class Token(BaseModel):
access_token: str
token_type: str
2022-03-18 23:04:28 +00:00
def create_access_token(
data: dict,
expires_delta: timedelta | None = None,
config: Config = Depends(Config.get),
):
to_encode = data.copy()
if expires_delta is None:
expires_delta = timedelta(minutes=15)
to_encode.update({"exp": datetime.utcnow() + expires_delta})
2022-03-18 23:04:28 +00:00
return jwt.encode(
to_encode,
config.jwt.secret,
algorithm=config.jwt.hash_algorithm,
)
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(),
config: Config = Depends(Config.get),
db: Session = Depends(Connection.get),
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
2022-03-18 23:45:09 +00:00
user = schemas.User.get(db, form_data.username)
if user is None:
2022-03-18 23:04:28 +00:00
config.crypt_context.dummy_verify()
raise credentials_exception
if not user.verify(form_data.password):
raise credentials_exception
access_token = create_access_token(
data={"sub": user.name},
2022-03-18 23:04:28 +00:00
expires_delta=timedelta(minutes=config.jwt.expiry_minutes),
)
return {"access_token": access_token, "token_type": "bearer"}