Skip to content
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

Add FastAPI Support #73

Merged
merged 7 commits into from Nov 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -21,3 +21,4 @@ venv/
*.sqlite3

flask_example/config.py
fastapi_example/.env
lepture marked this conversation as resolved.
Show resolved Hide resolved
32 changes: 32 additions & 0 deletions fastapi_example/app.py
@@ -0,0 +1,32 @@
from authlib.integrations.starlette_client import OAuth
from fastapi.responses import HTMLResponse
from starlette.config import Config
from starlette.middleware.sessions import SessionMiddleware
from loginpass import create_fastapi_routes, Twitter, GitHub, Google

from fastapi import FastAPI

app = FastAPI()

config = Config(".env")
oauth = OAuth(config)

app.add_middleware(SessionMiddleware, secret_key=config.get("SECRET_KEY"))

backends = [Twitter, GitHub, Google]


@app.get("/", response_class=HTMLResponse)
async def root() -> str:
tpl = '<li><a href="/login/{}">{}</a></li>'
lis = [tpl.format(b.NAME, b.NAME) for b in backends]
return "<ul>{}</ul>".format("".join(lis))


def handle_authorize(remote, token, user_info, request):
return user_info


router = create_fastapi_routes(backends, oauth, handle_authorize)

app.include_router(router)
56 changes: 56 additions & 0 deletions fastapi_example/example.env
@@ -0,0 +1,56 @@
SECRET_KEY=secret

TWITTER_CLIENT_ID=
TWITTER_CLIENT_SECRET=

FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=

DROPBOX_CLIENT_ID=
DROPBOX_CLIENT_SECRET=

REDDIT_CLIENT_ID=
REDDIT_CLIENT_SECRET=

GITLAB_CLIENT_ID=
GITLAB_CLIENT_SECRET=

SLACK_CLIENT_ID=
SLACK_CLIENT_SECRET=

DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=

STACKOVERFLOW_CLIENT_ID=
STACKOVERFLOW_CLIENT_SECRET=
# STACKOVERFLOW_CLIENT_KWARGS={
# 'api_key': '', # required
# 'api_filter': '' # optional
# }

BITBUCKET_CLIENT_ID=
BITBUCKET_CLIENT_SECRET=

STRAVA_CLIENT_ID=
STRAVA_CLIENT_SECRET=

SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=

YANDEX_CLIENT_ID=
YANDEX_CLIENT_SECRET=

TWITCH_CLIENT_ID=
TWITCH_CLIENT_SECRET=

VK_CLIENT_ID=
VK_CLIENT_SECRET=

BATTLENET_CLIENT_ID=
BATTLENET_CLIENT_SECRET=
3 changes: 3 additions & 0 deletions loginpass/__init__.py
@@ -1,4 +1,5 @@
from ._flask import create_flask_blueprint
from ._fastapi import create_fastapi_routes
from ._django import create_django_urlpatterns
from ._consts import version, homepage
from .azure import Azure, create_azure_backend
Expand Down Expand Up @@ -27,12 +28,14 @@

__all__ = [
'create_flask_blueprint',
'create_fastapi_routes',
'create_django_urlpatterns',
'Azure', 'create_azure_backend',
'BattleNet', 'create_battlenet_backend',
'Google', 'GoogleServiceAccount',
'GitHub',
'Facebook',
'Instagram',
'Twitter',
'Dropbox',
'LinkedIn',
Expand Down
94 changes: 94 additions & 0 deletions loginpass/_fastapi.py
@@ -0,0 +1,94 @@

def create_fastapi_routes(backends, oauth, handle_authorize):
"""Create a Fastapi routes that you can register it directly to fastapi
app. The routes contains two route: ``/auth/<backend>`` and
``/login/<backend>``::

from authlib.integrations.starlette_client import OAuth
from fastapi.responses import HTMLResponse
from starlette.config import Config
from starlette.middleware.sessions import SessionMiddleware
from loginpass import create_fastapi_routes, Twitter, GitHub, Google

from fastapi import FastAPI

app = FastAPI()
config = Config(".env")
oauth = OAuth(config)

app.add_middleware(SessionMiddleware, secret_key=config.get("SECRET_KEY"))

def handle_authorize(remote, token, user_info, request):
return user_info

router = create_fastapi_routes([GitHub, Google], oauth, handle_authorize)
app.include_router(router, prefix="/account")

# visit /account/login/github
# callback /account/auth/github

:param backends: A list of configured backends
:param oauth: Authlib Flask OAuth instance
:param handle_authorize: A function to handle authorized response
:return: Fastapi APIRouter instance
"""
from fastapi import Request, APIRouter
from fastapi.exceptions import HTTPException

router = APIRouter()

for b in backends:
register_to(oauth, b)

@router.get("/auth/{backend}")
async def auth(
backend: str,
id_token: str = None,
code: str = None,
oauth_verifier: str = None,
request: Request = None,
):
remote = oauth.create_client(backend)
if remote is None:
raise HTTPException(404)

if code:
token = await remote.authorize_access_token(request)
if id_token:
token["id_token"] = id_token
elif id_token:
token = {"id_token": id_token}
elif oauth_verifier:
# OAuth 1
token = await remote.authorize_access_token(request)
else:
# handle failed
return handle_authorize(remote, None, None)
if "id_token" in token:
user_info = await remote.parse_id_token(request, token)
else:
remote.token = token
user_info = await remote.userinfo(token=token)
return handle_authorize(remote, token, user_info, request)

@router.get("/login/{backend}")
async def login(backend: str, request: Request):
remote = oauth.create_client(backend)
if remote is None:
raise HTTPException(404)

redirect_uri = request.url_for("auth", backend="google")
conf_key = "{}_AUTHORIZE_PARAMS".format(backend.upper())
params = oauth.config.get(conf_key, default={})
return await remote.authorize_redirect(request, redirect_uri, **params)

return router


def register_to(oauth, backend_cls):
from authlib.integrations.starlette_client import StarletteRemoteApp

class RemoteApp(backend_cls, StarletteRemoteApp):
OAUTH_APP_CONFIG = backend_cls.OAUTH_CONFIG

oauth.register(RemoteApp.NAME, overwrite=True, client_cls=RemoteApp)