summaryrefslogtreecommitdiff
path: root/src/main.py
blob: d6f420f028f0018984a8dc85e476c4941898dbbd (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
import sys

import uvicorn
from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from pydantic import BaseModel

import routers

app = FastAPI()

app.include_router(routers.router, prefix='/sc/v0')

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8001"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["X-Total-Count"],
)


@app.middleware("http")
async def mock_x_total_count_header(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Total-Count"] = "100"
    return response

<< << << < HEAD
== == == =
for i in range(10):
    try:
        db = DictDB()
    except Exception:
        print(
            f'Database not responding, will try again soon. Attempt {i + 1} of 10.')
    else:
        break
    time.sleep(1)
else:
    print('Database did not respond after 10 attempts, quitting.')
    sys.exit(-1)

>>>>>> > main


def get_pubkey():
    try:
        if 'JWT_PUBKEY_PATH' in os.environ:
            keypath = os.environ['JWT_PUBKEY_PATH']
        else:
            keypath = '/opt/certs/public.pem'

        with open(keypath, "r") as fd:
            pubkey = fd.read()
    except FileNotFoundError:
        print(f"Could not find JWT certificate in {keypath}")
        sys.exit(-1)

    return pubkey


class JWTConfig(BaseModel):
    authjwt_algorithm: str = "ES256"
    authjwt_public_key: str = get_pubkey()


@AuthJWT.load_config
def jwt_config():
    return JWTConfig()


@app.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
    return JSONResponse(content={"status": "error", "message":
                                 exc.message}, status_code=400)


@app.exception_handler(RuntimeError)
def app_exception_handler(request: Request, exc: RuntimeError):
    return JSONResponse(content={"status": "error", "message":
                                 str(exc.with_traceback(None))},
                        status_code=400)


def main(standalone=False):
    if not standalone:
        return app

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="debug")


if __name__ == '__main__':
    main(standalone=True)
else:
    app = main()