generateur_v3/backend/api_old/apis/auth/route_auth.py
2022-09-16 21:50:55 +02:00

140 lines
4.9 KiB
Python

from typing import List, Optional
from fastapi_jwt_auth import AuthJWT
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, FastAPI, Form, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from api_old.schema.user import UserForm
from config import Room_schema, User_schema, UserIn_Form, UserIn_schema
from database.auth.crud import create_user_db, disable_user_db, delete_user_db, get_user_db, update_password_db, update_user_db
from services.auth import PasswordSet, check_unique_user, create_access_token, authenticate_user, fresh_jwt_required, get_current_clientId, get_current_user, jwt_refresh_required, jwt_required, User, UserRegister, validate_passwords, validate_register_user
from services.password import get_password_hash, validate_password
from database.auth.models import UserModel
from database.decorators import as_form
class Token(BaseModel):
access_token: str
token_type: str
refresh_token: str
router = APIRouter()
@router.post("/login", response_model=Token)
async def login_for_access_token(user: User = Depends(authenticate_user), Authorize: AuthJWT = Depends()):
access_token = Authorize.create_access_token(
subject=user.username, fresh=True)
refresh_token = Authorize.create_refresh_token(subject=user.clientId)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
class Room(BaseModel):
name: str
id_code: str
owner: bool
class User(BaseModel):
username: str = None
firstname: str = None
name: str = None
email: str = None
rooms: list[Room] = []
class Config:
orm_mode = True
@router.get("/user", response_model=User)
async def read_users_me(Authorize: AuthJWT = Depends(get_current_user)):
Authorize.jwt_required()
clientId = Authorize.get_jwt_subject()
user = await get_user_db(clientId)
if user is not None and user.disabled == False:
print(user.room_owners)
sc = await User_schema.from_tortoise_orm(user)
sc = sc.dict()
# sc['rooms'] = await Room_schema.from_queryset(await user.rooms.all())
f = await Room_schema.from_queryset(user.rooms.all())
ro = await user.room_owners.all().values('room_id')
rr = [r['room_id'] for r in ro]
ff = [r.id for r in f]
rooms = [{**r.dict(), "owner": r.id in ff} for r in f]
print(rooms)
sc = await User_schema.from_tortoise_orm(user)
sc = sc.dict()
sc['rooms'] = rooms
return sc
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail='User disabled')
@router.delete('/user')
async def delete_user(user: UserModel = Depends(authenticate_user)):
await delete_user_db(user.username)
return 'success'
@router.put('/user')
async def update_user(user: UserForm = Depends(UserForm.as_form), username: str = Depends(get_current_clientId), Authorize: AuthJWT = Depends()):
user_obj = await update_user_db(username, **user.dict(exclude_unset=True))
access_token = Authorize.create_access_token(
subject=user.clientId)
refresh_token = Authorize.create_refresh_token(subject=user.clientId)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post('/register', response_model=Token)
async def register(user: UserRegister = Depends(UserRegister.as_form), Authorize: AuthJWT = Depends()):
username = await check_unique_user(user.username)
user = await create_user_db(user.username, get_password_hash(user.password))
access_token = Authorize.create_access_token(
subject=user.username)
refresh_token = Authorize.create_refresh_token(subject=user.username)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post('/user/disable')
async def disable_user(user: UserModel = Depends(authenticate_user)):
await disable_user_db(user.username)
return 'success'
@router.put('/user/password')
async def update_password(passwords: PasswordSet = Depends(validate_passwords),Authorize: AuthJWT=Depends(fresh_jwt_required)):
username = Authorize.get_jwt_subject()
user = await update_password_db(username, passwords.password)
return await User_schema.from_tortoise_orm(user)
@router.get('/users')
async def get_users():
return await User_schema.from_queryset(UserModel.all())
@router.post('/refresh')
async def refresh(Authorize: AuthJWT = Depends(jwt_refresh_required)):
current_user = Authorize.get_jwt_subject()
new_access_token = Authorize.create_access_token(subject=current_user)
return {"access_token": new_access_token}
@router.post('/check-access')
async def check_token(Authorize: AuthJWT = Depends(jwt_required)):
return ""