diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index b4256b2a90..981394d7cf 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -86,3 +86,5 @@ title: Webhooks server - local: package_reference/serialization title: Serialization + - local: package_reference/oauth + title: OAuth diff --git a/docs/source/en/package_reference/oauth.md b/docs/source/en/package_reference/oauth.md new file mode 100644 index 0000000000..5611ce7948 --- /dev/null +++ b/docs/source/en/package_reference/oauth.md @@ -0,0 +1,22 @@ +## TO BE COMPLETED + +### attach_huggingface_oauth + +[[autodoc]] attach_huggingface_oauth + +### parse_huggingface_oauth + +[[autodoc]] parse_huggingface_oauth + +### OAuthOrgInfo + +[[autodoc]] OAuthOrgInfo + +### OAuthUserInfo + +[[autodoc]] OAuthUserInfo + +### OAuthInfo + +[[autodoc]] OAuthInfo + diff --git a/src/huggingface_hub/_oauth.py b/src/huggingface_hub/_oauth.py index 4911e53743..5c47451960 100644 --- a/src/huggingface_hub/_oauth.py +++ b/src/huggingface_hub/_oauth.py @@ -126,6 +126,35 @@ class OAuthInfo: @experimental def attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"): + """ + Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face. + + How to use: + - Call this method on your FastAPI app to add the OAuth endpoints. + - Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info. + - If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned. + - In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out. + + Example: + ```py + from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth + + # Create a FastAPI app + app = FastAPI() + + # Add OAuth endpoints to the FastAPI app + attach_huggingface_oauth(app) + + # Add a route that greets the user if they are logged in + @app.get("/") + def greet_json(request: Request): + # Retrieve the OAuth info from the request + oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass + if oauth_info is None: + return {"msg": "Not logged in!"} + return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"} + ``` + """ # TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority) # Add SessionMiddleware to the FastAPI app to store the OAuth info in the session. @@ -170,6 +199,8 @@ def parse_huggingface_oauth(request: "fastapi.Request") -> Optional[OAuthInfo]: Missing fields are set to `None` without a warning. Return `None`, if the user is not logged in (no info in session cookie). + + See [`attach_huggingface_oauth`] for an example on how to use this method. """ if "oauth_info" not in request.session: logger.debug("No OAuth info in session.")