-
Notifications
You must be signed in to change notification settings - Fork 2
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
Refactor auth code to output auth scheme in OpenAPI spec #418
Closed
+89
−51
Closed
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6442d2d
Refactor auth code to output auth scheme in OpenAPI spec
nikochiko dc46d6c
Merge branch 'master' into bearer-openapi
nikochiko 1b5f46f
Add openapi params for fern bearer auth, hide healthcheck from fern
nikochiko 63deccf
Add x-fern-sdk-return-value for all status routes
nikochiko 53a8036
fern: ignore v2 sync APIs
nikochiko 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,27 @@ | ||
import threading | ||
|
||
from fastapi import Header | ||
from fastapi import Request | ||
from fastapi.exceptions import HTTPException | ||
from fastapi.openapi.models import HTTPBase as HTTPBaseModel, SecuritySchemeType | ||
from fastapi.security.base import SecurityBase | ||
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN | ||
|
||
from app_users.models import AppUser | ||
from auth.auth_backend import authlocal | ||
from daras_ai_v2 import db | ||
from daras_ai_v2.crypto import PBKDF2PasswordHasher | ||
|
||
auth_keyword = "Bearer" | ||
|
||
class AuthenticationError(HTTPException): | ||
status_code = HTTP_401_UNAUTHORIZED | ||
|
||
def __init__(self, msg: str): | ||
super().__init__(status_code=self.status_code, detail={"error": msg}) | ||
|
||
def api_auth_header( | ||
authorization: str = Header( | ||
alias="Authorization", | ||
description=f"{auth_keyword} $GOOEY_API_KEY", | ||
), | ||
) -> AppUser: | ||
if authlocal: | ||
return authlocal[0] | ||
return authenticate(authorization) | ||
|
||
class AuthorizationError(HTTPException): | ||
status_code = HTTP_403_FORBIDDEN | ||
|
||
def authenticate(auth_token: str) -> AppUser: | ||
auth = auth_token.split() | ||
if not auth or auth[0].lower() != auth_keyword.lower(): | ||
msg = "Invalid Authorization header." | ||
raise HTTPException(status_code=401, detail={"error": msg}) | ||
if len(auth) == 1: | ||
msg = "Invalid Authorization header. No credentials provided." | ||
raise HTTPException(status_code=401, detail={"error": msg}) | ||
elif len(auth) > 2: | ||
msg = "Invalid Authorization header. Token string should not contain spaces." | ||
raise HTTPException(status_code=401, detail={"error": msg}) | ||
return authenticate_credentials(auth[1]) | ||
def __init__(self, msg: str): | ||
super().__init__(status_code=self.status_code, detail={"error": msg}) | ||
|
||
|
||
def authenticate_credentials(token: str) -> AppUser: | ||
|
@@ -48,12 +36,7 @@ def authenticate_credentials(token: str) -> AppUser: | |
.get()[0] | ||
) | ||
except IndexError: | ||
raise HTTPException( | ||
status_code=403, | ||
detail={ | ||
"error": "Invalid API Key.", | ||
}, | ||
) | ||
raise AuthorizationError("Invalid API Key.") | ||
|
||
uid = doc.get("uid") | ||
user = AppUser.objects.get_or_create_from_uid(uid)[0] | ||
|
@@ -62,6 +45,50 @@ def authenticate_credentials(token: str) -> AppUser: | |
"Your Gooey.AI account has been disabled for violating our Terms of Service. " | ||
"Contact us at [email protected] if you think this is a mistake." | ||
) | ||
raise HTTPException(status_code=401, detail={"error": msg}) | ||
raise AuthenticationError(msg) | ||
|
||
return user | ||
|
||
|
||
class APIAuth(SecurityBase): | ||
""" | ||
### Usage: | ||
|
||
```python | ||
api_auth = APIAuth(scheme_name="Bearer", description="Bearer $GOOEY_API_KEY") | ||
|
||
@app.get("/api/users") | ||
def get_users(authenticated_user: AppUser = Depends(api_auth)): | ||
... | ||
``` | ||
""" | ||
|
||
def __init__(self, scheme_name: str, description: str): | ||
self.model = HTTPBaseModel( | ||
type=SecuritySchemeType.http, scheme=scheme_name, description=description | ||
) | ||
self.scheme_name = scheme_name | ||
self.description = description | ||
|
||
def __call__(self, request: Request) -> AppUser: | ||
if authlocal: # testing only! | ||
return authlocal[0] | ||
|
||
auth = request.headers.get("Authorization", "").split() | ||
if not auth or auth[0].lower() != self.scheme_name.lower(): | ||
raise AuthenticationError("Invalid Authorization header.") | ||
if len(auth) == 1: | ||
raise AuthenticationError( | ||
"Invalid Authorization header. No credentials provided." | ||
) | ||
elif len(auth) > 2: | ||
raise AuthenticationError( | ||
"Invalid Authorization header. Token string should not contain spaces." | ||
) | ||
return authenticate_credentials(auth[1]) | ||
|
||
|
||
auth_scheme = "Bearer" | ||
api_auth_header = APIAuth( | ||
scheme_name=auth_scheme, description=f"{auth_scheme} $GOOEY_API_KEY" | ||
) |
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
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.
I created a new class instead of using FastAPI's default
HTTPBearer
because it has terrible error messages and uses 403 for all auth problems.https://github.com/fastapi/fastapi/blob/0.85.0/fastapi/security/http.py#L113-L133
My changes are compatible with what we already do - nothing has changed behaviourally for the API.