From 7c01270f3e95c7eab12219714f7a27caaf33cacc Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 09:00:46 +0300 Subject: Adds Production Constant Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/constants.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'backend') diff --git a/backend/constants.py b/backend/constants.py index fedab64..af25d84 100644 --- a/backend/constants.py +++ b/backend/constants.py @@ -10,6 +10,8 @@ FRONTEND_URL = os.getenv("FRONTEND_URL", "https://forms.pythondiscord.com") DATABASE_URL = os.getenv("DATABASE_URL") MONGO_DATABASE = os.getenv("MONGO_DATABASE", "pydis_forms") +PRODUCTION = os.getenv("PRODUCTION", "True").lower() != "false" + OAUTH2_CLIENT_ID = os.getenv("OAUTH2_CLIENT_ID") OAUTH2_CLIENT_SECRET = os.getenv("OAUTH2_CLIENT_SECRET") OAUTH2_REDIRECT_URI = os.getenv( -- cgit v1.2.3 From 7a16a6b129f754a5486c441f2602a8d593edb85f Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 09:01:38 +0300 Subject: Adds Token Refresh Route Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/authentication/user.py | 17 +++++++++ backend/discord.py | 11 ++++-- backend/routes/auth/authorize.py | 81 +++++++++++++++++++++++++++++++++------- 3 files changed, 93 insertions(+), 16 deletions(-) (limited to 'backend') diff --git a/backend/authentication/user.py b/backend/authentication/user.py index f40c68c..a1d78e5 100644 --- a/backend/authentication/user.py +++ b/backend/authentication/user.py @@ -1,7 +1,11 @@ import typing as t +import jwt from starlette.authentication import BaseUser +from backend.constants import SECRET_KEY +from backend.discord import fetch_user_details + class User(BaseUser): """Starlette BaseUser implementation for JWT authentication.""" @@ -23,3 +27,16 @@ class User(BaseUser): @property def discord_mention(self) -> str: return f"<@{self.payload['id']}>" + + @property + def decoded_token(self) -> dict[str, any]: + return jwt.decode(self.token, SECRET_KEY, algorithms=["HS256"]) + + async def refresh_data(self) -> None: + """Fetches user data from discord, and updates the instance.""" + self.payload = await fetch_user_details(self.decoded_token.get("token")) + + updated_info = self.decoded_token + updated_info["user_details"] = self.payload + + self.token = jwt.encode(updated_info, SECRET_KEY, algorithm="HS256") diff --git a/backend/discord.py b/backend/discord.py index d6310b7..9cdd2c4 100644 --- a/backend/discord.py +++ b/backend/discord.py @@ -8,16 +8,21 @@ from backend.constants import ( API_BASE_URL = "https://discord.com/api/v8" -async def fetch_bearer_token(access_code: str) -> dict: +async def fetch_bearer_token(code: str, *, refresh: bool) -> dict: async with httpx.AsyncClient() as client: data = { "client_id": OAUTH2_CLIENT_ID, "client_secret": OAUTH2_CLIENT_SECRET, - "grant_type": "authorization_code", - "code": access_code, "redirect_uri": OAUTH2_REDIRECT_URI } + if refresh: + data["grant_type"] = "refresh_token" + data["refresh_token"] = code + else: + data["grant_type"] = "authorization_code" + data["code"] = code + r = await client.post(f"{API_BASE_URL}/oauth2/token", headers={ "Content-Type": "application/x-www-form-urlencoded" }, data=data) diff --git a/backend/routes/auth/authorize.py b/backend/routes/auth/authorize.py index 975936a..2244152 100644 --- a/backend/routes/auth/authorize.py +++ b/backend/routes/auth/authorize.py @@ -2,17 +2,23 @@ Use a token received from the Discord OAuth2 system to fetch user information. """ +import datetime +from typing import Union + import httpx import jwt from pydantic.fields import Field from pydantic.main import BaseModel from spectree.response import Response +from starlette.authentication import requires from starlette.requests import Request from starlette.responses import JSONResponse +from backend import constants +from backend.authentication.user import User from backend.constants import SECRET_KEY -from backend.route import Route from backend.discord import fetch_bearer_token, fetch_user_details +from backend.route import Route from backend.validation import ErrorMessage, api @@ -21,7 +27,42 @@ class AuthorizeRequest(BaseModel): class AuthorizeResponse(BaseModel): - token: str = Field(description="A JWT token containing the user information") + username: str = Field("Discord display name.") + + +AUTH_FAILURE = JSONResponse({"error": "auth_failure"}, status_code=400) + + +async def process_token(bearer_token: dict) -> Union[AuthorizeResponse, AUTH_FAILURE]: + """Post a bearer token to Discord, and return a JWT and username.""" + interaction_start = datetime.datetime.now() + + try: + user_details = await fetch_user_details(bearer_token["access_token"]) + except httpx.HTTPStatusError: + AUTH_FAILURE.delete_cookie("BackendToken") + return AUTH_FAILURE + + max_age = datetime.timedelta(seconds=int(bearer_token["expires_in"])) + token_expiry = interaction_start + max_age + + data = { + "token": bearer_token["access_token"], + "refresh": bearer_token["refresh_token"], + "user_details": user_details, + "expiry": token_expiry.isoformat() + } + + token = jwt.encode(data, SECRET_KEY, algorithm="HS256") + user = User(token, user_details) + + response = JSONResponse({"username": user.display_name}) + response.set_cookie( + "BackendToken", f"JWT {token}", + secure=constants.PRODUCTION, httponly=True, samesite="strict", + max_age=bearer_token["expires_in"] + ) + return response class AuthorizeRoute(Route): @@ -40,19 +81,33 @@ class AuthorizeRoute(Route): async def post(self, request: Request) -> JSONResponse: """Generate an authorization token.""" data = await request.json() - try: - bearer_token = await fetch_bearer_token(data["token"]) - user_details = await fetch_user_details(bearer_token["access_token"]) + bearer_token = await fetch_bearer_token(data["token"], refresh=False) except httpx.HTTPStatusError: - return JSONResponse({ - "error": "auth_failure" - }, status_code=400) + return AUTH_FAILURE + + return await process_token(bearer_token) - user_details["admin"] = await request.state.db.admins.find_one( - {"_id": user_details["id"]} - ) is not None - token = jwt.encode(user_details, SECRET_KEY, algorithm="HS256") +class TokenRefreshRoute(Route): + """ + Use the refresh code from a JWT to get a new token and generate a new JWT token. + """ + + name = "refresh" + path = "/refresh" + + @requires(["authenticated"]) + @api.validate( + resp=Response(HTTP_200=AuthorizeResponse, HTTP_400=ErrorMessage), + tags=["auth"] + ) + async def post(self, request: Request) -> JSONResponse: + """Refresh an authorization token.""" + try: + token = request.user.decoded_token.get("refresh") + bearer_token = await fetch_bearer_token(token, refresh=True) + except httpx.HTTPStatusError: + return AUTH_FAILURE - return JSONResponse({"token": token}) + return await process_token(bearer_token) -- cgit v1.2.3 From 10a2afbf27b052ba3561709bcda1ae2924b90cd2 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 09:10:38 +0300 Subject: Refreshes User Data On Form Submit Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/authentication/backend.py | 42 +++++++++++++++++++++++++---------- backend/routes/forms/submit.py | 46 ++++++++++++++++++++++++++++++++------- 2 files changed, 69 insertions(+), 19 deletions(-) (limited to 'backend') diff --git a/backend/authentication/backend.py b/backend/authentication/backend.py index f1d2ece..abe7313 100644 --- a/backend/authentication/backend.py +++ b/backend/authentication/backend.py @@ -1,6 +1,6 @@ -import jwt import typing as t +import jwt from starlette import authentication from starlette.requests import Request @@ -13,18 +13,18 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): """Custom Starlette authentication backend for JWT.""" @staticmethod - def get_token_from_header(header: str) -> str: - """Parse JWT token from header value.""" + def get_token_from_cookie(cookie: str) -> str: + """Parse JWT token from cookie.""" try: - prefix, token = header.split() + prefix, token = cookie.split() except ValueError: raise authentication.AuthenticationError( - "Unable to split prefix and token from Authorization header." + "Unable to split prefix and token from authorization cookie." ) if prefix.upper() != "JWT": raise authentication.AuthenticationError( - f"Invalid Authorization header prefix '{prefix}'." + f"Invalid authorization cookie prefix '{prefix}'." ) return token @@ -33,11 +33,11 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): self, request: Request ) -> t.Optional[tuple[authentication.AuthCredentials, authentication.BaseUser]]: """Handles JWT authentication process.""" - if "Authorization" not in request.headers: + cookie = request.cookies.get("BackendToken") + if not cookie: return None - auth = request.headers["Authorization"] - token = self.get_token_from_header(auth) + token = self.get_token_from_cookie(cookie) try: payload = jwt.decode(token, constants.SECRET_KEY, algorithms=["HS256"]) @@ -46,7 +46,27 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): scopes = ["authenticated"] - if payload.get("admin") is True: + if not payload.get("token"): + raise authentication.AuthenticationError("Token is missing from JWT.") + if not payload.get("refresh"): + raise authentication.AuthenticationError( + "Refresh token is missing from JWT." + ) + + try: + user_details = payload.get("user_details") + if not user_details or not user_details.get("id"): + raise authentication.AuthenticationError("Improper user details.") + except Exception: + raise authentication.AuthenticationError("Could not parse user details.") + + admin = await request.state.db.admins.find_one( + {"_id": user_details["id"]} + ) is not None + + if admin: scopes.append("admin") - return authentication.AuthCredentials(scopes), User(token, payload) + user = User(token, user_details) + + return authentication.AuthCredentials(scopes), user diff --git a/backend/routes/forms/submit.py b/backend/routes/forms/submit.py index d8e6d35..ec9b24f 100644 --- a/backend/routes/forms/submit.py +++ b/backend/routes/forms/submit.py @@ -3,6 +3,7 @@ Submit a form. """ import binascii +import datetime import hashlib import uuid from typing import Any, Optional @@ -15,7 +16,8 @@ from starlette.background import BackgroundTask from starlette.requests import Request from starlette.responses import JSONResponse -from backend.constants import FRONTEND_URL, FormFeatures, HCAPTCHA_API_SECRET +from backend import constants +from backend.authentication.user import User from backend.models import Form, FormResponse from backend.route import Route from backend.validation import AuthorizationHeaders, ErrorMessage, api @@ -56,8 +58,36 @@ class SubmitForm(Route): ) async def post(self, request: Request) -> JSONResponse: """Submit a response to the form.""" - data = await request.json() + response = await self.submit(request) + + # Silently try to update user data + try: + if hasattr(request.user, User.refresh_data.__name__): + old = request.user.token + await request.user.refresh_data() + + if old != request.user.token: + try: + expiry = datetime.datetime.fromisoformat( + request.user.decoded_token.get("expiry") + ) + except ValueError: + expiry = None + + response.set_cookie( + "BackendToken", f"JWT {request.user.token}", + secure=constants.PRODUCTION, httponly=True, samesite="strict", + max_age=(expiry - datetime.datetime.now()).seconds + ) + except httpx.HTTPStatusError: + pass + + return response + + async def submit(self, request: Request) -> JSONResponse: + """Helper method for handling submission logic.""" + data = await request.json() data["timestamp"] = None if form := await request.state.db.forms.find_one( @@ -68,7 +98,7 @@ class SubmitForm(Route): response["id"] = str(uuid.uuid4()) response["form_id"] = form.id - if FormFeatures.DISABLE_ANTISPAM.value not in form.features: + if constants.FormFeatures.DISABLE_ANTISPAM.value 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()) @@ -78,7 +108,7 @@ class SubmitForm(Route): async with httpx.AsyncClient() as client: query_params = { - "secret": HCAPTCHA_API_SECRET, + "secret": constants.HCAPTCHA_API_SECRET, "response": data.get("captcha") } r = await client.post( @@ -95,11 +125,11 @@ class SubmitForm(Route): "captcha_pass": captcha_data["success"] } - if FormFeatures.REQUIRES_LOGIN.value in form.features: + if constants.FormFeatures.REQUIRES_LOGIN.value in form.features: if request.user.is_authenticated: response["user"] = request.user.payload - if FormFeatures.COLLECT_EMAIL.value in form.features and "email" not in response["user"]: # noqa + if constants.FormFeatures.COLLECT_EMAIL.value in form.features and "email" not in response["user"]: # noqa return JSONResponse({ "error": "email_required" }, status_code=400) @@ -132,7 +162,7 @@ class SubmitForm(Route): ) send_webhook = None - if FormFeatures.WEBHOOK_ENABLED.value in form.features: + if constants.FormFeatures.WEBHOOK_ENABLED.value in form.features: send_webhook = BackgroundTask( self.send_submission_webhook, form=form, @@ -172,7 +202,7 @@ class SubmitForm(Route): embed = { "title": "New Form Response", "description": f"{mention} submitted a response to `{form.name}`.", - "url": f"{FRONTEND_URL}/path_to_view_form/{response.id}", # noqa # TODO: Enter Form View URL + "url": f"{constants.FRONTEND_URL}/path_to_view_form/{response.id}", # noqa # TODO: Enter Form View URL "timestamp": response.timestamp, "color": 7506394, } -- cgit v1.2.3 From 839525ef99ca353a107812cefb006e22a5f3f7f4 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 09:49:09 +0300 Subject: Remove AuthorizationHeaders Class Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/routes/forms/submit.py | 3 +-- backend/validation.py | 11 ----------- 2 files changed, 1 insertion(+), 13 deletions(-) (limited to 'backend') diff --git a/backend/routes/forms/submit.py b/backend/routes/forms/submit.py index ec9b24f..55a4875 100644 --- a/backend/routes/forms/submit.py +++ b/backend/routes/forms/submit.py @@ -20,7 +20,7 @@ from backend import constants from backend.authentication.user import User from backend.models import Form, FormResponse from backend.route import Route -from backend.validation import AuthorizationHeaders, ErrorMessage, api +from backend.validation import ErrorMessage, api HCAPTCHA_VERIFY_URL = "https://hcaptcha.com/siteverify" HCAPTCHA_HEADERS = { @@ -53,7 +53,6 @@ class SubmitForm(Route): HTTP_404=ErrorMessage, HTTP_400=ErrorMessage ), - headers=AuthorizationHeaders, tags=["forms", "responses"] ) async def post(self, request: Request) -> JSONResponse: diff --git a/backend/validation.py b/backend/validation.py index e696683..8771924 100644 --- a/backend/validation.py +++ b/backend/validation.py @@ -1,6 +1,5 @@ """Utilities for providing API payload validation.""" -from typing import Optional from pydantic.fields import Field from pydantic.main import BaseModel from spectree import SpecTree @@ -18,13 +17,3 @@ class ErrorMessage(BaseModel): class OkayResponse(BaseModel): status: str = "ok" - - -class AuthorizationHeaders(BaseModel): - authorization: Optional[str] = Field( - title="Authorization", - description=( - "The Authorization JWT token received from the " - "authorize route in the format `JWT {token}`" - ) - ) -- cgit v1.2.3 From 423a1bdf2e89b73ac2aca10e1a20891d5fc01715 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 10:12:46 +0300 Subject: Adds CORS Rules Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/__init__.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'backend') diff --git a/backend/__init__.py b/backend/__init__.py index a3704a0..d56edfb 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -7,10 +7,20 @@ from starlette.middleware.cors import CORSMiddleware from backend import constants from backend.authentication import JWTAuthenticationBackend -from backend.route_manager import create_route_map from backend.middleware import DatabaseMiddleware, ProtectedDocsMiddleware +from backend.route_manager import create_route_map from backend.validation import api +ORIGINS = [ + r"(https://[^.?#]*--pydis-forms\.netlify\.app)", # Netlify Previews + r"(https?://[^.?#]*.forms-frontend.pages.dev)", # Cloudflare Previews +] +if not constants.PRODUCTION: + # Add localhost to allowed origins on non-production deployments + ORIGINS.append(r"(https?://localhost:\d{0,4})") + +ALLOW_ORIGIN_REGEX = "|".join(ORIGINS) + sentry_sdk.init( dsn=constants.FORMS_BACKEND_DSN, send_default_pii=True, @@ -20,13 +30,13 @@ sentry_sdk.init( middleware = [ Middleware( CORSMiddleware, - # TODO: Convert this into a RegEx that works for prod, netlify & previews - allow_origins=["*"], + allow_origins=["https://forms.pythondiscord.com"], + allow_origin_regex=ALLOW_ORIGIN_REGEX, allow_headers=[ - "Authorization", "Content-Type" ], - allow_methods=["*"] + allow_methods=["*"], + allow_credentials=True ), Middleware(DatabaseMiddleware), Middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend()), -- cgit v1.2.3 From f6b09f5366a0921d12707c444a8bd86e05b7df19 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Fri, 19 Feb 2021 10:13:17 +0300 Subject: Adds Expiry To Authorization Routes Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/routes/auth/authorize.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'backend') diff --git a/backend/routes/auth/authorize.py b/backend/routes/auth/authorize.py index 2244152..c6cd86c 100644 --- a/backend/routes/auth/authorize.py +++ b/backend/routes/auth/authorize.py @@ -28,6 +28,7 @@ class AuthorizeRequest(BaseModel): class AuthorizeResponse(BaseModel): username: str = Field("Discord display name.") + expiry: str = Field("ISO formatted timestamp of expiry.") AUTH_FAILURE = JSONResponse({"error": "auth_failure"}, status_code=400) @@ -56,7 +57,11 @@ async def process_token(bearer_token: dict) -> Union[AuthorizeResponse, AUTH_FAI token = jwt.encode(data, SECRET_KEY, algorithm="HS256") user = User(token, user_details) - response = JSONResponse({"username": user.display_name}) + response = JSONResponse({ + "username": user.display_name, + "expiry": token_expiry.isoformat() + }) + response.set_cookie( "BackendToken", f"JWT {token}", secure=constants.PRODUCTION, httponly=True, samesite="strict", -- cgit v1.2.3 From 3c4f7e71cb1ecdfd8d255b02cf44adcd90f32f01 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Sat, 20 Feb 2021 03:45:16 +0300 Subject: Centralizes Admin Authentication Sets admin authentication on authenticator to allow the addition and removal of admins without creating a new token. Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/authentication/backend.py | 9 ++------- backend/authentication/user.py | 9 +++++++++ backend/routes/forms/form.py | 2 +- backend/routes/forms/submit.py | 1 + 4 files changed, 13 insertions(+), 8 deletions(-) (limited to 'backend') diff --git a/backend/authentication/backend.py b/backend/authentication/backend.py index abe7313..bdff796 100644 --- a/backend/authentication/backend.py +++ b/backend/authentication/backend.py @@ -60,13 +60,8 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): except Exception: raise authentication.AuthenticationError("Could not parse user details.") - admin = await request.state.db.admins.find_one( - {"_id": user_details["id"]} - ) is not None - - if admin: - scopes.append("admin") - user = User(token, user_details) + if user.fetch_admin_status(request): + scopes.append("admin") return authentication.AuthCredentials(scopes), user diff --git a/backend/authentication/user.py b/backend/authentication/user.py index a1d78e5..52baa61 100644 --- a/backend/authentication/user.py +++ b/backend/authentication/user.py @@ -2,6 +2,7 @@ import typing as t import jwt from starlette.authentication import BaseUser +from starlette.requests import Request from backend.constants import SECRET_KEY from backend.discord import fetch_user_details @@ -13,6 +14,7 @@ class User(BaseUser): def __init__(self, token: str, payload: dict[str, t.Any]) -> None: self.token = token self.payload = payload + self.admin = False @property def is_authenticated(self) -> bool: @@ -32,6 +34,13 @@ class User(BaseUser): def decoded_token(self) -> dict[str, any]: return jwt.decode(self.token, SECRET_KEY, algorithms=["HS256"]) + def fetch_admin_status(self, request: Request) -> bool: + self.admin = request.state.db.admins.find_one( + {"_id": self.payload["id"]} + ) is not None + + return self.admin + async def refresh_data(self) -> None: """Fetches user data from discord, and updates the instance.""" self.payload = await fetch_user_details(self.decoded_token.get("token")) diff --git a/backend/routes/forms/form.py b/backend/routes/forms/form.py index b6b722e..e3360b1 100644 --- a/backend/routes/forms/form.py +++ b/backend/routes/forms/form.py @@ -26,7 +26,7 @@ class SingleForm(Route): @api.validate(resp=Response(HTTP_200=Form, HTTP_404=ErrorMessage), tags=["forms"]) async def get(self, request: Request) -> JSONResponse: """Returns single form information by ID.""" - admin = request.user.payload["admin"] if request.user.is_authenticated else False # noqa + admin = request.user.admin if request.user.is_authenticated else False filters = { "_id": request.path_params["form_id"] diff --git a/backend/routes/forms/submit.py b/backend/routes/forms/submit.py index 55a4875..8627a29 100644 --- a/backend/routes/forms/submit.py +++ b/backend/routes/forms/submit.py @@ -127,6 +127,7 @@ class SubmitForm(Route): if constants.FormFeatures.REQUIRES_LOGIN.value in form.features: if request.user.is_authenticated: response["user"] = request.user.payload + response["user"]["admin"] = request.user.admin if constants.FormFeatures.COLLECT_EMAIL.value in form.features and "email" not in response["user"]: # noqa return JSONResponse({ -- cgit v1.2.3 From f90d0c7fddb81215b907808b8365f63f42344652 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Sun, 21 Feb 2021 01:44:01 +0300 Subject: Dynamically Selects OAuth Redirect URI Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/discord.py | 6 +++--- backend/routes/auth/authorize.py | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) (limited to 'backend') diff --git a/backend/discord.py b/backend/discord.py index 9cdd2c4..8cb602c 100644 --- a/backend/discord.py +++ b/backend/discord.py @@ -2,18 +2,18 @@ import httpx from backend.constants import ( - OAUTH2_CLIENT_ID, OAUTH2_CLIENT_SECRET, OAUTH2_REDIRECT_URI + OAUTH2_CLIENT_ID, OAUTH2_CLIENT_SECRET ) API_BASE_URL = "https://discord.com/api/v8" -async def fetch_bearer_token(code: str, *, refresh: bool) -> dict: +async def fetch_bearer_token(code: str, redirect: str, *, refresh: bool) -> dict: async with httpx.AsyncClient() as client: data = { "client_id": OAUTH2_CLIENT_ID, "client_secret": OAUTH2_CLIENT_SECRET, - "redirect_uri": OAUTH2_REDIRECT_URI + "redirect_uri": f"{redirect}/callback" } if refresh: diff --git a/backend/routes/auth/authorize.py b/backend/routes/auth/authorize.py index c6cd86c..65709ab 100644 --- a/backend/routes/auth/authorize.py +++ b/backend/routes/auth/authorize.py @@ -87,7 +87,8 @@ class AuthorizeRoute(Route): """Generate an authorization token.""" data = await request.json() try: - bearer_token = await fetch_bearer_token(data["token"], refresh=False) + url = request.headers.get("origin") + bearer_token = await fetch_bearer_token(data["token"], url, refresh=False) except httpx.HTTPStatusError: return AUTH_FAILURE @@ -111,7 +112,8 @@ class TokenRefreshRoute(Route): """Refresh an authorization token.""" try: token = request.user.decoded_token.get("refresh") - bearer_token = await fetch_bearer_token(token, refresh=True) + url = request.headers.get("origin") + bearer_token = await fetch_bearer_token(token, url, refresh=True) except httpx.HTTPStatusError: return AUTH_FAILURE -- cgit v1.2.3 From c175279e4172160f0d119ddd93dce8a813fff69b Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Mon, 1 Mar 2021 16:51:25 +0300 Subject: Allows All CORS Requests On Development Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/__init__.py | 4 ++-- docker-compose.yml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'backend') diff --git a/backend/__init__.py b/backend/__init__.py index d56edfb..5c91a65 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -16,8 +16,8 @@ ORIGINS = [ r"(https?://[^.?#]*.forms-frontend.pages.dev)", # Cloudflare Previews ] if not constants.PRODUCTION: - # Add localhost to allowed origins on non-production deployments - ORIGINS.append(r"(https?://localhost:\d{0,4})") + # Allow all hosts on non-production deployments + ORIGINS.append(r"(.*)") ALLOW_ORIGIN_REGEX = "|".join(ORIGINS) diff --git a/docker-compose.yml b/docker-compose.yml index 4e58ef7..8ee46be 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,3 +37,4 @@ services: - OAUTH2_CLIENT_SECRET - ALLOWED_URL - DEBUG=true + - PRODUCTION=false -- cgit v1.2.3 From da41f255a06516c1b7b85a587b982535cd7fec54 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Mon, 1 Mar 2021 16:56:02 +0300 Subject: Make Admin Fetch Async Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/authentication/backend.py | 2 +- backend/authentication/user.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'backend') diff --git a/backend/authentication/backend.py b/backend/authentication/backend.py index bdff796..206d1eb 100644 --- a/backend/authentication/backend.py +++ b/backend/authentication/backend.py @@ -61,7 +61,7 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): raise authentication.AuthenticationError("Could not parse user details.") user = User(token, user_details) - if user.fetch_admin_status(request): + if await user.fetch_admin_status(request): scopes.append("admin") return authentication.AuthCredentials(scopes), user diff --git a/backend/authentication/user.py b/backend/authentication/user.py index 52baa61..857c2ed 100644 --- a/backend/authentication/user.py +++ b/backend/authentication/user.py @@ -34,8 +34,8 @@ class User(BaseUser): def decoded_token(self) -> dict[str, any]: return jwt.decode(self.token, SECRET_KEY, algorithms=["HS256"]) - def fetch_admin_status(self, request: Request) -> bool: - self.admin = request.state.db.admins.find_one( + async def fetch_admin_status(self, request: Request) -> bool: + self.admin = await request.state.db.admins.find_one( {"_id": self.payload["id"]} ) is not None -- cgit v1.2.3 From 02154294da8b25bf7dae1b79f170aab888f92797 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Sat, 6 Mar 2021 22:42:52 +0300 Subject: Renames Token To `token` Changes the name for the token used to authorize with the backend. Co-authored-by: Joe Banks --- backend/authentication/backend.py | 2 +- backend/routes/auth/authorize.py | 4 ++-- backend/routes/forms/submit.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'backend') diff --git a/backend/authentication/backend.py b/backend/authentication/backend.py index 206d1eb..c7590e9 100644 --- a/backend/authentication/backend.py +++ b/backend/authentication/backend.py @@ -33,7 +33,7 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend): self, request: Request ) -> t.Optional[tuple[authentication.AuthCredentials, authentication.BaseUser]]: """Handles JWT authentication process.""" - cookie = request.cookies.get("BackendToken") + cookie = request.cookies.get("token") if not cookie: return None diff --git a/backend/routes/auth/authorize.py b/backend/routes/auth/authorize.py index 65709ab..98f9887 100644 --- a/backend/routes/auth/authorize.py +++ b/backend/routes/auth/authorize.py @@ -41,7 +41,7 @@ async def process_token(bearer_token: dict) -> Union[AuthorizeResponse, AUTH_FAI try: user_details = await fetch_user_details(bearer_token["access_token"]) except httpx.HTTPStatusError: - AUTH_FAILURE.delete_cookie("BackendToken") + AUTH_FAILURE.delete_cookie("token") return AUTH_FAILURE max_age = datetime.timedelta(seconds=int(bearer_token["expires_in"])) @@ -63,7 +63,7 @@ async def process_token(bearer_token: dict) -> Union[AuthorizeResponse, AUTH_FAI }) response.set_cookie( - "BackendToken", f"JWT {token}", + "token", f"JWT {token}", secure=constants.PRODUCTION, httponly=True, samesite="strict", max_age=bearer_token["expires_in"] ) diff --git a/backend/routes/forms/submit.py b/backend/routes/forms/submit.py index 4224586..8680b2d 100644 --- a/backend/routes/forms/submit.py +++ b/backend/routes/forms/submit.py @@ -75,7 +75,7 @@ class SubmitForm(Route): expiry = None response.set_cookie( - "BackendToken", f"JWT {request.user.token}", + "token", f"JWT {request.user.token}", secure=constants.PRODUCTION, httponly=True, samesite="strict", max_age=(expiry - datetime.datetime.now()).seconds ) -- cgit v1.2.3 From ca730082b523e62595687843a914adad8dbbaccf Mon Sep 17 00:00:00 2001 From: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> Date: Sat, 6 Mar 2021 22:48:19 +0300 Subject: Formats Authorize File Cleans up the authorize file, and the __init__ to maintain the project's code style. Co-authored-by: Joe Banks Signed-off-by: Hassan Abouelela <47495861+HassanAbouelela@users.noreply.github.com> --- backend/__init__.py | 1 + backend/routes/auth/authorize.py | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'backend') diff --git a/backend/__init__.py b/backend/__init__.py index 5c91a65..220b457 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -15,6 +15,7 @@ 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 ORIGINS.append(r"(.*)") diff --git a/backend/routes/auth/authorize.py b/backend/routes/auth/authorize.py index 98f9887..26d8622 100644 --- a/backend/routes/auth/authorize.py +++ b/backend/routes/auth/authorize.py @@ -21,6 +21,8 @@ from backend.discord import fetch_bearer_token, fetch_user_details from backend.route import Route from backend.validation import ErrorMessage, api +AUTH_FAILURE = JSONResponse({"error": "auth_failure"}, status_code=400) + class AuthorizeRequest(BaseModel): token: str = Field(description="The access token received from Discord.") @@ -31,9 +33,6 @@ class AuthorizeResponse(BaseModel): expiry: str = Field("ISO formatted timestamp of expiry.") -AUTH_FAILURE = JSONResponse({"error": "auth_failure"}, status_code=400) - - async def process_token(bearer_token: dict) -> Union[AuthorizeResponse, AUTH_FAILURE]: """Post a bearer token to Discord, and return a JWT and username.""" interaction_start = datetime.datetime.now() -- cgit v1.2.3