lenapi 0.1.4.3__tar.gz → 0.1.4.5__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.
Files changed (54) hide show
  1. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/PKG-INFO +35 -14
  2. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/README.md +34 -13
  3. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/__init__.py +1 -1
  4. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/application.py +5 -1
  5. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/auth.py +105 -20
  6. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/background.py +62 -3
  7. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/cli.py +10 -0
  8. lenapi-0.1.4.5/lenapi/migration_render.py +25 -0
  9. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/models.py +14 -2
  10. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/PKG-INFO +35 -14
  11. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/SOURCES.txt +2 -0
  12. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi_bootstrap.py +6 -1
  13. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/pyproject.toml +1 -1
  14. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_framework_features.py +26 -0
  15. lenapi-0.1.4.5/tests/test_migration_render.py +48 -0
  16. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_project_isolation.py +44 -0
  17. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_security_patch.py +49 -2
  18. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/LICENSE +0 -0
  19. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/admin.py +0 -0
  20. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/authentication.py +0 -0
  21. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/authorization.py +0 -0
  22. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/concurrency.py +0 -0
  23. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/database.py +0 -0
  24. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/dependencies.py +0 -0
  25. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/docs_guard.py +0 -0
  26. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/logging.py +0 -0
  27. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/middleware.py +0 -0
  28. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/model.py +0 -0
  29. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/mongodb.py +0 -0
  30. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/openapi.py +0 -0
  31. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/parameters.py +0 -0
  32. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/project.py +0 -0
  33. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/request.py +0 -0
  34. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/response.py +0 -0
  35. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/security.py +0 -0
  36. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/security_store.py +0 -0
  37. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/sentinels.py +0 -0
  38. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/service.py +0 -0
  39. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/throttling.py +0 -0
  40. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi/transaction.py +0 -0
  41. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/dependency_links.txt +0 -0
  42. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/entry_points.txt +0 -0
  43. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/requires.txt +0 -0
  44. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/lenapi.egg-info/top_level.txt +0 -0
  45. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/setup.cfg +0 -0
  46. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_admin_console.py +0 -0
  47. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_cli_settings_recovery.py +0 -0
  48. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_docs_guard.py +0 -0
  49. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_media_upload.py +0 -0
  50. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_mongodb.py +0 -0
  51. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_platform_services.py +0 -0
  52. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_sentinels.py +0 -0
  53. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/tests/test_throttle.py +0 -0
  54. {lenapi-0.1.4.3 → lenapi-0.1.4.5}/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
3
+ Version: 0.1.4.5
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>
@@ -531,6 +531,8 @@ python lenora.py run
531
531
 
532
532
  Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
533
533
 
534
+ Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
535
+
534
536
  If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
535
537
 
536
538
  Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
@@ -1471,6 +1473,8 @@ def oidc_profile(identity=Depends(provider_auth)):
1471
1473
  ```python
1472
1474
  # settings.py — replace with the exact origin serving your frontend.
1473
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1476
+ SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1477
+ FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1474
1478
 
1475
1479
  # main.py
1476
1480
  from lenapi import LENAPI
@@ -1479,7 +1483,7 @@ from lenapi.security import SocialAuth
1479
1483
  auth = SocialAuth(
1480
1484
  providers=["google", "github", "linkedin"],
1481
1485
  auto_register=True,
1482
- jwt_enabled=True,
1486
+ jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
1483
1487
  )
1484
1488
 
1485
1489
  app = LENAPI()
@@ -1492,23 +1496,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1492
1496
  2. The provider authenticates the person and redirects the browser to the registered callback URL.
1493
1497
  3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
1494
1498
  4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
1495
- 5. With `jwt_enabled=True`, LenAPI issues **one LenAPI JWT access token** for use on protected application routes.
1499
+ 5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
1496
1500
 
1497
- `jwt_enabled` controls only that final LenAPI credential. SocialAuth currently issues a JWT access token; it does not issue an API key, session cookie, opaque bearer token, or refresh token. The provider's OAuth access token is used internally during the callback and is not returned to the client. With `jwt_enabled=False`, the callback response contains the provider `identity` and includes `user_id` when a local user was resolved, but no LenAPI token. For sessions, API keys, or opaque tokens, implement the desired credential issuance after the provider callback using the matching LenAPI auth dependency/store, or build a custom callback flow. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1501
+ 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
1502
 
1499
- For example, with both flags enabled, the callback response includes fields in this shape (identity claims vary by provider):
1503
+ 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
1504
 
1501
- ```json
1502
- {
1503
- "identity": {"sub": "provider-subject", "email": "ada@example.com"},
1504
- "user_id": 42,
1505
- "access_token": "<LenAPI JWT>",
1506
- "token_type": "bearer",
1507
- "expires_in": 3600
1508
- }
1505
+ ```python
1506
+ # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1507
+ from lenapi import JSONResponse, LENAPI, Request
1508
+ import settings
1509
+
1510
+ app = LENAPI()
1511
+
1512
+ @app.post("/auth/social/success")
1513
+ async def social_success(request: Request):
1514
+ data = await request.json()
1515
+ identity = data["identity"]
1516
+ user_id = data.get("user_id")
1517
+
1518
+ # Implement your own account rules and issue your own session/JWT here.
1519
+ user = await find_or_create_user(identity, user_id)
1520
+ session_id = await create_session(user)
1521
+
1522
+ response = JSONResponse({"accepted": True})
1523
+ response.set_cookie(
1524
+ "session_id", session_id, max_age=3600, path="/",
1525
+ httponly=True, secure=True, samesite="lax",
1526
+ )
1527
+ return response
1509
1528
  ```
1510
1529
 
1511
- The client then sends `Authorization: Bearer <access_token>` to routes protected with LenAPI JWT authentication. Store and transmit the token securely; do not use the provider token in place of the LenAPI token.
1530
+ 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
1531
 
1513
1532
  `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
1533
 
@@ -1615,6 +1634,8 @@ class User(BaseUser):
1615
1634
 
1616
1635
  Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
1617
1636
 
1637
+ LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
1638
+
1618
1639
  For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
1619
1640
 
1620
1641
  Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
@@ -479,6 +479,8 @@ python lenora.py run
479
479
 
480
480
  Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
481
481
 
482
+ Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
483
+
482
484
  If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
483
485
 
484
486
  Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
@@ -1419,6 +1421,8 @@ def oidc_profile(identity=Depends(provider_auth)):
1419
1421
  ```python
1420
1422
  # settings.py — replace with the exact origin serving your frontend.
1421
1423
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1424
+ SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1425
+ FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1422
1426
 
1423
1427
  # main.py
1424
1428
  from lenapi import LENAPI
@@ -1427,7 +1431,7 @@ from lenapi.security import SocialAuth
1427
1431
  auth = SocialAuth(
1428
1432
  providers=["google", "github", "linkedin"],
1429
1433
  auto_register=True,
1430
- jwt_enabled=True,
1434
+ jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
1431
1435
  )
1432
1436
 
1433
1437
  app = LENAPI()
@@ -1440,23 +1444,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1440
1444
  2. The provider authenticates the person and redirects the browser to the registered callback URL.
1441
1445
  3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
1442
1446
  4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
1443
- 5. With `jwt_enabled=True`, LenAPI issues **one LenAPI JWT access token** for use on protected application routes.
1447
+ 5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
1444
1448
 
1445
- `jwt_enabled` controls only that final LenAPI credential. SocialAuth currently issues a JWT access token; it does not issue an API key, session cookie, opaque bearer token, or refresh token. The provider's OAuth access token is used internally during the callback and is not returned to the client. With `jwt_enabled=False`, the callback response contains the provider `identity` and includes `user_id` when a local user was resolved, but no LenAPI token. For sessions, API keys, or opaque tokens, implement the desired credential issuance after the provider callback using the matching LenAPI auth dependency/store, or build a custom callback flow. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1449
+ 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
1450
 
1447
- For example, with both flags enabled, the callback response includes fields in this shape (identity claims vary by provider):
1451
+ 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
1452
 
1449
- ```json
1450
- {
1451
- "identity": {"sub": "provider-subject", "email": "ada@example.com"},
1452
- "user_id": 42,
1453
- "access_token": "<LenAPI JWT>",
1454
- "token_type": "bearer",
1455
- "expires_in": 3600
1456
- }
1453
+ ```python
1454
+ # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1455
+ from lenapi import JSONResponse, LENAPI, Request
1456
+ import settings
1457
+
1458
+ app = LENAPI()
1459
+
1460
+ @app.post("/auth/social/success")
1461
+ async def social_success(request: Request):
1462
+ data = await request.json()
1463
+ identity = data["identity"]
1464
+ user_id = data.get("user_id")
1465
+
1466
+ # Implement your own account rules and issue your own session/JWT here.
1467
+ user = await find_or_create_user(identity, user_id)
1468
+ session_id = await create_session(user)
1469
+
1470
+ response = JSONResponse({"accepted": True})
1471
+ response.set_cookie(
1472
+ "session_id", session_id, max_age=3600, path="/",
1473
+ httponly=True, secure=True, samesite="lax",
1474
+ )
1475
+ return response
1457
1476
  ```
1458
1477
 
1459
- The client then sends `Authorization: Bearer <access_token>` to routes protected with LenAPI JWT authentication. Store and transmit the token securely; do not use the provider token in place of the LenAPI token.
1478
+ 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
1479
 
1461
1480
  `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
1481
 
@@ -1563,6 +1582,8 @@ class User(BaseUser):
1563
1582
 
1564
1583
  Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
1565
1584
 
1585
+ LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
1586
+
1566
1587
  For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
1567
1588
 
1568
1589
  Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
@@ -8,7 +8,7 @@ if sys.version_info < (3, 11):
8
8
  "on 2026-10-01 and is no longer supported."
9
9
  )
10
10
 
11
- __version__ = "0.1.4.3"
11
+ __version__ = "0.1.4.5"
12
12
 
13
13
  from .application import Application, LENAPI, Router
14
14
  from .background import BackgroundQueue, BackgroundTasks
@@ -672,7 +672,11 @@ class Application(Router):
672
672
  media_root=self.media_root,
673
673
  private_media_root=self.private_media_root,
674
674
  )
675
- request.background_tasks = BackgroundTasks()
675
+ request.background_tasks = BackgroundTasks(
676
+ session_factory=self.session_factory,
677
+ async_session_factory=self.async_session_factory,
678
+ database_backend=self.database_type,
679
+ )
676
680
  session = None
677
681
  async_session = None
678
682
  session_token = None
@@ -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
- self.jwt = jwt_auth(self.settings) if self.jwt_enabled else None
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
- result = {"identity": identity}
269
- if user_id is not None:
270
- result["user_id"] = user_id
271
- if self.jwt_enabled:
272
- subject = str(user_id) if user_id is not None else f"{provider}:{identity['sub']}"
273
- claims = {
274
- "auth_provider": provider,
275
- "email": identity.get("email"),
276
- "email_verified": identity.get("email_verified", False),
277
- "name": identity.get("name"),
278
- "username": identity.get("username"),
279
- }
280
- result.update({
281
- "access_token": self.jwt.create_access_token(subject, claims=claims),
282
- "token_type": "bearer",
283
- "expires_in": self.jwt.token_lifetime_seconds,
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"
@@ -12,6 +12,14 @@ from collections.abc import Callable
12
12
  from sqlalchemy import and_, or_, select, update
13
13
 
14
14
  from .models import BACKGROUND_JOBS_TABLE
15
+ from .models import (
16
+ reset_current_async_session,
17
+ reset_current_database_backend,
18
+ reset_current_session,
19
+ set_current_async_session,
20
+ set_current_database_backend,
21
+ set_current_session,
22
+ )
15
23
 
16
24
  from .logging import get_logger
17
25
 
@@ -24,8 +32,12 @@ _MEMORY_QUEUE_JOBS: dict[str, dict[str, dict]] = {}
24
32
  class BackgroundTasks:
25
33
  """Collect functions to run after the response body has been sent."""
26
34
 
27
- def __init__(self) -> None:
35
+ def __init__(self, *, session_factory=None, async_session_factory=None,
36
+ database_backend: str | None = None) -> None:
28
37
  self._tasks: list[tuple[Callable, tuple, dict]] = []
38
+ self._session_factory = session_factory
39
+ self._async_session_factory = async_session_factory
40
+ self._database_backend = database_backend
29
41
 
30
42
  def add_task(self, function: Callable, *args, **kwargs) -> None:
31
43
  if not callable(function):
@@ -37,9 +49,56 @@ class BackgroundTasks:
37
49
  for function, args, kwargs in tasks:
38
50
  try:
39
51
  if inspect.iscoroutinefunction(function):
40
- await function(*args, **kwargs)
52
+ # Async handlers run on this event-loop thread, so create
53
+ # their independent sessions and bind them to this context.
54
+ session = self._session_factory() if self._session_factory else None
55
+ async_session = (
56
+ self._async_session_factory() if self._async_session_factory else None
57
+ )
58
+ session_token = set_current_session(session) if session is not None else None
59
+ async_session_token = (
60
+ set_current_async_session(async_session)
61
+ if async_session is not None else None
62
+ )
63
+ backend_token = (
64
+ set_current_database_backend(self._database_backend)
65
+ if self._database_backend is not None else None
66
+ )
67
+ try:
68
+ await function(*args, **kwargs)
69
+ finally:
70
+ if backend_token is not None:
71
+ reset_current_database_backend(backend_token)
72
+ if async_session_token is not None:
73
+ reset_current_async_session(async_session_token)
74
+ if session_token is not None:
75
+ reset_current_session(session_token)
76
+ if session is not None:
77
+ session.close()
78
+ if async_session is not None:
79
+ await async_session.close()
41
80
  else:
42
- result = await asyncio.to_thread(function, *args, **kwargs)
81
+ def invoke_sync_task():
82
+ # SQLAlchemy sessions are thread-affine for several
83
+ # drivers (including SQLite), so construct, use, and
84
+ # close the task session in the same worker thread.
85
+ session = self._session_factory() if self._session_factory else None
86
+ session_token = set_current_session(session) if session is not None else None
87
+ backend_token = (
88
+ set_current_database_backend(self._database_backend)
89
+ if self._database_backend is not None else None
90
+ )
91
+ try:
92
+ return function(*args, **kwargs)
93
+ finally:
94
+ if backend_token is not None:
95
+ reset_current_database_backend(backend_token)
96
+ if session_token is not None:
97
+ reset_current_session(session_token)
98
+ if session is not None:
99
+ session.close()
100
+
101
+ result = await asyncio.to_thread(invoke_sync_task)
43
102
  if inspect.isawaitable(result):
44
103
  await result
45
104
  except Exception:
@@ -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 = {
@@ -114,6 +119,8 @@ TOKEN = {
114
119
 
115
120
  from lenapi_bootstrap import create_app
116
121
 
122
+ # Keep app creation before imports from app.models or routers. This configures
123
+ # the project namespace for direct ``uvicorn main:app`` startup.
117
124
  app = create_app(__file__, __package__)
118
125
 
119
126
 
@@ -226,6 +233,7 @@ from sqlalchemy import create_engine, inspect
226
233
 
227
234
  from lenapi import Model
228
235
  from lenapi.project import project_namespace, project_object_name
236
+ from lenapi.migration_render import render_migration_item
229
237
 
230
238
  config = context.config
231
239
 
@@ -286,6 +294,7 @@ def run_migrations_offline():
286
294
  dialect_opts={"paramstyle": "named"},
287
295
  compare_type=True,
288
296
  include_object=include_migration_object,
297
+ render_item=render_migration_item,
289
298
  )
290
299
  with context.begin_transaction():
291
300
  context.run_migrations()
@@ -302,6 +311,7 @@ def run_migrations_online():
302
311
  version_table=project_object_name("alembic_version"),
303
312
  compare_type=True,
304
313
  include_object=include_migration_object,
314
+ render_item=render_migration_item,
305
315
  render_as_batch=connection.dialect.name == "sqlite",
306
316
  )
307
317
  with context.begin_transaction():
@@ -0,0 +1,25 @@
1
+ """Alembic render helpers for portable LenAPI migrations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlalchemy.sql.elements import False_, True_
6
+
7
+
8
+ def render_migration_item(type_: str, item, autogen_context):
9
+ """Keep Boolean server defaults as Boolean expressions in revisions.
10
+
11
+ Alembic renders ``false()`` using the dialect used to generate a revision.
12
+ On SQLite that becomes ``sa.text('0')``; such a revision then fails when
13
+ applied to PostgreSQL. Preserve the expression so the target dialect
14
+ compiles it to its native Boolean literal at migration time.
15
+ """
16
+ if type_ != "server_default":
17
+ return False
18
+
19
+ expression = getattr(item, "arg", item)
20
+ sqlalchemy_prefix = autogen_context.opts.get("sqlalchemy_module_prefix", "sa.")
21
+ if isinstance(expression, False_):
22
+ return f"{sqlalchemy_prefix}false()"
23
+ if isinstance(expression, True_):
24
+ return f"{sqlalchemy_prefix}true()"
25
+ return False
@@ -9,9 +9,10 @@ import re
9
9
  import uuid
10
10
  from urllib.parse import urlsplit
11
11
 
12
- from sqlalchemy import BigInteger, Boolean, CheckConstraint, Column, Date, DateTime, Float, ForeignKey, Integer, Interval, JSON, MetaData, Numeric, String, Table, Text, Time, Uuid, UniqueConstraint, and_, delete, false, func, inspect, or_, select
12
+ from sqlalchemy import BigInteger, Boolean, CheckConstraint, Column, Date, DateTime, Float, ForeignKey, Integer, Interval, JSON, MetaData, Numeric, String, Table, Text, Time, Uuid, UniqueConstraint, and_, delete, false, func, inspect, or_, select, text
13
13
  from sqlalchemy.exc import IntegrityError
14
14
  from sqlalchemy.orm import DeclarativeBase, Mapped, MappedColumn, Mapper, backref, declared_attr, mapped_column, object_session, relationship, selectinload
15
+ from sqlalchemy.sql.elements import False_, True_
15
16
  from sqlalchemy import event
16
17
 
17
18
  from .response import HTTPException
@@ -1615,8 +1616,19 @@ TExtfield = TextField
1615
1616
 
1616
1617
 
1617
1618
  def BooleanField(**kwargs):
1618
- """Declare a boolean column that defaults to ``True`` unless overridden."""
1619
+ """Declare a boolean column that defaults to ``True`` unless overridden.
1620
+
1621
+ Normalize SQLAlchemy's dialect-compiled Boolean server defaults to stable
1622
+ SQL literals. Alembic otherwise renders ``false()`` as ``0`` when a
1623
+ revision is generated against SQLite, which PostgreSQL rejects later.
1624
+ """
1619
1625
  kwargs.setdefault("default", True)
1626
+ server_default = kwargs.get("server_default")
1627
+ expression = getattr(server_default, "arg", server_default)
1628
+ if isinstance(expression, False_):
1629
+ kwargs["server_default"] = text("false")
1630
+ elif isinstance(expression, True_):
1631
+ kwargs["server_default"] = text("true")
1620
1632
  return _field(Boolean, **kwargs)
1621
1633
 
1622
1634
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lenapi
3
- Version: 0.1.4.3
3
+ Version: 0.1.4.5
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>
@@ -531,6 +531,8 @@ python lenora.py run
531
531
 
532
532
  Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
533
533
 
534
+ Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
535
+
534
536
  If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
535
537
 
536
538
  Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
@@ -1471,6 +1473,8 @@ def oidc_profile(identity=Depends(provider_auth)):
1471
1473
  ```python
1472
1474
  # settings.py — replace with the exact origin serving your frontend.
1473
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1476
+ SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1477
+ FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1474
1478
 
1475
1479
  # main.py
1476
1480
  from lenapi import LENAPI
@@ -1479,7 +1483,7 @@ from lenapi.security import SocialAuth
1479
1483
  auth = SocialAuth(
1480
1484
  providers=["google", "github", "linkedin"],
1481
1485
  auto_register=True,
1482
- jwt_enabled=True,
1486
+ jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
1483
1487
  )
1484
1488
 
1485
1489
  app = LENAPI()
@@ -1492,23 +1496,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1492
1496
  2. The provider authenticates the person and redirects the browser to the registered callback URL.
1493
1497
  3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
1494
1498
  4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
1495
- 5. With `jwt_enabled=True`, LenAPI issues **one LenAPI JWT access token** for use on protected application routes.
1499
+ 5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
1496
1500
 
1497
- `jwt_enabled` controls only that final LenAPI credential. SocialAuth currently issues a JWT access token; it does not issue an API key, session cookie, opaque bearer token, or refresh token. The provider's OAuth access token is used internally during the callback and is not returned to the client. With `jwt_enabled=False`, the callback response contains the provider `identity` and includes `user_id` when a local user was resolved, but no LenAPI token. For sessions, API keys, or opaque tokens, implement the desired credential issuance after the provider callback using the matching LenAPI auth dependency/store, or build a custom callback flow. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1501
+ 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
1502
 
1499
- For example, with both flags enabled, the callback response includes fields in this shape (identity claims vary by provider):
1503
+ 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
1504
 
1501
- ```json
1502
- {
1503
- "identity": {"sub": "provider-subject", "email": "ada@example.com"},
1504
- "user_id": 42,
1505
- "access_token": "<LenAPI JWT>",
1506
- "token_type": "bearer",
1507
- "expires_in": 3600
1508
- }
1505
+ ```python
1506
+ # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1507
+ from lenapi import JSONResponse, LENAPI, Request
1508
+ import settings
1509
+
1510
+ app = LENAPI()
1511
+
1512
+ @app.post("/auth/social/success")
1513
+ async def social_success(request: Request):
1514
+ data = await request.json()
1515
+ identity = data["identity"]
1516
+ user_id = data.get("user_id")
1517
+
1518
+ # Implement your own account rules and issue your own session/JWT here.
1519
+ user = await find_or_create_user(identity, user_id)
1520
+ session_id = await create_session(user)
1521
+
1522
+ response = JSONResponse({"accepted": True})
1523
+ response.set_cookie(
1524
+ "session_id", session_id, max_age=3600, path="/",
1525
+ httponly=True, secure=True, samesite="lax",
1526
+ )
1527
+ return response
1509
1528
  ```
1510
1529
 
1511
- The client then sends `Authorization: Bearer <access_token>` to routes protected with LenAPI JWT authentication. Store and transmit the token securely; do not use the provider token in place of the LenAPI token.
1530
+ 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
1531
 
1513
1532
  `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
1533
 
@@ -1615,6 +1634,8 @@ class User(BaseUser):
1615
1634
 
1616
1635
  Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
1617
1636
 
1637
+ LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
1638
+
1618
1639
  For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
1619
1640
 
1620
1641
  Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
@@ -16,6 +16,7 @@ lenapi/dependencies.py
16
16
  lenapi/docs_guard.py
17
17
  lenapi/logging.py
18
18
  lenapi/middleware.py
19
+ lenapi/migration_render.py
19
20
  lenapi/model.py
20
21
  lenapi/models.py
21
22
  lenapi/mongodb.py
@@ -41,6 +42,7 @@ tests/test_cli_settings_recovery.py
41
42
  tests/test_docs_guard.py
42
43
  tests/test_framework_features.py
43
44
  tests/test_media_upload.py
45
+ tests/test_migration_render.py
44
46
  tests/test_mongodb.py
45
47
  tests/test_platform_services.py
46
48
  tests/test_project_isolation.py
@@ -54,7 +54,12 @@ def configure_project(source_file: str, package: str | None = None):
54
54
 
55
55
 
56
56
  def create_app(source_file: str, package: str | None = None):
57
- """Create a configured app and import the project's models for migrations."""
57
+ """Create a configured app and import project models under its namespace.
58
+
59
+ Call this before importing application routers or models. Generated
60
+ ``main.py`` does so at module import time, which lets Uvicorn load
61
+ ``main:app`` directly without the ``lenora`` launcher.
62
+ """
58
63
  settings = configure_project(source_file, package)
59
64
  model_module = f"{package}.app.models" if package else "app.models"
60
65
  importlib.import_module(model_module)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "lenapi"
7
- version = "0.1.4.3"
7
+ version = "0.1.4.5"
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"},
@@ -228,6 +228,32 @@ def test_typed_path_query_body_request_and_background_tasks():
228
228
  app.database.close()
229
229
 
230
230
 
231
+ def test_sync_background_task_gets_fresh_database_session(tmp_path):
232
+ app = Application(
233
+ database=Database(f"sqlite:///{tmp_path / 'background.sqlite3'}"),
234
+ security_storage="memory",
235
+ )
236
+ Model.metadata.create_all(app.database.engine, tables=[FeatureRecord.__table__])
237
+
238
+ @app.post("/audit")
239
+ def audit(request: Request):
240
+ request.background_tasks.add_task(FeatureRecord.create, name="background-audit")
241
+ return {"accepted": True}
242
+
243
+ status, _headers, result = json_request(app, "/audit", method="POST")
244
+ assert status == 200
245
+ assert result == {"accepted": True}
246
+
247
+ with app.database.engine.connect() as connection:
248
+ rows = connection.execute(
249
+ select(FeatureRecord.__table__).where(
250
+ FeatureRecord.__table__.c.name == "background-audit"
251
+ )
252
+ ).mappings().all()
253
+ assert len(rows) == 1
254
+ app.database.close()
255
+
256
+
231
257
  def test_dependency_results_are_cached_and_cycles_return_422():
232
258
  app = make_app()
233
259
  calls = []
@@ -0,0 +1,48 @@
1
+ """Regression tests for portable generated database defaults."""
2
+
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+ from sqlalchemy import Boolean, Column, MetaData, Table, false, true
7
+ from sqlalchemy.dialects import mysql, postgresql, sqlite
8
+ from sqlalchemy.schema import CreateTable, DefaultClause
9
+
10
+ from lenapi.migration_render import render_migration_item
11
+ from lenapi.models import BooleanField
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ ("expression", "expected_sql", "expected_render"),
16
+ [
17
+ (false(), "false", "sa.false()"),
18
+ (true(), "true", "sa.true()"),
19
+ ],
20
+ )
21
+ def test_boolean_field_server_defaults_are_portable(
22
+ expression, expected_sql, expected_render
23
+ ):
24
+ field = BooleanField(default=False, nullable=False, server_default=expression)
25
+ default = field.column.server_default
26
+
27
+ assert str(default.arg) == expected_sql
28
+ for dialect in (sqlite.dialect(), postgresql.dialect(), mysql.dialect()):
29
+ table = Table(
30
+ f"boolean_default_{dialect.name}",
31
+ MetaData(),
32
+ Column("enabled", Boolean, server_default=default.arg, nullable=False),
33
+ )
34
+ ddl = str(CreateTable(table).compile(dialect=dialect))
35
+ assert f"default {expected_sql}" in ddl.lower()
36
+
37
+ rendered = render_migration_item(
38
+ "server_default",
39
+ DefaultClause(expression),
40
+ SimpleNamespace(opts={"sqlalchemy_module_prefix": "sa."}),
41
+ )
42
+ assert rendered == expected_render
43
+
44
+
45
+ def test_non_boolean_server_default_uses_alembic_default_renderer():
46
+ assert render_migration_item(
47
+ "server_default", "CURRENT_TIMESTAMP", SimpleNamespace(opts={})
48
+ ) is False
@@ -171,6 +171,50 @@ def test_generated_project_uses_namespaced_tables_and_requires_orphan_confirmati
171
171
  ).fetchone() is None
172
172
 
173
173
 
174
+ def test_generated_project_imports_with_uvicorn_before_model_declarations(tmp_path):
175
+ env = os.environ.copy()
176
+ env.pop("LENAPI_PROJECT_NAME", None)
177
+ env.pop("LENAPI_PROJECT_NAMESPACE", None)
178
+ env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "")
179
+ created = subprocess.run(
180
+ [sys.executable, "-c", "from lenapi.cli import main; main()", "startproject", "demo"],
181
+ cwd=tmp_path,
182
+ env=env,
183
+ capture_output=True,
184
+ text=True,
185
+ check=False,
186
+ )
187
+ assert created.returncode == 0, created.stdout + created.stderr
188
+
189
+ project_dir = tmp_path / "demo"
190
+ models_path = project_dir / "app" / "models.py"
191
+ with models_path.open("a", encoding="utf-8") as models_file:
192
+ models_file.write(
193
+ "\nfrom lenapi import model\n"
194
+ "class UvicornNamespaceProbe(model.Model):\n"
195
+ " value = model.StringField(max_length=20)\n"
196
+ )
197
+
198
+ direct_import = subprocess.run(
199
+ [
200
+ sys.executable,
201
+ "-c",
202
+ "from uvicorn.importer import import_from_string\n"
203
+ "app = import_from_string('main:app')\n"
204
+ "from app.models import UvicornNamespaceProbe\n"
205
+ "assert UvicornNamespaceProbe.__table__.name == "
206
+ "f'{app.project_namespace}_uvicornnamespaceprobe'\n"
207
+ "assert app.project_name == 'demo'\n",
208
+ ],
209
+ cwd=project_dir,
210
+ env=env,
211
+ capture_output=True,
212
+ text=True,
213
+ check=False,
214
+ )
215
+ assert direct_import.returncode == 0, direct_import.stdout + direct_import.stderr
216
+
217
+
174
218
  def test_project_settings_identity_matches_project_directory(tmp_path, monkeypatch):
175
219
  monkeypatch.delenv("LENAPI_PROJECT_NAME", raising=False)
176
220
  monkeypatch.delenv("LENAPI_PROJECT_NAMESPACE", raising=False)
@@ -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(app, path, *, method="GET", payload=None, headers=(), query_string=b""):
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
- return start["status"], json.loads(response_body or b"null")
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