1 |
cbd239c6
|
Matej Zeman
|
from typing import List
|
2 |
|
|
from fastapi import Depends, FastAPI, HTTPException, APIRouter, Form
|
3 |
|
|
from sqlalchemy.orm import Session
|
4 |
|
|
from sql_app import crud, models, schemas
|
5 |
|
|
from ..database import SessionLocal, engine
|
6 |
|
|
from fastapi import FastAPI, Request
|
7 |
|
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
8 |
|
|
from fastapi_jwt_auth import AuthJWT
|
9 |
|
|
from fastapi.staticfiles import StaticFiles
|
10 |
|
|
from fastapi.templating import Jinja2Templates
|
11 |
|
|
|
12 |
|
|
models.Base.metadata.create_all(bind=engine)
|
13 |
|
|
|
14 |
|
|
# Path to html templates used in this file
|
15 |
|
|
templates = Jinja2Templates(directory="templates/users")
|
16 |
|
|
|
17 |
|
|
# prefix used for all endpoints in this file
|
18 |
|
|
users = APIRouter(prefix="")
|
19 |
|
|
|
20 |
|
|
|
21 |
|
|
# Dependency
|
22 |
|
|
def get_db():
|
23 |
|
|
db = SessionLocal()
|
24 |
|
|
try:
|
25 |
|
|
yield db
|
26 |
|
|
finally:
|
27 |
|
|
db.close()
|
28 |
|
|
|
29 |
|
|
|
30 |
|
|
@users.get("/users-web", response_class=HTMLResponse)
|
31 |
|
|
async def read_usrs(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db),
|
32 |
|
|
Authorize: AuthJWT = Depends()):
|
33 |
|
|
"""
|
34 |
|
|
Returns template with all users currently saved in database
|
35 |
|
|
"""
|
36 |
|
|
Authorize.jwt_optional()
|
37 |
|
|
current_user = Authorize.get_jwt_subject()
|
38 |
|
|
users = crud.get_users(db, skip, limit)
|
39 |
|
|
if current_user == "admin":
|
40 |
93d0ec10
|
Matej Zeman
|
return templates.TemplateResponse("users.html", {"request": request, "users": users, "user": current_user})
|
41 |
cbd239c6
|
Matej Zeman
|
else:
|
42 |
|
|
return RedirectResponse(url=f"/logs-web", status_code=303)
|
43 |
|
|
|
44 |
|
|
|
45 |
|
|
@users.get("/user-role/{usr_id}", response_class=HTMLResponse)
|
46 |
|
|
async def connect_pc_team(usr_id: int, db: Session = Depends(get_db), Authorize: AuthJWT = Depends()):
|
47 |
|
|
"""
|
48 |
|
|
Changes role of user to either guest or admin depending on old role.
|
49 |
|
|
"""
|
50 |
|
|
Authorize.jwt_optional()
|
51 |
|
|
current_user = Authorize.get_jwt_subject()
|
52 |
|
|
if current_user != "admin":
|
53 |
|
|
return RedirectResponse(url=f"/logs-web", status_code=303)
|
54 |
|
|
user = crud.find_user_byid(db, usr_id)
|
55 |
|
|
if user.role == "admin":
|
56 |
|
|
crud.change_role(db, usr_id, "guest")
|
57 |
|
|
else:
|
58 |
|
|
crud.change_role(db, usr_id, "admin")
|
59 |
|
|
return RedirectResponse(url=f"/users-web", status_code=303)
|