generated from MinBZK/python-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
131c8dd
commit 0f51081
Showing
13 changed files
with
350 additions
and
19 deletions.
There are no files selected for viewing
This file contains 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 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,10 +1,11 @@ | ||
from fastapi import APIRouter | ||
|
||
from amt.api.routes import health, pages, project, projects, root | ||
from amt.api.routes import auth, health, pages, project, projects, root | ||
|
||
api_router = APIRouter() | ||
api_router.include_router(root.router) | ||
api_router.include_router(health.router, prefix="/health", tags=["health"]) | ||
api_router.include_router(pages.router, prefix="/pages", tags=["pages"]) | ||
api_router.include_router(projects.router, prefix="/projects", tags=["projects"]) | ||
api_router.include_router(project.router, prefix="/project", tags=["projects"]) | ||
api_router.include_router(auth.router, prefix="/auth", tags=["auth"]) |
This file contains 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,56 @@ | ||
import logging | ||
|
||
from authlib.integrations.starlette_client import OAuth, OAuthError # type: ignore | ||
from fastapi import APIRouter, Request | ||
from fastapi.responses import HTMLResponse, RedirectResponse, Response | ||
|
||
from amt.core.authorization import get_user, no_authorization | ||
from amt.core.exceptions import AMTAuthorizationError | ||
|
||
router = APIRouter() | ||
logger = logging.getLogger(__name__) | ||
|
||
|
||
@router.get("/login") | ||
@no_authorization | ||
async def login(request: Request) -> HTMLResponse: | ||
oauth: OAuth = request.app.state.oauth | ||
redirect_uri = request.url_for("auth_callback") | ||
return await oauth.keycloak.authorize_redirect(request, redirect_uri) # type: ignore | ||
|
||
|
||
@router.get("/logout") | ||
@no_authorization | ||
async def logout(request: Request) -> RedirectResponse: | ||
user = get_user(request) | ||
id_token = request.session.get("id_token", None) | ||
request.session.pop("user", None) | ||
request.session.pop("id_token", None) | ||
|
||
if user: | ||
redirect_uri = request.url_for("base") | ||
return RedirectResponse( | ||
url=user["iss"] | ||
+ "/protocol/openid-connect/logout?id_token_hint=" | ||
+ id_token | ||
+ "&post_logout_redirect_uri=" | ||
+ str(redirect_uri) | ||
) | ||
|
||
return RedirectResponse(url="/") | ||
|
||
|
||
@router.get("/callback", response_class=Response) | ||
@no_authorization | ||
async def auth_callback(request: Request) -> Response: | ||
oauth: OAuth = request.app.state.oauth | ||
try: | ||
token = await oauth.keycloak.authorize_access_token(request) # type: ignore | ||
except OAuthError as error: | ||
raise AMTAuthorizationError() from error | ||
|
||
user: dict = token.get("userinfo") # type: ignore | ||
if user: | ||
request.session["user"] = dict(user) # type: ignore | ||
request.session["id_token"] = token["id_token"] # type: ignore | ||
return RedirectResponse(url="/") |
This file contains 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 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,23 @@ | ||
from collections.abc import Callable | ||
from functools import wraps | ||
from typing import Any | ||
|
||
from starlette.requests import Request | ||
|
||
|
||
def get_user(request: Request) -> dict[str, str] | None: | ||
user = None | ||
if "session" in request.scope: | ||
user = request.session.get("user", None) | ||
return user | ||
|
||
|
||
def no_authorization(func: Callable[..., Any]): # noqa: ANN201 | ||
@wraps(func) | ||
async def wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 | ||
request: Request = kwargs.get("request") # type: ignore | ||
if request: | ||
request.state.noauth = True | ||
return await func(*args, **kwargs) | ||
|
||
return wrapper |
This file contains 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 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 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,31 @@ | ||
import os | ||
import typing | ||
|
||
from starlette.middleware.base import BaseHTTPMiddleware | ||
from starlette.requests import Request | ||
from starlette.responses import Response | ||
|
||
from amt.core.authorization import get_user | ||
from amt.core.exceptions import AMTAuthorizationError | ||
|
||
RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] | ||
|
||
|
||
class AuthorizationMiddleware(BaseHTTPMiddleware): | ||
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: | ||
if request.url.path.startswith("/static/"): | ||
return await call_next(request) | ||
|
||
user = get_user(request) | ||
if user: | ||
return await call_next(request) | ||
|
||
response = await call_next(request) | ||
## todo: move to decorator function | ||
if hasattr(request.state, "noauth"): | ||
return response | ||
|
||
if os.environ.get("PYTEST_CURRENT_TEST", False): | ||
return response | ||
|
||
raise AMTAuthorizationError() |
This file contains 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 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
Oops, something went wrong.