-
Notifications
You must be signed in to change notification settings - Fork 3
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
83a0ff5
commit 76500b9
Showing
13 changed files
with
273 additions
and
69 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
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,105 @@ | ||
import requests | ||
from fastapi import Depends, HTTPException, Request, status | ||
from fastapi.security import OAuth2PasswordBearer | ||
from jose import JOSEError, jwt | ||
from sqlalchemy import text | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
|
||
from src.core.config import settings | ||
from src.endpoints.deps import get_db | ||
|
||
auth_key = None | ||
try: | ||
ISSUER_URL = f"{settings.KEYCLOAK_SERVER_URL}/realms/{settings.REALM_NAME}" | ||
|
||
_auth_server_public_key = requests.get(ISSUER_URL).json().get("public_key") | ||
auth_key = ( | ||
"-----BEGIN PUBLIC KEY-----\n" | ||
+ _auth_server_public_key | ||
+ "\n-----END PUBLIC KEY-----" | ||
) # noqa: E501 | ||
except Exception: | ||
print("Error getting public key from Keycloak") | ||
|
||
oauth2_scheme = OAuth2PasswordBearer( | ||
tokenUrl=f"{settings.API_V2_STR}/auth/access-token", | ||
) | ||
|
||
|
||
def decode_token(token: str): | ||
""" | ||
Decodes a JWT token. | ||
""" | ||
user_token = jwt.decode( | ||
token, | ||
key=auth_key, | ||
options={ | ||
"verify_signature": True, | ||
"verify_aud": False, | ||
"verify_iss": ISSUER_URL, | ||
}, | ||
) | ||
|
||
return user_token | ||
|
||
|
||
async def auth(token: str = Depends(oauth2_scheme)) -> str: | ||
try: | ||
decode_token(token) | ||
except JOSEError as e: | ||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e)) | ||
|
||
return token | ||
|
||
|
||
def user_token(token: str = Depends(auth)) -> dict: | ||
payload = decode_token(token) | ||
return payload | ||
|
||
|
||
def is_superuser(user_token: dict = Depends(user_token), throw_error: bool = True): | ||
is_superuser = False | ||
if user_token["realm_access"] and user_token["realm_access"]["roles"]: | ||
is_superuser = "superuser" in user_token["realm_access"]["roles"] | ||
|
||
if not is_superuser and throw_error: | ||
raise HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized" | ||
) | ||
|
||
return is_superuser | ||
|
||
|
||
def clean_path(path: str) -> str: | ||
return path.replace(settings.API_V2_STR + "/", "") | ||
|
||
|
||
async def auth_z( | ||
request: Request, | ||
user_token: dict = Depends(user_token), | ||
async_session: AsyncSession = Depends(get_db), | ||
) -> bool: | ||
try: | ||
user_id = user_token["sub"] | ||
path = request.scope.get("path") | ||
route = request.scope.get("route") | ||
method = request.scope.get("method") | ||
if path and route and method and user_id: | ||
cleaned_path = clean_path( | ||
path | ||
) # e.g /organizations/b65e040a-f8f0-453f-9888-baa2b9342cce | ||
cleaned_route_path = clean_path( | ||
route.path | ||
) # e.g /organizations/{organization_id} | ||
authz_query = text( | ||
f"SELECT * FROM {settings.ACCOUNTS_SCHEMA}.authorization('{user_id}', '{cleaned_route_path}', '{cleaned_path}', '{method}');" | ||
) | ||
response = await async_session.execute(authz_query) | ||
state = response.scalars().all() | ||
if not state or not len(state) or state[0] is False: | ||
raise ValueError("Unauthorized") | ||
return True | ||
else: | ||
raise ValueError("Missing path, route, or method in request scope") | ||
except Exception as e: | ||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e)) |
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
Oops, something went wrong.