lenapi 0.1.4.3__tar.gz → 0.1.4.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/PKG-INFO +31 -14
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/README.md +30 -13
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/__init__.py +1 -1
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/auth.py +105 -20
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/cli.py +5 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/PKG-INFO +31 -14
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/pyproject.toml +1 -1
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_security_patch.py +49 -2
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/LICENSE +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/admin.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/application.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/authentication.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/authorization.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/background.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/concurrency.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/database.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/dependencies.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/docs_guard.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/logging.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/middleware.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/model.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/models.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/mongodb.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/openapi.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/parameters.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/project.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/request.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/response.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/security.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/security_store.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/sentinels.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/service.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/throttling.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi/transaction.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/SOURCES.txt +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/dependency_links.txt +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/entry_points.txt +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/requires.txt +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi.egg-info/top_level.txt +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/lenapi_bootstrap.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/setup.cfg +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_admin_console.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_cli_settings_recovery.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_docs_guard.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_framework_features.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_media_upload.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_mongodb.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_platform_services.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_project_isolation.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_sentinels.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_throttle.py +0 -0
- {lenapi-0.1.4.3 → lenapi-0.1.4.4}/tests/test_user_model_extension.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lenapi
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.4
|
|
4
4
|
Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
|
|
5
5
|
Author: Maekandex Communication Limitation
|
|
6
6
|
Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
|
|
@@ -1471,6 +1471,8 @@ def oidc_profile(identity=Depends(provider_auth)):
|
|
|
1471
1471
|
```python
|
|
1472
1472
|
# settings.py — replace with the exact origin serving your frontend.
|
|
1473
1473
|
SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
|
|
1474
|
+
SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
|
|
1475
|
+
FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
|
|
1474
1476
|
|
|
1475
1477
|
# main.py
|
|
1476
1478
|
from lenapi import LENAPI
|
|
@@ -1479,7 +1481,7 @@ from lenapi.security import SocialAuth
|
|
|
1479
1481
|
auth = SocialAuth(
|
|
1480
1482
|
providers=["google", "github", "linkedin"],
|
|
1481
1483
|
auto_register=True,
|
|
1482
|
-
jwt_enabled=
|
|
1484
|
+
jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
|
|
1483
1485
|
)
|
|
1484
1486
|
|
|
1485
1487
|
app = LENAPI()
|
|
@@ -1492,23 +1494,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
|
|
|
1492
1494
|
2. The provider authenticates the person and redirects the browser to the registered callback URL.
|
|
1493
1495
|
3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
|
|
1494
1496
|
4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
|
|
1495
|
-
5.
|
|
1497
|
+
5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
|
|
1496
1498
|
|
|
1497
|
-
|
|
1499
|
+
The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
|
|
1498
1500
|
|
|
1499
|
-
|
|
1501
|
+
To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
|
|
1500
1502
|
|
|
1501
|
-
```
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1503
|
+
```python
|
|
1504
|
+
# Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
|
|
1505
|
+
from lenapi import JSONResponse, LENAPI, Request
|
|
1506
|
+
import settings
|
|
1507
|
+
|
|
1508
|
+
app = LENAPI()
|
|
1509
|
+
|
|
1510
|
+
@app.post("/auth/social/success")
|
|
1511
|
+
async def social_success(request: Request):
|
|
1512
|
+
data = await request.json()
|
|
1513
|
+
identity = data["identity"]
|
|
1514
|
+
user_id = data.get("user_id")
|
|
1515
|
+
|
|
1516
|
+
# Implement your own account rules and issue your own session/JWT here.
|
|
1517
|
+
user = await find_or_create_user(identity, user_id)
|
|
1518
|
+
session_id = await create_session(user)
|
|
1519
|
+
|
|
1520
|
+
response = JSONResponse({"accepted": True})
|
|
1521
|
+
response.set_cookie(
|
|
1522
|
+
"session_id", session_id, max_age=3600, path="/",
|
|
1523
|
+
httponly=True, secure=True, samesite="lax",
|
|
1524
|
+
)
|
|
1525
|
+
return response
|
|
1509
1526
|
```
|
|
1510
1527
|
|
|
1511
|
-
The
|
|
1528
|
+
The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
|
|
1512
1529
|
|
|
1513
1530
|
`allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
|
|
1514
1531
|
|
|
@@ -1419,6 +1419,8 @@ def oidc_profile(identity=Depends(provider_auth)):
|
|
|
1419
1419
|
```python
|
|
1420
1420
|
# settings.py — replace with the exact origin serving your frontend.
|
|
1421
1421
|
SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
|
|
1422
|
+
SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
|
|
1423
|
+
FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
|
|
1422
1424
|
|
|
1423
1425
|
# main.py
|
|
1424
1426
|
from lenapi import LENAPI
|
|
@@ -1427,7 +1429,7 @@ from lenapi.security import SocialAuth
|
|
|
1427
1429
|
auth = SocialAuth(
|
|
1428
1430
|
providers=["google", "github", "linkedin"],
|
|
1429
1431
|
auto_register=True,
|
|
1430
|
-
jwt_enabled=
|
|
1432
|
+
jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
|
|
1431
1433
|
)
|
|
1432
1434
|
|
|
1433
1435
|
app = LENAPI()
|
|
@@ -1440,23 +1442,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
|
|
|
1440
1442
|
2. The provider authenticates the person and redirects the browser to the registered callback URL.
|
|
1441
1443
|
3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
|
|
1442
1444
|
4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
|
|
1443
|
-
5.
|
|
1445
|
+
5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
|
|
1444
1446
|
|
|
1445
|
-
|
|
1447
|
+
The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
|
|
1446
1448
|
|
|
1447
|
-
|
|
1449
|
+
To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
|
|
1448
1450
|
|
|
1449
|
-
```
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1451
|
+
```python
|
|
1452
|
+
# Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
|
|
1453
|
+
from lenapi import JSONResponse, LENAPI, Request
|
|
1454
|
+
import settings
|
|
1455
|
+
|
|
1456
|
+
app = LENAPI()
|
|
1457
|
+
|
|
1458
|
+
@app.post("/auth/social/success")
|
|
1459
|
+
async def social_success(request: Request):
|
|
1460
|
+
data = await request.json()
|
|
1461
|
+
identity = data["identity"]
|
|
1462
|
+
user_id = data.get("user_id")
|
|
1463
|
+
|
|
1464
|
+
# Implement your own account rules and issue your own session/JWT here.
|
|
1465
|
+
user = await find_or_create_user(identity, user_id)
|
|
1466
|
+
session_id = await create_session(user)
|
|
1467
|
+
|
|
1468
|
+
response = JSONResponse({"accepted": True})
|
|
1469
|
+
response.set_cookie(
|
|
1470
|
+
"session_id", session_id, max_age=3600, path="/",
|
|
1471
|
+
httponly=True, secure=True, samesite="lax",
|
|
1472
|
+
)
|
|
1473
|
+
return response
|
|
1457
1474
|
```
|
|
1458
1475
|
|
|
1459
|
-
The
|
|
1476
|
+
The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
|
|
1460
1477
|
|
|
1461
1478
|
`allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
|
|
1462
1479
|
|
|
@@ -11,7 +11,6 @@ from urllib.parse import urlencode, urlsplit
|
|
|
11
11
|
from sqlalchemy import insert, select
|
|
12
12
|
from sqlalchemy.exc import IntegrityError
|
|
13
13
|
|
|
14
|
-
from .authentication import jwt_auth
|
|
15
14
|
from .concurrency import call_sync_or_async
|
|
16
15
|
from .models import SOCIAL_ACCOUNT_TABLE, User, _session
|
|
17
16
|
from .request import get_current_request
|
|
@@ -43,6 +42,8 @@ class SocialAuth:
|
|
|
43
42
|
settings=None,
|
|
44
43
|
user_model=None,
|
|
45
44
|
allowed_origins=None,
|
|
45
|
+
success_callback: str | None = None,
|
|
46
|
+
frontend_redirect_uri: str | None = None,
|
|
46
47
|
) -> None:
|
|
47
48
|
if isinstance(providers, str):
|
|
48
49
|
raise TypeError("providers must be a list or tuple of provider names")
|
|
@@ -70,11 +71,62 @@ class SocialAuth:
|
|
|
70
71
|
self.auto_register = bool(auto_register)
|
|
71
72
|
self.jwt_enabled = bool(jwt_enabled)
|
|
72
73
|
self.settings = settings or self._load_settings()
|
|
74
|
+
if success_callback is None:
|
|
75
|
+
success_callback = getattr(self.settings, "SOCIAL_AUTH_SUCCESS_CALLBACK", "") or None
|
|
76
|
+
self.success_callback = self._validate_success_callback(success_callback)
|
|
77
|
+
if frontend_redirect_uri is None:
|
|
78
|
+
frontend_redirect_uri = getattr(self.settings, "FRONTEND_REDIRECT_URI", "") or None
|
|
79
|
+
self.frontend_redirect_uri = (
|
|
80
|
+
self._validate_success_redirect(frontend_redirect_uri)
|
|
81
|
+
if frontend_redirect_uri
|
|
82
|
+
else None
|
|
83
|
+
)
|
|
73
84
|
if allowed_origins is None:
|
|
74
85
|
allowed_origins = getattr(self.settings, "SOCIAL_AUTH_ALLOWED_ORIGINS", ())
|
|
75
86
|
self.allowed_origins = self._normalize_origins(allowed_origins)
|
|
76
87
|
self.user_model = user_model or self._load_user_model()
|
|
77
|
-
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
def _validate_success_callback(url: str | None) -> str | None:
|
|
91
|
+
if url is None or url == "":
|
|
92
|
+
return None
|
|
93
|
+
if not isinstance(url, str):
|
|
94
|
+
raise TypeError("SOCIAL_AUTH_SUCCESS_CALLBACK must be a URL string")
|
|
95
|
+
parsed = urlsplit(url.strip())
|
|
96
|
+
if (
|
|
97
|
+
parsed.scheme.lower() not in {"https", "http"}
|
|
98
|
+
or not parsed.hostname
|
|
99
|
+
or parsed.username is not None
|
|
100
|
+
or parsed.password is not None
|
|
101
|
+
or parsed.query
|
|
102
|
+
or parsed.fragment
|
|
103
|
+
):
|
|
104
|
+
raise ValueError("SOCIAL_AUTH_SUCCESS_CALLBACK must be a valid HTTPS URL")
|
|
105
|
+
if parsed.scheme.lower() != "https" and parsed.hostname.lower() not in {
|
|
106
|
+
"localhost", "127.0.0.1", "::1"
|
|
107
|
+
}:
|
|
108
|
+
raise ValueError("SOCIAL_AUTH_SUCCESS_CALLBACK must use HTTPS")
|
|
109
|
+
return url.strip()
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def _validate_success_redirect(url: str) -> str:
|
|
113
|
+
if not isinstance(url, str):
|
|
114
|
+
raise ValueError("Social login success callback did not provide a redirect URL")
|
|
115
|
+
parsed = urlsplit(url.strip())
|
|
116
|
+
if (
|
|
117
|
+
parsed.scheme.lower() not in {"https", "http"}
|
|
118
|
+
or not parsed.hostname
|
|
119
|
+
or parsed.username is not None
|
|
120
|
+
or parsed.password is not None
|
|
121
|
+
or parsed.query
|
|
122
|
+
or parsed.fragment
|
|
123
|
+
):
|
|
124
|
+
raise ValueError("Social login success callback returned an invalid redirect URL")
|
|
125
|
+
if parsed.scheme.lower() != "https" and parsed.hostname.lower() not in {
|
|
126
|
+
"localhost", "127.0.0.1", "::1"
|
|
127
|
+
}:
|
|
128
|
+
raise ValueError("Social login success redirect must use HTTPS")
|
|
129
|
+
return url.strip()
|
|
78
130
|
|
|
79
131
|
@staticmethod
|
|
80
132
|
def _normalize_origin(origin: str) -> str:
|
|
@@ -265,28 +317,61 @@ class SocialAuth:
|
|
|
265
317
|
message = f"{provider} authentication failed"
|
|
266
318
|
return self._callback_error(provider, state_cookie, verifier_cookie, message, status)
|
|
267
319
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
response = JSONResponse(result)
|
|
320
|
+
if not self.success_callback:
|
|
321
|
+
return self._callback_error(
|
|
322
|
+
provider, state_cookie, verifier_cookie,
|
|
323
|
+
"Social login success callback is not configured", 503,
|
|
324
|
+
)
|
|
325
|
+
try:
|
|
326
|
+
redirect_url, cookies = await self._deliver_success(
|
|
327
|
+
provider, identity, user_id
|
|
328
|
+
)
|
|
329
|
+
except Exception:
|
|
330
|
+
response = self._callback_error(
|
|
331
|
+
provider, state_cookie, verifier_cookie,
|
|
332
|
+
"Social login could not be completed by the application", 502,
|
|
333
|
+
)
|
|
334
|
+
return response
|
|
335
|
+
response = Response(status_code=303, headers={"location": redirect_url})
|
|
336
|
+
response._cookies.extend(cookies)
|
|
286
337
|
self._clear_cookies(response, state_cookie, verifier_cookie)
|
|
287
338
|
return response
|
|
288
339
|
callback.__name__ = f"{provider}_callback"
|
|
289
340
|
|
|
341
|
+
async def _deliver_success(self, provider: str, identity: dict, user_id) -> tuple[str, list[str]]:
|
|
342
|
+
"""Send verified identity to the developer backend and prepare a clean redirect."""
|
|
343
|
+
import json
|
|
344
|
+
import httpx
|
|
345
|
+
|
|
346
|
+
payload = {"provider": provider, "identity": identity}
|
|
347
|
+
if user_id is not None:
|
|
348
|
+
payload["user_id"] = str(user_id)
|
|
349
|
+
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
350
|
+
headers = {"Content-Type": "application/json"}
|
|
351
|
+
async with httpx.AsyncClient(timeout=10.0, follow_redirects=False) as client:
|
|
352
|
+
response = await client.post(self.success_callback, content=body, headers=headers)
|
|
353
|
+
if not response.is_success:
|
|
354
|
+
raise ValueError("Social login success callback rejected the login")
|
|
355
|
+
result = {}
|
|
356
|
+
if response.content:
|
|
357
|
+
try:
|
|
358
|
+
parsed_result = response.json()
|
|
359
|
+
except (ValueError, json.JSONDecodeError):
|
|
360
|
+
parsed_result = {}
|
|
361
|
+
if isinstance(parsed_result, dict):
|
|
362
|
+
result = parsed_result
|
|
363
|
+
redirect_url = result.get("redirect_url") or self.frontend_redirect_uri
|
|
364
|
+
if not redirect_url:
|
|
365
|
+
raise ValueError(
|
|
366
|
+
"Social login needs a frontend redirect URL in the webhook response "
|
|
367
|
+
"or FRONTEND_REDIRECT_URI setting"
|
|
368
|
+
)
|
|
369
|
+
redirect_url = self._validate_success_redirect(redirect_url)
|
|
370
|
+
cookies = response.headers.get_list("set-cookie")
|
|
371
|
+
if any("\r" in cookie or "\n" in cookie for cookie in cookies):
|
|
372
|
+
raise ValueError("Social login success callback returned invalid cookies")
|
|
373
|
+
return redirect_url, cookies
|
|
374
|
+
|
|
290
375
|
def _authorization_url(self, provider, client_id, redirect_uri, state, challenge):
|
|
291
376
|
if provider == "google":
|
|
292
377
|
endpoint = "https://accounts.google.com/o/oauth2/v2/auth"
|
|
@@ -101,6 +101,11 @@ LINKEDIN_REDIRECT_URI = ""
|
|
|
101
101
|
LINKEDIN_COOKIE_SECURE = urlparse(LINKEDIN_REDIRECT_URI).scheme == "https"
|
|
102
102
|
# Exact browser origins allowed to start social login; configure your frontend origin.
|
|
103
103
|
SOCIAL_AUTH_ALLOWED_ORIGINS = []
|
|
104
|
+
# Optional server-to-server endpoint for application-owned social login/session handling.
|
|
105
|
+
# Use HTTPS when enabling it.
|
|
106
|
+
SOCIAL_AUTH_SUCCESS_CALLBACK = ""
|
|
107
|
+
# Browser destination after the social-auth webhook succeeds.
|
|
108
|
+
FRONTEND_REDIRECT_URI = ""
|
|
104
109
|
# Keep this generated key private. Rotate it to invalidate existing tokens.
|
|
105
110
|
SECRET_KEY = "__LENAPI_GENERATED_SECRET_KEY__"
|
|
106
111
|
TOKEN = {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lenapi
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.4
|
|
4
4
|
Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
|
|
5
5
|
Author: Maekandex Communication Limitation
|
|
6
6
|
Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
|
|
@@ -1471,6 +1471,8 @@ def oidc_profile(identity=Depends(provider_auth)):
|
|
|
1471
1471
|
```python
|
|
1472
1472
|
# settings.py — replace with the exact origin serving your frontend.
|
|
1473
1473
|
SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
|
|
1474
|
+
SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
|
|
1475
|
+
FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
|
|
1474
1476
|
|
|
1475
1477
|
# main.py
|
|
1476
1478
|
from lenapi import LENAPI
|
|
@@ -1479,7 +1481,7 @@ from lenapi.security import SocialAuth
|
|
|
1479
1481
|
auth = SocialAuth(
|
|
1480
1482
|
providers=["google", "github", "linkedin"],
|
|
1481
1483
|
auto_register=True,
|
|
1482
|
-
jwt_enabled=
|
|
1484
|
+
jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
|
|
1483
1485
|
)
|
|
1484
1486
|
|
|
1485
1487
|
app = LENAPI()
|
|
@@ -1492,23 +1494,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
|
|
|
1492
1494
|
2. The provider authenticates the person and redirects the browser to the registered callback URL.
|
|
1493
1495
|
3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
|
|
1494
1496
|
4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
|
|
1495
|
-
5.
|
|
1497
|
+
5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
|
|
1496
1498
|
|
|
1497
|
-
|
|
1499
|
+
The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
|
|
1498
1500
|
|
|
1499
|
-
|
|
1501
|
+
To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
|
|
1500
1502
|
|
|
1501
|
-
```
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1503
|
+
```python
|
|
1504
|
+
# Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
|
|
1505
|
+
from lenapi import JSONResponse, LENAPI, Request
|
|
1506
|
+
import settings
|
|
1507
|
+
|
|
1508
|
+
app = LENAPI()
|
|
1509
|
+
|
|
1510
|
+
@app.post("/auth/social/success")
|
|
1511
|
+
async def social_success(request: Request):
|
|
1512
|
+
data = await request.json()
|
|
1513
|
+
identity = data["identity"]
|
|
1514
|
+
user_id = data.get("user_id")
|
|
1515
|
+
|
|
1516
|
+
# Implement your own account rules and issue your own session/JWT here.
|
|
1517
|
+
user = await find_or_create_user(identity, user_id)
|
|
1518
|
+
session_id = await create_session(user)
|
|
1519
|
+
|
|
1520
|
+
response = JSONResponse({"accepted": True})
|
|
1521
|
+
response.set_cookie(
|
|
1522
|
+
"session_id", session_id, max_age=3600, path="/",
|
|
1523
|
+
httponly=True, secure=True, samesite="lax",
|
|
1524
|
+
)
|
|
1525
|
+
return response
|
|
1509
1526
|
```
|
|
1510
1527
|
|
|
1511
|
-
The
|
|
1528
|
+
The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
|
|
1512
1529
|
|
|
1513
1530
|
`allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
|
|
1514
1531
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "lenapi"
|
|
7
|
-
version = "0.1.4.
|
|
7
|
+
version = "0.1.4.4"
|
|
8
8
|
description = "A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation."
|
|
9
9
|
authors = [
|
|
10
10
|
{name = "Ifeanyi M. Onovo", email = "ifeanyi@maekandex.com.ng"},
|
|
@@ -27,7 +27,9 @@ from lenapi.middleware import DocsAuthMiddleware
|
|
|
27
27
|
from lenapi.models import SECURITY_STORE_TABLE
|
|
28
28
|
|
|
29
29
|
|
|
30
|
-
async def _http_request(
|
|
30
|
+
async def _http_request(
|
|
31
|
+
app, path, *, method="GET", payload=None, headers=(), query_string=b"", return_headers=False
|
|
32
|
+
):
|
|
31
33
|
body = b"" if payload is None else json.dumps(payload).encode()
|
|
32
34
|
headers = list(headers)
|
|
33
35
|
if payload is not None:
|
|
@@ -53,7 +55,8 @@ async def _http_request(app, path, *, method="GET", payload=None, headers=(), qu
|
|
|
53
55
|
}, receive, send)
|
|
54
56
|
start = next(item for item in messages if item["type"] == "http.response.start")
|
|
55
57
|
response_body = next(item for item in messages if item["type"] == "http.response.body")["body"]
|
|
56
|
-
|
|
58
|
+
result = (start["status"], json.loads(response_body or b"null"))
|
|
59
|
+
return (*result, start["headers"]) if return_headers else result
|
|
57
60
|
|
|
58
61
|
|
|
59
62
|
def test_authentication_public_api_is_available_from_security_module():
|
|
@@ -161,6 +164,50 @@ def test_social_auth_callback_requires_state_even_when_provider_origin_is_presen
|
|
|
161
164
|
assert body["error"] == "Invalid or expired OAuth state"
|
|
162
165
|
|
|
163
166
|
|
|
167
|
+
def test_social_auth_success_callback_redirects_without_exposing_identity():
|
|
168
|
+
settings = SimpleNamespace(
|
|
169
|
+
GOOGLE_CLIENT_ID="test-client",
|
|
170
|
+
GOOGLE_CLIENT_SECRET="test-secret",
|
|
171
|
+
GOOGLE_REDIRECT_URI="https://api.example/auth/google/callback",
|
|
172
|
+
GOOGLE_COOKIE_SECURE=True,
|
|
173
|
+
SOCIAL_AUTH_SUCCESS_CALLBACK="https://backend.example/auth/social/success",
|
|
174
|
+
)
|
|
175
|
+
app = Application(database=Database("sqlite://"), security_storage="memory")
|
|
176
|
+
auth = SocialAuth(["google"], settings=settings)
|
|
177
|
+
delivered = {}
|
|
178
|
+
|
|
179
|
+
async def fetch_identity(provider, code, verifier):
|
|
180
|
+
return {"sub": "provider-user-1", "email": "ada@example.com", "email_verified": True}
|
|
181
|
+
|
|
182
|
+
async def deliver_success(provider, identity, user_id):
|
|
183
|
+
delivered.update(provider=provider, identity=identity, user_id=user_id)
|
|
184
|
+
return "https://frontend.example/login/success", ["session_id=secret; Path=/; HttpOnly; Secure"]
|
|
185
|
+
|
|
186
|
+
auth._fetch_identity = fetch_identity
|
|
187
|
+
auth._deliver_success = deliver_success
|
|
188
|
+
app.include_router(auth.router(), prefix="/auth")
|
|
189
|
+
status, body, headers = asyncio.run(_http_request(
|
|
190
|
+
app,
|
|
191
|
+
"/auth/google/callback",
|
|
192
|
+
query_string=b"state=valid-state&code=provider-code",
|
|
193
|
+
headers=[(
|
|
194
|
+
b"cookie",
|
|
195
|
+
b"lenapi_social_google_state=valid-state; lenapi_social_google_verifier=valid-verifier",
|
|
196
|
+
)],
|
|
197
|
+
return_headers=True,
|
|
198
|
+
))
|
|
199
|
+
|
|
200
|
+
response_headers = dict(headers)
|
|
201
|
+
set_cookies = [value for key, value in headers if key == b"set-cookie"]
|
|
202
|
+
assert status == 303
|
|
203
|
+
assert body is None
|
|
204
|
+
assert response_headers[b"location"] == b"https://frontend.example/login/success"
|
|
205
|
+
assert b"session_id=secret; Path=/; HttpOnly; Secure" in set_cookies
|
|
206
|
+
assert "provider-user-1" not in repr(body)
|
|
207
|
+
assert delivered["provider"] == "google"
|
|
208
|
+
assert delivered["identity"]["sub"] == "provider-user-1"
|
|
209
|
+
|
|
210
|
+
|
|
164
211
|
def test_social_auth_origin_configuration_is_normalized_and_validated():
|
|
165
212
|
auth = SocialAuth(
|
|
166
213
|
["google"],
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|