-
Notifications
You must be signed in to change notification settings - Fork 0
/
admins.py
84 lines (67 loc) · 2.35 KB
/
admins.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import logging
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.Admin])
def read_admins(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
_: models.Admin = Depends(deps.get_current_active_admin_with_permission("admin")),
) -> Any:
"""
Retrieve admins
"""
return crud.admin.get_multi(db, skip=skip, limit=limit)
@router.get("/me", response_model=schemas.Admin)
def get_admin_me(
current_admin: models.Admin = Depends(deps.get_current_admin),
) -> Any:
"""
Get current admin
"""
return current_admin
@router.get("/{admin_id}", response_model=schemas.Admin)
def read_admin_by_id(
admin_id: int, current_admin: models.Admin = Depends(deps.get_current_admin), db: Session = Depends(deps.get_db)
) -> Any:
"""
Get a specific admin by ID.
"""
# Fetch Admin with the corresponding ID from DB
admin = crud.admin.get(db, id=admin_id)
# Return the fetched object without checking perms if current_admin is trying to fetch itself
if admin == current_admin:
return admin
# check perms and return if admin exists, else 404
if schemas.AdminPermissions(current_admin.permissions).is_allowed("admin"):
if admin:
return admin
raise HTTPException(
status_code=404,
detail="The admin with this ID does not exist in the system",
)
raise HTTPException(status_code=403, detail="The user doesn't have enough privileges")
@router.put("/", response_model=schemas.Admin)
def update_admin(
*,
db: Session = Depends(deps.get_db),
admin_in: schemas.AdminUpdate,
current_admin: models.Admin = Depends(deps.get_current_active_admin_with_permission("admin")),
) -> Any:
"""
Update admin.
"""
if admin := crud.admin.get(db, admin_in.user_id):
logging.info(
f"Admin {current_admin.user_id} ({current_admin.user.email}) is updating Admin {admin.user_id}"
f"({admin.user.email}) to {admin_in.__dict__}"
)
return crud.admin.update(db, db_obj=admin, obj_in=admin_in)
raise HTTPException(
status_code=404,
detail="This admin does not exist!",
)