15 lines
983 B
Python
15 lines
983 B
Python
|
|
from datetime import timedelta
|
||
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
||
|
|
from app.auth import ACCESS_TOKEN_EXPIRE_MINUTES, Token, authenticate_user, create_access_token, get_current_active_user
|
||
|
|
router = APIRouter(prefix='/auth', tags=['auth'])
|
||
|
|
@router.post('/token', response_model=Token)
|
||
|
|
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
||
|
|
user = authenticate_user(form_data.username, form_data.password)
|
||
|
|
if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Incorrect username or password')
|
||
|
|
access_token = create_access_token({'sub': user.username, 'role': user.role}, timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||
|
|
return Token(access_token=access_token)
|
||
|
|
@router.get('/me')
|
||
|
|
async def me(current_user=Depends(get_current_active_user)):
|
||
|
|
return {'username': current_user.username, 'role': current_user.role, 'disabled': current_user.disabled}
|