kiwi-vpn/api/kiwi_vpn_api/routers/device.py
2022-03-29 16:35:41 +00:00

67 lines
1.8 KiB
Python

"""
/device endpoints.
"""
from fastapi import APIRouter, Depends, HTTPException, status
from ..db import Device, DeviceCreate, DeviceRead, User
from ._common import (Responses, get_device_by_id_if_editable,
get_user_by_name_if_editable)
router = APIRouter(prefix="/device", tags=["device"])
@router.post(
"",
responses={
status.HTTP_200_OK: Responses.OK,
status.HTTP_400_BAD_REQUEST: Responses.NOT_INSTALLED,
status.HTTP_401_UNAUTHORIZED: Responses.NEEDS_USER,
status.HTTP_403_FORBIDDEN: Responses.NEEDS_REQUESTED_USER,
status.HTTP_404_NOT_FOUND: Responses.ENTRY_DOESNT_EXIST,
status.HTTP_409_CONFLICT: Responses.ENTRY_EXISTS,
},
response_model=DeviceRead,
)
async def add_device(
device: DeviceCreate,
user: User = Depends(get_user_by_name_if_editable),
) -> Device:
"""
POST ./: Create a new device in the database.
"""
# create the new device
new_device = Device.create(
owner=user,
device=device,
)
# fail if creation was unsuccessful
if new_device is None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
# return the created device on success
return new_device
@router.delete(
"/{device_id}",
responses={
status.HTTP_200_OK: Responses.OK,
status.HTTP_400_BAD_REQUEST: Responses.NOT_INSTALLED,
status.HTTP_401_UNAUTHORIZED: Responses.NEEDS_USER,
status.HTTP_403_FORBIDDEN: Responses.NEEDS_ADMIN,
status.HTTP_404_NOT_FOUND: Responses.ENTRY_DOESNT_EXIST,
},
response_model=User,
)
async def remove_device(
device: Device = Depends(get_device_by_id_if_editable),
):
"""
DELETE ./{device_id}: Remove a device from the database.
"""
# delete device
device.delete()