-
Notifications
You must be signed in to change notification settings - Fork 21
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
feat: support local auth #593
Merged
+272
−204
Merged
Changes from all commits
Commits
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 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
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
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 |
---|---|---|
|
@@ -2842,10 +2842,10 @@ | |
resolved "https://registry.yarnpkg.com/@panva/hkdf/-/hkdf-1.2.1.tgz#cb0d111ef700136f4580349ff0226bf25c853f23" | ||
integrity sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw== | ||
|
||
"@petercatai/[email protected].20": | ||
version "1.0.20" | ||
resolved "https://registry.yarnpkg.com/@petercatai/assistant/-/assistant-1.0.20.tgz#2d2dc1beb296c8524219a6de7eee1575cb3b4c92" | ||
integrity sha512-csfRRsKB9FbBM+cMcCTQQowsuuFRVerSrxfMRTWoI1XHhBW3ormbt1XTeYKiubmwz4iKznR+2UCrZrCl75ckmA== | ||
"@petercatai/[email protected].22": | ||
version "1.0.22" | ||
resolved "https://registry.yarnpkg.com/@petercatai/assistant/-/assistant-1.0.22.tgz#a4113bf4eae9dc66ad0f0e2b33b1f579ca1252a2" | ||
integrity sha512-E8uMZRK3bdD9Oh2mQhK6Zd2A+KV6dt/H2F/fnv/cBT6KOdywwDQIx94K/2fTcpZJXPsUCTMcOhl2877FNaJkxQ== | ||
dependencies: | ||
"@ant-design/icons" "^5.3.5" | ||
"@ant-design/pro-chat" "^1.9.0" | ||
|
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,12 @@ | ||
from auth.clients.auth0 import Auth0Client | ||
from auth.clients.base import BaseAuthClient | ||
from auth.clients.local import LocalClient | ||
|
||
from petercat_utils import get_env_variable | ||
|
||
PETERCAT_AUTH0_ENABLED = get_env_variable("PETERCAT_AUTH0_ENABLED", "True") == "True" | ||
|
||
def get_auth_client() -> BaseAuthClient: | ||
if PETERCAT_AUTH0_ENABLED: | ||
return Auth0Client() | ||
return LocalClient() |
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,92 @@ | ||
import httpx | ||
import secrets | ||
|
||
from fastapi import Request | ||
from auth.clients.base import BaseAuthClient | ||
from petercat_utils import get_env_variable | ||
from starlette.config import Config | ||
from authlib.integrations.starlette_client import OAuth | ||
|
||
CLIENT_ID = get_env_variable("AUTH0_CLIENT_ID") | ||
CLIENT_SECRET = get_env_variable("AUTH0_CLIENT_SECRET") | ||
AUTH0_DOMAIN = get_env_variable("AUTH0_DOMAIN") | ||
API_AUDIENCE = get_env_variable("API_IDENTIFIER") | ||
API_URL = get_env_variable("API_URL") | ||
|
||
CALLBACK_URL = f"{API_URL}/api/auth/callback" | ||
|
||
config = Config( | ||
environ={ | ||
"AUTH0_CLIENT_ID": CLIENT_ID, | ||
"AUTH0_CLIENT_SECRET": CLIENT_SECRET, | ||
} | ||
) | ||
|
||
class Auth0Client(BaseAuthClient): | ||
_client: OAuth | ||
|
||
def __init__(self): | ||
self._client = OAuth(config) | ||
self._client.register( | ||
name="auth0", | ||
server_metadata_url=f"https://{AUTH0_DOMAIN}/.well-known/openid-configuration", | ||
client_kwargs={"scope": "openid email profile"}, | ||
) | ||
|
||
async def login(self, request): | ||
return await self._client.auth0.authorize_redirect( | ||
request, redirect_uri=CALLBACK_URL | ||
) | ||
|
||
async def get_oauth_token(self): | ||
url = f'https://{AUTH0_DOMAIN}/oauth/token' | ||
headers = {"content-type": "application/x-www-form-urlencoded"} | ||
data = { | ||
'client_id': CLIENT_ID, | ||
'client_secret': CLIENT_SECRET, | ||
'audience': API_AUDIENCE, | ||
'grant_type': 'client_credentials' | ||
} | ||
async with httpx.AsyncClient() as client: | ||
response = await client.post(url, data=data, headers=headers) | ||
return response.json()['access_token'] | ||
|
||
async def get_user_info(self, request: Request) -> dict: | ||
auth0_token = await self._client.auth0.authorize_access_token(request) | ||
access_token = auth0_token["access_token"] | ||
userinfo_url = f"https://{AUTH0_DOMAIN}/userinfo" | ||
headers = {"authorization": f"Bearer {access_token}"} | ||
async with httpx.AsyncClient() as client: | ||
user_info_response = await client.get(userinfo_url, headers=headers) | ||
if user_info_response.status_code == 200: | ||
user_info = user_info_response.json() | ||
RaoHai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
data = { | ||
"id": user_info["sub"], | ||
"nickname": user_info.get("nickname"), | ||
"name": user_info.get("name"), | ||
"picture": user_info.get("picture"), | ||
"sub": user_info["sub"], | ||
"sid": secrets.token_urlsafe(32), | ||
"agreement_accepted": user_info.get("agreement_accepted"), | ||
} | ||
return data | ||
else: | ||
return None | ||
|
||
async def get_access_token(self, user_id: str, provider="github"): | ||
token = await self.get_oauth_token() | ||
user_accesstoken_url = f"https://{AUTH0_DOMAIN}/api/v2/users/{user_id}" | ||
|
||
async with httpx.AsyncClient() as client: | ||
headers = {"authorization": f"Bearer {token}"} | ||
user_info_response = await client.get(user_accesstoken_url, headers=headers) | ||
user = user_info_response.json() | ||
identity = next( | ||
( | ||
identity | ||
for identity in user["identities"] | ||
if identity["provider"] == provider | ||
), | ||
None, | ||
) | ||
return identity["access_token"] |
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,51 @@ | ||
import secrets | ||
|
||
from abc import abstractmethod | ||
from fastapi import Request | ||
from utils.random_str import random_str | ||
from petercat_utils import get_client | ||
|
||
|
||
class BaseAuthClient: | ||
def __init__(self): | ||
pass | ||
|
||
def generateAnonymousUser(self, clientId: str) -> tuple[str, dict]: | ||
token = f"client|{clientId}" | ||
seed = clientId[:4] | ||
random_name = f"{seed}_{random_str(4)}" | ||
data = { | ||
"id": token, | ||
"sub": token, | ||
"nickname": random_name, | ||
"name": random_name, | ||
"picture": f"https://picsum.photos/seed/{seed}/100/100", | ||
"sid": secrets.token_urlsafe(32), | ||
"agreement_accepted": False, | ||
} | ||
|
||
return token, data | ||
|
||
async def anonymouseLogin(self, request: Request) -> dict: | ||
clientId = request.query_params.get("clientId") or random_str() | ||
token, data = self.generateAnonymousUser(clientId = clientId) | ||
supabase = get_client() | ||
supabase.table("profiles").upsert(data).execute() | ||
request.session["user"] = data | ||
return data | ||
|
||
@abstractmethod | ||
async def login(self, request: Request): | ||
pass | ||
|
||
@abstractmethod | ||
async def get_oauth_token(self) -> str: | ||
pass | ||
|
||
@abstractmethod | ||
async def get_user_info(self, request: Request) -> dict: | ||
pass | ||
|
||
@abstractmethod | ||
async def get_access_token(self, user_id: str, provider="github") -> str: | ||
pass |
Oops, something went wrong.
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.
Ensure to handle potential exceptions when accessing
response.json()['access_token']
to avoid runtime errors in case of unexpected response formats or errors.