aboutsummaryrefslogtreecommitdiffstats
path: root/backend/__init__.py
blob: b5360ef6f2b3311ccd7771a8b3b91f1ea968001e (plain) (blame)
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
import logging

import sentry_sdk
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.cors import CORSMiddleware

from backend import constants
from backend import logs  # This has to be imported before logging statements are used
from backend.authentication import JWTAuthenticationBackend
from backend.middleware import DatabaseMiddleware, ProtectedDocsMiddleware
from backend.route_manager import create_route_map
from backend.validation import api

logger = logging.getLogger(__name__)

# Setup CORS Origins
ORIGINS = [
    r"(https://[^.?#]*--pydis-forms\.netlify\.app)",  # Netlify Previews
    r"(https?://[^.?#]*.forms-frontend.pages.dev)",  # Cloudflare Previews
]

if not constants.PRODUCTION:
    # Allow all hosts on non-production deployments
    logger.info("Allowing all CORS origins.")
    ORIGINS.append(r"(.*)")

ALLOW_ORIGIN_REGEX = "|".join(ORIGINS)

sentry_sdk.init(
    dsn=constants.FORMS_BACKEND_DSN,
    send_default_pii=True,
    release=f"forms-backend@{constants.GIT_SHA}"
)

middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=["https://forms.pythondiscord.com"],
        allow_origin_regex=ALLOW_ORIGIN_REGEX,
        allow_headers=[
            "Content-Type"
        ],
        allow_methods=["*"],
        allow_credentials=True
    ),
    Middleware(DatabaseMiddleware),
    Middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend()),
    Middleware(SentryAsgiMiddleware),
    Middleware(ProtectedDocsMiddleware),
]

app = Starlette(routes=create_route_map(), middleware=middleware)
api.register(app)