Metadata-Version: 2.4
Name: hawkapi-sso
Version: 0.1.0
Summary: Social SSO for HawkAPI — Google, GitHub, Microsoft, Discord, Facebook, LinkedIn
Project-URL: Homepage, https://pypi.org/project/hawkapi-sso/
Project-URL: Repository, https://github.com/ashimov/hawkapi-sso
Project-URL: Issues, https://github.com/ashimov/hawkapi-sso/issues
Author-email: HawkAPI Contributors <hawkapi@users.noreply.github.com>
License: MIT License
        
        Copyright (c) 2026 HawkAPI Contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: discord,facebook,github,google,hawkapi,linkedin,microsoft,oauth2,sso
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: hawkapi>=0.1.7
Requires-Dist: httpx>=0.27
Provides-Extra: dev
Requires-Dist: pyright>=1.1; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Description-Content-Type: text/markdown

# hawkapi-sso

Social SSO for [HawkAPI](https://github.com/ashimov/HawkAPI). One plugin, six providers:

- **Google** (OAuth2 + OIDC, PKCE)
- **GitHub** (OAuth2)
- **Microsoft / Entra** (OAuth2 + OIDC, PKCE)
- **Discord** (OAuth2)
- **Facebook** (OAuth2 + Graph API)
- **LinkedIn** (OAuth2 + OIDC, PKCE)

Pure-Python, async, `httpx`-based. CSRF-protected via HMAC-signed state cookie. PKCE applied automatically where the provider supports it.

## Install

```bash
pip install hawkapi-sso
```

## Quickstart

```python
from hawkapi import HawkAPI
from hawkapi_sso import GoogleProvider, GitHubProvider, init_sso

app = HawkAPI()
init_sso(
    app,
    providers={
        "google": GoogleProvider(client_id="...", client_secret="..."),
        "github": GitHubProvider(client_id="...", client_secret="..."),
    },
    state_secret="...",            # ≥16 chars; stable across restarts
)


# These routes are mounted automatically:
# GET /auth/sso/login/{provider}     → redirects to the provider's authorize URL
# GET /auth/sso/callback/{provider}  → handles the OAuth callback, sets `request.scope["sso_user"]`,
#                                       then redirects to `?next=` (or success_redirect).
```

## Reading the authenticated user

The callback handler stashes a normalized `OAuthUser` on the request scope. Pick it up in your downstream middleware / handlers:

```python
@app.middleware("http")
async def persist_session(request, call_next):
    response = await call_next(request)
    user = request.scope.get("sso_user")
    if user is not None:
        # persist user, set session cookie, etc.
        ...
    return response
```

You can also wire a callback hook:

```python
async def on_login(request, user, token):
    # persist, mint JWT, etc.
    ...

cfg = init_sso(app, providers={...}, state_secret="...")
cfg.on_success = on_login
```

## OAuthUser

```python
@dataclass
class OAuthUser:
    provider: str         # "google" / "github" / ...
    sub: str              # provider-issued user id (always string)
    email: str            # "" if not granted
    email_verified: bool  # only True when the provider explicitly signals it
    name: str
    picture: str
    raw: dict             # the parsed userinfo response, for advanced use
```

## Security

- **State cookie** — `HttpOnly`, `Secure` (configurable), `SameSite=Lax`, `Max-Age=600` by default. Signed with HMAC-SHA256 over the state secret.
- **CSRF** — the callback rejects requests whose `state` query parameter does not match the state cookie byte-for-byte.
- **PKCE** — automatically generated and verified for Google, Microsoft, LinkedIn.
- **Open-redirect guard** — `?next=` parameter must be a path (`/...`); anything else falls back to `success_redirect`.
- **`client_secret`** — never logged, never returned in any URL or response.
- **Email verification** — `email_verified=True` is set only when the provider explicitly signals it (GitHub uses the `/user/emails` endpoint). Facebook does not, so it defaults to `False`.

## Configuration

```python
init_sso(
    app,
    providers={...},
    state_secret="...",
    cookie_name="hawkapi_sso_state",
    cookie_secure=True,
    cookie_samesite="lax",
    cookie_max_age=600,
    login_path_prefix="/auth/sso",
    success_redirect="/",
    failure_redirect="/login?error=sso",
)
```

## Development

```bash
git clone https://github.com/ashimov/hawkapi-sso.git
cd hawkapi-sso
uv sync --extra dev
uv run pytest -q
uv run ruff check . && uv run ruff format --check .
uv run pyright src/
```

## License

MIT.
