-
Notifications
You must be signed in to change notification settings - Fork 19
Migrate discord OAuth to fastapi #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mohamed040406
merged 17 commits into
Tech-With-Tim:fastapi-rewrite
from
mohamed040406:auth
Aug 2, 2021
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
09e77f5
Migrate discord OAuth to fastapi
mohamed040406 cd51e2d
Whoops
mohamed040406 89f574d
Fix workflow
mohamed040406 5086ac2
Update `User` Model
mohamed040406 34f6078
Remove `requests`
mohamed040406 9f1e708
Update folder tree
mohamed040406 14aba01
remove models
mohamed040406 f5621a8
Add models submodule
mohamed040406 d695e09
Fix submodule
mohamed040406 b2f7659
fixes.
mohamed040406 af593e5
Fix Dockerfiles
mohamed040406 67b8ffd
should be good now!
mohamed040406 cf60d66
hmmm
mohamed040406 13d1ba5
fix
mohamed040406 f82ddd8
whoops
mohamed040406 5efb4dd
mhm
mohamed040406 a099b0a
format imports
mohamed040406 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| [submodule "api/models"] | ||
| path = api/models | ||
| url = https://github.com/Tech-With-Tim/models |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| from aiohttp import ClientSession | ||
| from typing import Optional | ||
|
|
||
| session: Optional[ClientSession] = None | ||
|
|
||
| __all__ = (session,) |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| from .routes import router | ||
|
|
||
|
|
||
| __all__ = (router,) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import config | ||
| import typing | ||
|
|
||
| from urllib.parse import quote_plus | ||
|
|
||
| from api.http_session import session | ||
|
|
||
| DISCORD_ENDPOINT = "https://discord.com/api" | ||
| SCOPES = ["identify"] | ||
|
|
||
|
|
||
| async def exchange_code( | ||
| *, code: str, scope: str, redirect_uri: str, grant_type: str = "authorization_code" | ||
| ) -> typing.Tuple[dict, int]: | ||
| """Exchange discord oauth code for access and refresh tokens.""" | ||
| async with session.post( | ||
| "%s/v6/oauth2/token" % DISCORD_ENDPOINT, | ||
| data=dict( | ||
| code=code, | ||
| scope=scope, | ||
| grant_type=grant_type, | ||
| redirect_uri=redirect_uri, | ||
| client_id=config.discord_client_id(), | ||
| client_secret=config.discord_client_secret(), | ||
| ), | ||
| headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||
| ) as response: | ||
| return await response.json(), response.status | ||
|
|
||
|
|
||
| async def get_user(access_token: str) -> dict: | ||
| """Coroutine to fetch User data from discord using the users `access_token`""" | ||
| async with session.get( | ||
| "%s/v6/users/@me" % DISCORD_ENDPOINT, | ||
| headers={"Authorization": "Bearer %s" % access_token}, | ||
| ) as response: | ||
| return await response.json() | ||
|
|
||
|
|
||
| def format_scopes(scopes: typing.List[str]) -> str: | ||
| """Format a list of scopes.""" | ||
| return " ".join(scopes) | ||
|
|
||
|
|
||
| def get_redirect(callback: str, scopes: typing.List[str]) -> str: | ||
| """Generates the correct oauth link depending on our provided arguments.""" | ||
| return ( | ||
| "{BASE}/oauth2/authorize?response_type=code" | ||
| "&client_id={client_id}" | ||
| "&scope={scopes}" | ||
| "&redirect_uri={redirect_uri}" | ||
| "&prompt=consent" | ||
| ).format( | ||
| BASE=DISCORD_ENDPOINT, | ||
| scopes=format_scopes(scopes), | ||
| redirect_uri=quote_plus(callback), | ||
| client_id=config.discord_client_id(), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| from datetime import datetime | ||
| from pydantic import BaseModel, HttpUrl | ||
|
|
||
|
|
||
| class CallbackResponse(BaseModel): | ||
| token: str | ||
| exp: datetime | ||
|
|
||
|
|
||
| class CallbackBody(BaseModel): | ||
| code: str | ||
| callback: HttpUrl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import jwt | ||
| import utils | ||
| import config | ||
|
|
||
| from pydantic import HttpUrl | ||
| from fastapi import APIRouter, Request | ||
| from datetime import datetime, timedelta | ||
| from fastapi.responses import RedirectResponse | ||
|
|
||
| from api.models import User, Token | ||
| from .models import CallbackBody, CallbackResponse | ||
| from .helpers import ( | ||
| SCOPES, | ||
| get_user, | ||
| get_redirect, | ||
| exchange_code, | ||
| format_scopes, | ||
| ) | ||
|
|
||
| router = APIRouter(prefix="/auth") | ||
|
|
||
|
|
||
| @router.get( | ||
| "/discord/redirect", | ||
| tags=["auth"], | ||
| status_code=307, | ||
| ) | ||
| async def redirect_to_discord_oauth_portal(request: Request, callback: HttpUrl = None): | ||
| """Redirect user to correct oauth link depending on specified domain and requested scopes.""" | ||
| callback = callback or (str(request.base_url) + "v1/auth/discord/callback") | ||
|
|
||
| return RedirectResponse( | ||
| get_redirect(callback=callback, scopes=SCOPES), status_code=307 | ||
| ) | ||
|
|
||
|
|
||
| if config.debug(): | ||
|
|
||
| @router.get( | ||
| "/discord/callback", | ||
| tags=["auth"], | ||
| response_model=CallbackResponse, | ||
| response_description="GET Discord OAuth Callback", | ||
| ) | ||
| async def get_discord_oauth_callback( | ||
| request: Request, code: str, callback: HttpUrl = None | ||
| ): | ||
| """ | ||
| Callback endpoint for finished discord authorization flow. | ||
mohamed040406 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| callback = callback or (str(request.base_url) + "v1/auth/discord/callback") | ||
| return await post_discord_oauth_callback(code, callback) | ||
mohamed040406 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| @router.post( | ||
| "/discord/callback", | ||
| tags=["auth"], | ||
| response_model=CallbackResponse, | ||
| response_description="POST Discord OAuth Callback", | ||
| ) | ||
| async def post_discord_oauth_callback(data: CallbackBody): | ||
| """ | ||
| Callback endpoint for finished discord authorization flow. | ||
| """ | ||
| access_data, status_code = await exchange_code( | ||
| code=data.code, scope=format_scopes(SCOPES), redirect_uri=data.callback | ||
| ) | ||
|
|
||
| if access_data.get("error", False): | ||
| if status_code == 400: | ||
| return utils.JSONResponse( | ||
| { | ||
| "error": "Bad Request", | ||
| "message": "Discord returned 400 status.", | ||
| "data": access_data, | ||
| }, | ||
| 400, | ||
| ) | ||
|
|
||
| if status_code < 200 or status_code >= 300: | ||
| return utils.JSONResponse( | ||
| { | ||
| "error": "Bad Gateway", | ||
| "message": "Discord returned non 2xx status code", | ||
| }, | ||
| 502, | ||
| ) | ||
|
|
||
| expires_at = datetime.utcnow() + timedelta(seconds=access_data["expires_in"]) | ||
| expires_at = expires_at.replace(microsecond=0) | ||
|
|
||
| user_data = await get_user(access_token=access_data["access_token"]) | ||
| user_data["id"] = uid = int(user_data["id"]) | ||
|
|
||
| user = await User.fetch(id=uid) | ||
|
|
||
| if user is None: | ||
| user = await User.create( | ||
| id=user_data["id"], | ||
| username=user_data["username"], | ||
| discriminator=user_data["discriminator"], | ||
| avatar=user_data["avatar"], | ||
| ) | ||
|
|
||
| await Token( | ||
| user_id=user.id, | ||
| data=access_data, | ||
| expires_at=expires_at, | ||
| token=access_data["access_token"], | ||
| ).update() | ||
|
|
||
| token = jwt.encode( | ||
| {"uid": user.id, "exp": expires_at, "iat": datetime.utcnow()}, | ||
| key=config.secret_key(), | ||
| ) | ||
|
|
||
| return {"token": token, "exp": expires_at} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| from fastapi import APIRouter | ||
| from . import auth | ||
|
|
||
| router = APIRouter(prefix="/v1") | ||
|
|
||
| router.include_router(auth.router) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ordering isn't logical at all, ordering by length doesn't make sense to me. Order by first party, third party and local packages and in each of them put
imports thenfrom ... imports and each of these categories order alphabetically or just useisort.