-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
69 lines (56 loc) · 2.06 KB
/
main.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
import json
import os
from typing import List
from uuid import UUID
# Local Imports
import crud_operations
import models
import schemas as schema
from database import Base, SessionLocal, engine, get_db
# Third-party Imports
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from routes import (department_role_routes, department_routes, qrcode_routes,
user_routes)
from security import authenticate_user, create_access_token
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session
from validators import (format_and_validate_department_name,
format_and_validate_role, is_user_admin_of_department)
"""
Entry point of the application.
"""
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
print("Creating the tables")
try:
Base.metadata.create_all(bind=engine)
except OperationalError as e:
print("Unable to access postgresql database:", e)
"""
Routes
"""
@app.get("/", response_model=dict, tags=["Root route"])
def read_root():
return {"message": "Hello, world!"}
@app.post("/token", response_model=dict, tags=["Authentication token"])
def generate_token(
form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
):
user = authenticate_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=401, detail="Invalid username or password")
access_token = create_access_token(data={"sub": user.name})
return {"access_token": access_token, "token_type": "bearer"}
app.include_router(qrcode_routes.router, tags=["Upload Qrcodes files"])
app.include_router(user_routes.router, tags=["Users"])
app.include_router(department_routes.router, tags=["Departments"])
app.include_router(department_role_routes.router, tags=["Department roles"])