fastapi-djauth 1.4.0__py3-none-any.whl

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.

Potentially problematic release.


This version of fastapi-djauth might be problematic. Click here for more details.

Files changed (62) hide show
  1. djauth/__init__.py +82 -0
  2. djauth/__main__.py +98 -0
  3. djauth/api.py +890 -0
  4. djauth/backends.py +130 -0
  5. djauth/core.py +1280 -0
  6. djauth/database.py +148 -0
  7. djauth/decorators.py +119 -0
  8. djauth/errors.py +107 -0
  9. djauth/fields.py +157 -0
  10. djauth/hashers.py +54 -0
  11. djauth/models.py +200 -0
  12. djauth/plantilla/.dockerignore.tpl +8 -0
  13. djauth/plantilla/.env.example.tpl +15 -0
  14. djauth/plantilla/.github/workflows/ci.yml.tpl +22 -0
  15. djauth/plantilla/.gitignore.tpl +12 -0
  16. djauth/plantilla/Dockerfile.tpl +26 -0
  17. djauth/plantilla/README.md.tpl +83 -0
  18. djauth/plantilla/alembic.ini.tpl +39 -0
  19. djauth/plantilla/migrations/env.py.tpl +52 -0
  20. djauth/plantilla/migrations/script.py.mako.tpl +24 -0
  21. djauth/plantilla/migrations/versions/0001_productos.py.tpl +35 -0
  22. djauth/plantilla/pyproject.toml.tpl +46 -0
  23. djauth/plantilla/src/__paquete__/__init__.py.tpl +3 -0
  24. djauth/plantilla/src/__paquete__/api/__init__.py.tpl +0 -0
  25. djauth/plantilla/src/__paquete__/api/deps.py.tpl +12 -0
  26. djauth/plantilla/src/__paquete__/api/router.py.tpl +8 -0
  27. djauth/plantilla/src/__paquete__/api/v1/__init__.py.tpl +0 -0
  28. djauth/plantilla/src/__paquete__/api/v1/productos.py.tpl +74 -0
  29. djauth/plantilla/src/__paquete__/core/__init__.py.tpl +0 -0
  30. djauth/plantilla/src/__paquete__/core/config.py.tpl +41 -0
  31. djauth/plantilla/src/__paquete__/core/security.py.tpl +50 -0
  32. djauth/plantilla/src/__paquete__/db.py.tpl +41 -0
  33. djauth/plantilla/src/__paquete__/main.py.tpl +52 -0
  34. djauth/plantilla/src/__paquete__/models/__init__.py.tpl +5 -0
  35. djauth/plantilla/src/__paquete__/models/producto.py.tpl +24 -0
  36. djauth/plantilla/src/__paquete__/schemas/__init__.py.tpl +0 -0
  37. djauth/plantilla/src/__paquete__/schemas/producto.py.tpl +36 -0
  38. djauth/plantilla/src/__paquete__/services/__init__.py.tpl +0 -0
  39. djauth/plantilla/src/__paquete__/services/productos.py.tpl +46 -0
  40. djauth/plantilla/tests/__init__.py.tpl +0 -0
  41. djauth/plantilla/tests/conftest.py.tpl +35 -0
  42. djauth/plantilla/tests/test_app.py.tpl +42 -0
  43. djauth/py.typed +0 -0
  44. djauth/routers.py +404 -0
  45. djauth/settings.py +127 -0
  46. djauth/startproject.py +271 -0
  47. djauth/static/account.html +51 -0
  48. djauth/static/account.js +34 -0
  49. djauth/static/admin.html +167 -0
  50. djauth/static/admin.js +346 -0
  51. djauth/static/common.js +99 -0
  52. djauth/static/djauth.css +99 -0
  53. djauth/static/login.html +26 -0
  54. djauth/static/login.js +38 -0
  55. djauth/static/reset.html +27 -0
  56. djauth/static/reset.js +30 -0
  57. djauth/validators.py +139 -0
  58. fastapi_djauth-1.4.0.dist-info/METADATA +133 -0
  59. fastapi_djauth-1.4.0.dist-info/RECORD +62 -0
  60. fastapi_djauth-1.4.0.dist-info/WHEEL +4 -0
  61. fastapi_djauth-1.4.0.dist-info/entry_points.txt +2 -0
  62. fastapi_djauth-1.4.0.dist-info/licenses/LICENSE +20 -0
djauth/__init__.py ADDED
@@ -0,0 +1,82 @@
1
+ """djauth: usuarios, grupos (roles), permisos y administración al estilo de Django, para FastAPI.
2
+
3
+ from djauth import AuthKit, AuthSettings, current_user, require_perm
4
+
5
+ kit = AuthKit(AuthSettings(database_url="sqlite:///auth.sqlite3")).init()
6
+ kit.install(app, protect=True)
7
+ """
8
+
9
+ from djauth.api import (
10
+ AuthMiddleware,
11
+ Rule,
12
+ current_user,
13
+ identify,
14
+ optional_user,
15
+ require_perm,
16
+ require_staff,
17
+ require_superuser,
18
+ rule,
19
+ ws_user,
20
+ )
21
+ from djauth.backends import AllowAllUsersModelBackend, AuthRequest, BaseBackend, ModelBackend
22
+ from djauth.core import SERVICE_USER, AuthKit, AuthUser
23
+ from djauth.database import DatabaseConfigError, url_from_django
24
+ from djauth.decorators import login_required, permission_required, staff_member_required, superuser_required, user_passes_test
25
+ from djauth.errors import (
26
+ AuthError,
27
+ InvalidCredentialsError,
28
+ NotAuthenticatedError,
29
+ NotFoundError,
30
+ PermissionDeniedError,
31
+ TooManyAttemptsError,
32
+ ValidationError,
33
+ )
34
+ from djauth.hashers import check_password, make_password
35
+ from djauth.routers import BaseRouter, Databases, ModelMeta, RoutingSession, model_meta
36
+ from djauth.settings import AuthSettings, ExtraField
37
+
38
+ __version__ = "1.4.0"
39
+
40
+ __all__ = [
41
+ "SERVICE_USER",
42
+ "AllowAllUsersModelBackend",
43
+ "AuthError",
44
+ "AuthKit",
45
+ "AuthMiddleware",
46
+ "AuthRequest",
47
+ "AuthSettings",
48
+ "AuthUser",
49
+ "BaseBackend",
50
+ "BaseRouter",
51
+ "DatabaseConfigError",
52
+ "Databases",
53
+ "ExtraField",
54
+ "InvalidCredentialsError",
55
+ "ModelBackend",
56
+ "ModelMeta",
57
+ "NotAuthenticatedError",
58
+ "NotFoundError",
59
+ "PermissionDeniedError",
60
+ "RoutingSession",
61
+ "Rule",
62
+ "TooManyAttemptsError",
63
+ "ValidationError",
64
+ "__version__",
65
+ "check_password",
66
+ "current_user",
67
+ "identify",
68
+ "login_required",
69
+ "make_password",
70
+ "model_meta",
71
+ "optional_user",
72
+ "permission_required",
73
+ "require_perm",
74
+ "require_staff",
75
+ "require_superuser",
76
+ "rule",
77
+ "staff_member_required",
78
+ "superuser_required",
79
+ "url_from_django",
80
+ "user_passes_test",
81
+ "ws_user",
82
+ ]
djauth/__main__.py ADDED
@@ -0,0 +1,98 @@
1
+ """Comandos de administración (como `manage.py`):
2
+
3
+ python -m djauth --db sqlite:///auth.sqlite3 createsuperuser --username admin --email a@b.co
4
+ python -m djauth --db … changepassword admin
5
+ python -m djauth --db … listusers
6
+ djauth startproject inventario --db postgresql # proyecto FastAPI nuevo con djauth integrado
7
+
8
+ La contraseña se pide por teclado; para scripts, use la variable DJAUTH_PASSWORD.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import getpass
15
+ import os
16
+ import sys
17
+
18
+ from djauth.core import AuthKit
19
+ from djauth.errors import AuthError, ValidationError
20
+ from djauth.settings import AuthSettings
21
+
22
+
23
+ def _ask_password() -> str:
24
+ if env := os.environ.get("DJAUTH_PASSWORD"):
25
+ return env
26
+ while True:
27
+ first = getpass.getpass("Contraseña: ")
28
+ if first == getpass.getpass("Contraseña (otra vez): "):
29
+ return first
30
+ print("Las contraseñas no coinciden.", file=sys.stderr)
31
+
32
+
33
+ def main(argv: list[str] | None = None) -> int:
34
+ parser = argparse.ArgumentParser(prog="python -m djauth", description="Administración de usuarios de djauth")
35
+ parser.add_argument(
36
+ "--db", default=os.environ.get("DJAUTH_DATABASE_URL", "sqlite:///auth.sqlite3"), help="URL de la base de datos"
37
+ )
38
+ parser.add_argument("--prefix", default="auth_", help="Prefijo de las tablas")
39
+ sub = parser.add_subparsers(dest="command", required=True)
40
+ create = sub.add_parser("createsuperuser", help="Crear un superusuario")
41
+ create.add_argument("--username", required=True)
42
+ create.add_argument("--email", default="")
43
+ change = sub.add_parser("changepassword", help="Cambiar la contraseña de un usuario")
44
+ change.add_argument("username")
45
+ sub.add_parser("listusers", help="Listar usuarios")
46
+ start = sub.add_parser("startproject", help="Crear un proyecto FastAPI nuevo con djauth integrado")
47
+ start.add_argument("name", help="Nombre del paquete: minúsculas, números y _ (p. ej. inventario)")
48
+ start.add_argument("directory", nargs="?", help="Carpeta donde crearlo (por defecto ./<name>; debe estar vacía)")
49
+ start.add_argument("--db", dest="db_engine", choices=("sqlite", "postgresql", "mysql"), default="sqlite")
50
+ start.add_argument(
51
+ "--versiones",
52
+ dest="versions",
53
+ choices=("probadas", "ultimas"),
54
+ default="probadas",
55
+ help="probadas: versiones exactas verificadas con este djauth · ultimas: lo más reciente compatible",
56
+ )
57
+ start.add_argument("--titulo", dest="title", help='Nombre visible de la aplicación (p. ej. "Inventario de planta")')
58
+ start.add_argument("--sin-lock", dest="no_lock", action="store_true", help="No ejecutar `uv lock` al terminar")
59
+ args = parser.parse_args(argv)
60
+
61
+ if args.command == "startproject":
62
+ from djauth.startproject import main as startproject
63
+
64
+ return startproject(args)
65
+
66
+ kit = AuthKit(AuthSettings(database_url=args.db, table_prefix=args.prefix)).init()
67
+ try:
68
+ if args.command == "createsuperuser":
69
+ created = kit.create_superuser(
70
+ args.username, _ask_password(), email=args.email, reason="Creado con djauth createsuperuser."
71
+ )
72
+ print(f"Superusuario {created['username']} creado.")
73
+ elif args.command == "changepassword":
74
+ user = kit.get_by_username(args.username)
75
+ if user is None:
76
+ print(f"No existe el usuario {args.username}.", file=sys.stderr)
77
+ return 1
78
+ kit.set_password(user.id, _ask_password(), reason="Cambiada con djauth changepassword.")
79
+ print(f"Contraseña de {user.username} cambiada; sus sesiones abiertas se cerraron.")
80
+ elif args.command == "listusers":
81
+ items, total = kit.list_users(limit=1000)
82
+ for u in items:
83
+ flags = "".join(f for f, on in (("S", u["is_superuser"]), ("A", u["is_staff"]), ("-", not u["is_active"])) if on)
84
+ print(f"{u['id']:>5} {u['username']:<30} {flags:<3} {', '.join(u['groups'])}")
85
+ print(f"{total} usuarios")
86
+ except ValidationError as exc:
87
+ for field, messages in exc.errors.items():
88
+ for m in messages:
89
+ print(f"{field}: {m}", file=sys.stderr)
90
+ return 1
91
+ except AuthError as exc:
92
+ print(str(exc), file=sys.stderr)
93
+ return 1
94
+ return 0
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())