aboutsummaryrefslogtreecommitdiffstats
path: root/backend/routes/forms/submit.py
blob: 599900f83cf04969239e7235bcd4fd852a74d82c (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
57
58
59
60
61
62
63
64
65
66
67
68
"""
Submit a form.
"""

import binascii
import hashlib

import jwt

from starlette.responses import JSONResponse

from backend.constants import SECRET_KEY
from backend.route import Route


class SubmitForm(Route):
    """
    Submit a form with the provided form ID.
    """

    name = "submit_form"
    path = "/submit/{form_id:str}"

    async def post(self, request):
        data = await request.json()

        if form := request.state.db.forms.find_one(
            {"_id": request.path_params["form_id"], "features": "OPEN"}
        ):
            response_obj = {}

            if "DISABLE_ANTISPAM" not in form["features"]:
                ip_hash_ctx = hashlib.md5()
                ip_hash_ctx.update(request.client.host.encode())
                ip_hash = binascii.hexlify(ip_hash_ctx.digest())

                response_obj["antispam"] = {
                    "ip": ip_hash.decode()
                }

            if "REQUIRES_LOGIN" in form["features"]:
                if token := data.get("token"):
                    data = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
                    response_obj["user"] = {
                        "user": f"{data['username']}#{data['discriminator']}",
                        "id": data["id"]
                    }

                    if "COLLECT_EMAIL" in form["features"]:
                        if data.get("email"):
                            response_obj["user"]["email"] = data["email"]
                        else:
                            return JSONResponse({
                                "error": "User data did not include email information"
                            })
                else:
                    return JSONResponse({
                        "error": "Missing Discord user data"
                    })

            return JSONResponse({
                "form": form,
                "response": response_obj
            })
        else:
            return JSONResponse({
                "error": "Open form not found"
            })