File size: 2,155 Bytes
dbc6c62
7832703
 
dbc6c62
 
0b77457
dbc6c62
7832703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc6c62
 
 
 
10f29f7
fb44d11
10f29f7
dbc6c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request, Form, File, UploadFile, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates

from .admin import admin_functions as admin

app = FastAPI()

# Add middleware
# Set all origins to wildcard for simplicity, but you should limit this in production
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")

# Setup Jinja2Templates to point to the templates directory
templates = Jinja2Templates(directory="app/admin/templates")

@app.get("/")
async def get_admin_login(request: Request):
    return templates.TemplateResponse("admin_login.html", {"request": request})

# Admin Login Handler
@app.post("/admin/login", response_class=HTMLResponse)
async def handle_admin_login(request: Request, username: str = Form(...), password: str = Form(...)):

    if admin.verify_admin_password(username, password):
        # Redirect to user registration page upon successful login
        return RedirectResponse(url="/admin/register_user", status_code=303)
    else:
        # Reload login page with error message
        return templates.TemplateResponse("admin_login.html", {"request": request, "error": "Invalid password"})

# User Registration Handler
@app.post("/admin/register_user", response_class=HTMLResponse)
async def handle_user_registration(request: Request, email: str = Form(...), name: str = Form(...), role: str = Form(...), file: UploadFile = File(...)):
    user_id = await admin.register_user(email, name, role, file)
    if user_id:
        # Redirect or display a success message
        return templates.TemplateResponse("registration_success.html", {"request": request})
    else:
        # Reload registration page with error message
        return templates.TemplateResponse("user_registration.html", {"request": request, "error": "Registration failed"})