lenapi 0.1.4.4__tar.gz → 0.1.4.6__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.4 → lenapi-0.1.4.6}/PKG-INFO +19 -13
  2. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/README.md +18 -12
  3. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/__init__.py +1 -1
  4. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/application.py +5 -1
  5. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/auth.py +2 -12
  6. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/background.py +62 -3
  7. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/cli.py +5 -2
  8. lenapi-0.1.4.6/lenapi/migration_render.py +25 -0
  9. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/models.py +14 -2
  10. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/PKG-INFO +19 -13
  11. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/SOURCES.txt +2 -0
  12. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi_bootstrap.py +6 -1
  13. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/pyproject.toml +1 -1
  14. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_framework_features.py +26 -0
  15. lenapi-0.1.4.6/tests/test_migration_render.py +48 -0
  16. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_project_isolation.py +44 -0
  17. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_security_patch.py +42 -0
  18. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/LICENSE +0 -0
  19. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/admin.py +0 -0
  20. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/authentication.py +0 -0
  21. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/authorization.py +0 -0
  22. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/concurrency.py +0 -0
  23. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/database.py +0 -0
  24. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/dependencies.py +0 -0
  25. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/docs_guard.py +0 -0
  26. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/logging.py +0 -0
  27. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/middleware.py +0 -0
  28. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/model.py +0 -0
  29. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/mongodb.py +0 -0
  30. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/openapi.py +0 -0
  31. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/parameters.py +0 -0
  32. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/project.py +0 -0
  33. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/request.py +0 -0
  34. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/response.py +0 -0
  35. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/security.py +0 -0
  36. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/security_store.py +0 -0
  37. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/sentinels.py +0 -0
  38. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/service.py +0 -0
  39. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/throttling.py +0 -0
  40. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi/transaction.py +0 -0
  41. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/dependency_links.txt +0 -0
  42. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/entry_points.txt +0 -0
  43. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/requires.txt +0 -0
  44. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/lenapi.egg-info/top_level.txt +0 -0
  45. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/setup.cfg +0 -0
  46. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_admin_console.py +0 -0
  47. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_cli_settings_recovery.py +0 -0
  48. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_docs_guard.py +0 -0
  49. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_media_upload.py +0 -0
  50. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_mongodb.py +0 -0
  51. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_platform_services.py +0 -0
  52. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_sentinels.py +0 -0
  53. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/tests/test_throttle.py +0 -0
  54. {lenapi-0.1.4.4 → lenapi-0.1.4.6}/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.4
3
+ Version: 0.1.4.6
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`.
@@ -1472,7 +1474,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1472
1474
  # settings.py — replace with the exact origin serving your frontend.
1473
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1474
1476
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1475
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1476
1477
 
1477
1478
  # main.py
1478
1479
  from lenapi import LENAPI
@@ -1498,12 +1499,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1498
1499
 
1499
1500
  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.
1500
1501
 
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.
1502
+ 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. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1502
1503
 
1503
1504
  ```python
1504
1505
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1505
1506
  from lenapi import JSONResponse, LENAPI, Request
1506
- import settings
1507
+ import hashlib
1508
+ import secrets
1509
+ from urllib.parse import urlencode
1507
1510
 
1508
1511
  app = LENAPI()
1509
1512
 
@@ -1513,19 +1516,20 @@ async def social_success(request: Request):
1513
1516
  identity = data["identity"]
1514
1517
  user_id = data.get("user_id")
1515
1518
 
1516
- # Implement your own account rules and issue your own session/JWT here.
1519
+ # Apply your own account rules, then store a short-lived, single-use code.
1517
1520
  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",
1521
+ code = secrets.token_urlsafe(32)
1522
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1523
+ await app.cache.set(
1524
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1524
1525
  )
1525
- return response
1526
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1527
+ return JSONResponse({"redirect_url": redirect_url})
1526
1528
  ```
1527
1529
 
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.
1530
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1531
+
1532
+ 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 webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1529
1533
 
1530
1534
  `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.
1531
1535
 
@@ -1632,6 +1636,8 @@ class User(BaseUser):
1632
1636
 
1633
1637
  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.
1634
1638
 
1639
+ 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.
1640
+
1635
1641
  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.
1636
1642
 
1637
1643
  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`.
@@ -1420,7 +1422,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1420
1422
  # settings.py — replace with the exact origin serving your frontend.
1421
1423
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1422
1424
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1423
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1424
1425
 
1425
1426
  # main.py
1426
1427
  from lenapi import LENAPI
@@ -1446,12 +1447,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1446
1447
 
1447
1448
  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.
1448
1449
 
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.
1450
+ 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. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1450
1451
 
1451
1452
  ```python
1452
1453
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1453
1454
  from lenapi import JSONResponse, LENAPI, Request
1454
- import settings
1455
+ import hashlib
1456
+ import secrets
1457
+ from urllib.parse import urlencode
1455
1458
 
1456
1459
  app = LENAPI()
1457
1460
 
@@ -1461,19 +1464,20 @@ async def social_success(request: Request):
1461
1464
  identity = data["identity"]
1462
1465
  user_id = data.get("user_id")
1463
1466
 
1464
- # Implement your own account rules and issue your own session/JWT here.
1467
+ # Apply your own account rules, then store a short-lived, single-use code.
1465
1468
  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",
1469
+ code = secrets.token_urlsafe(32)
1470
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1471
+ await app.cache.set(
1472
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1472
1473
  )
1473
- return response
1474
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1475
+ return JSONResponse({"redirect_url": redirect_url})
1474
1476
  ```
1475
1477
 
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.
1478
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1479
+
1480
+ 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 webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1477
1481
 
1478
1482
  `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.
1479
1483
 
@@ -1580,6 +1584,8 @@ class User(BaseUser):
1580
1584
 
1581
1585
  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.
1582
1586
 
1587
+ 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.
1588
+
1583
1589
  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.
1584
1590
 
1585
1591
  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.4"
11
+ __version__ = "0.1.4.6"
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
@@ -43,7 +43,6 @@ class SocialAuth:
43
43
  user_model=None,
44
44
  allowed_origins=None,
45
45
  success_callback: str | None = None,
46
- frontend_redirect_uri: str | None = None,
47
46
  ) -> None:
48
47
  if isinstance(providers, str):
49
48
  raise TypeError("providers must be a list or tuple of provider names")
@@ -74,13 +73,6 @@ class SocialAuth:
74
73
  if success_callback is None:
75
74
  success_callback = getattr(self.settings, "SOCIAL_AUTH_SUCCESS_CALLBACK", "") or None
76
75
  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
- )
84
76
  if allowed_origins is None:
85
77
  allowed_origins = getattr(self.settings, "SOCIAL_AUTH_ALLOWED_ORIGINS", ())
86
78
  self.allowed_origins = self._normalize_origins(allowed_origins)
@@ -118,7 +110,6 @@ class SocialAuth:
118
110
  or not parsed.hostname
119
111
  or parsed.username is not None
120
112
  or parsed.password is not None
121
- or parsed.query
122
113
  or parsed.fragment
123
114
  ):
124
115
  raise ValueError("Social login success callback returned an invalid redirect URL")
@@ -360,11 +351,10 @@ class SocialAuth:
360
351
  parsed_result = {}
361
352
  if isinstance(parsed_result, dict):
362
353
  result = parsed_result
363
- redirect_url = result.get("redirect_url") or self.frontend_redirect_uri
354
+ redirect_url = result.get("redirect_url")
364
355
  if not redirect_url:
365
356
  raise ValueError(
366
- "Social login needs a frontend redirect URL in the webhook response "
367
- "or FRONTEND_REDIRECT_URI setting"
357
+ "Social login success callback must return a redirect_url"
368
358
  )
369
359
  redirect_url = self._validate_success_redirect(redirect_url)
370
360
  cookies = response.headers.get_list("set-cookie")
@@ -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:
@@ -104,8 +104,6 @@ SOCIAL_AUTH_ALLOWED_ORIGINS = []
104
104
  # Optional server-to-server endpoint for application-owned social login/session handling.
105
105
  # Use HTTPS when enabling it.
106
106
  SOCIAL_AUTH_SUCCESS_CALLBACK = ""
107
- # Browser destination after the social-auth webhook succeeds.
108
- FRONTEND_REDIRECT_URI = ""
109
107
  # Keep this generated key private. Rotate it to invalidate existing tokens.
110
108
  SECRET_KEY = "__LENAPI_GENERATED_SECRET_KEY__"
111
109
  TOKEN = {
@@ -119,6 +117,8 @@ TOKEN = {
119
117
 
120
118
  from lenapi_bootstrap import create_app
121
119
 
120
+ # Keep app creation before imports from app.models or routers. This configures
121
+ # the project namespace for direct ``uvicorn main:app`` startup.
122
122
  app = create_app(__file__, __package__)
123
123
 
124
124
 
@@ -231,6 +231,7 @@ from sqlalchemy import create_engine, inspect
231
231
 
232
232
  from lenapi import Model
233
233
  from lenapi.project import project_namespace, project_object_name
234
+ from lenapi.migration_render import render_migration_item
234
235
 
235
236
  config = context.config
236
237
 
@@ -291,6 +292,7 @@ def run_migrations_offline():
291
292
  dialect_opts={"paramstyle": "named"},
292
293
  compare_type=True,
293
294
  include_object=include_migration_object,
295
+ render_item=render_migration_item,
294
296
  )
295
297
  with context.begin_transaction():
296
298
  context.run_migrations()
@@ -307,6 +309,7 @@ def run_migrations_online():
307
309
  version_table=project_object_name("alembic_version"),
308
310
  compare_type=True,
309
311
  include_object=include_migration_object,
312
+ render_item=render_migration_item,
310
313
  render_as_batch=connection.dialect.name == "sqlite",
311
314
  )
312
315
  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.4
3
+ Version: 0.1.4.6
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`.
@@ -1472,7 +1474,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1472
1474
  # settings.py — replace with the exact origin serving your frontend.
1473
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1474
1476
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1475
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1476
1477
 
1477
1478
  # main.py
1478
1479
  from lenapi import LENAPI
@@ -1498,12 +1499,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1498
1499
 
1499
1500
  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.
1500
1501
 
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.
1502
+ 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. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1502
1503
 
1503
1504
  ```python
1504
1505
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1505
1506
  from lenapi import JSONResponse, LENAPI, Request
1506
- import settings
1507
+ import hashlib
1508
+ import secrets
1509
+ from urllib.parse import urlencode
1507
1510
 
1508
1511
  app = LENAPI()
1509
1512
 
@@ -1513,19 +1516,20 @@ async def social_success(request: Request):
1513
1516
  identity = data["identity"]
1514
1517
  user_id = data.get("user_id")
1515
1518
 
1516
- # Implement your own account rules and issue your own session/JWT here.
1519
+ # Apply your own account rules, then store a short-lived, single-use code.
1517
1520
  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",
1521
+ code = secrets.token_urlsafe(32)
1522
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1523
+ await app.cache.set(
1524
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1524
1525
  )
1525
- return response
1526
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1527
+ return JSONResponse({"redirect_url": redirect_url})
1526
1528
  ```
1527
1529
 
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.
1530
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1531
+
1532
+ 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 webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1529
1533
 
1530
1534
  `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.
1531
1535
 
@@ -1632,6 +1636,8 @@ class User(BaseUser):
1632
1636
 
1633
1637
  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.
1634
1638
 
1639
+ 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.
1640
+
1635
1641
  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.
1636
1642
 
1637
1643
  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.4"
7
+ version = "0.1.4.6"
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)
@@ -208,6 +208,48 @@ def test_social_auth_success_callback_redirects_without_exposing_identity():
208
208
  assert delivered["identity"]["sub"] == "provider-user-1"
209
209
 
210
210
 
211
+ def test_social_auth_uses_webhook_redirect_with_query_parameters(monkeypatch):
212
+ import httpx
213
+
214
+ settings = SimpleNamespace(
215
+ SOCIAL_AUTH_SUCCESS_CALLBACK="https://backend.example/auth/social/success",
216
+ )
217
+ auth = SocialAuth(["google"], settings=settings)
218
+
219
+ class CallbackResponse:
220
+ is_success = True
221
+ content = b'{"redirect_url": "https://frontend.example/login/success?code=one-time-code"}'
222
+ headers = httpx.Headers([
223
+ ("set-cookie", "session_id=opaque-session; Path=/; HttpOnly; Secure; SameSite=None")
224
+ ])
225
+
226
+ @staticmethod
227
+ def json():
228
+ return {"redirect_url": "https://frontend.example/login/success?code=one-time-code"}
229
+
230
+ class CallbackClient:
231
+ def __init__(self, **kwargs):
232
+ pass
233
+
234
+ async def __aenter__(self):
235
+ return self
236
+
237
+ async def __aexit__(self, *_args):
238
+ return False
239
+
240
+ async def post(self, url, **kwargs):
241
+ assert url == settings.SOCIAL_AUTH_SUCCESS_CALLBACK
242
+ return CallbackResponse()
243
+
244
+ monkeypatch.setattr(httpx, "AsyncClient", CallbackClient)
245
+ redirect_url, cookies = asyncio.run(
246
+ auth._deliver_success("google", {"sub": "provider-user"}, None)
247
+ )
248
+
249
+ assert redirect_url == "https://frontend.example/login/success?code=one-time-code"
250
+ assert cookies == [
251
+ "session_id=opaque-session; Path=/; HttpOnly; Secure; SameSite=None"
252
+ ]
211
253
  def test_social_auth_origin_configuration_is_normalized_and_validated():
212
254
  auth = SocialAuth(
213
255
  ["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