drfast-api 0.1.0__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.
- drfast_api-0.1.0/.env.example +3 -0
- drfast_api-0.1.0/.github/workflows/ci.yml +26 -0
- drfast_api-0.1.0/.github/workflows/deploy_pypi.yml +20 -0
- drfast_api-0.1.0/.gitignore +11 -0
- drfast_api-0.1.0/.readthedocs.yaml +17 -0
- drfast_api-0.1.0/LICENSE +21 -0
- drfast_api-0.1.0/PKG-INFO +98 -0
- drfast_api-0.1.0/README.md +66 -0
- drfast_api-0.1.0/docs/api.rst +6 -0
- drfast_api-0.1.0/docs/conf.py +12 -0
- drfast_api-0.1.0/docs/index.rst +11 -0
- drfast_api-0.1.0/pyproject.toml +75 -0
- drfast_api-0.1.0/src/drfast/__init__.py +44 -0
- drfast_api-0.1.0/src/drfast/auth.py +126 -0
- drfast_api-0.1.0/src/drfast/cli.py +358 -0
- drfast_api-0.1.0/src/drfast/filters.py +36 -0
- drfast_api-0.1.0/src/drfast/middleware.py +48 -0
- drfast_api-0.1.0/src/drfast/models.py +45 -0
- drfast_api-0.1.0/src/drfast/orm.py +35 -0
- drfast_api-0.1.0/src/drfast/pagination.py +53 -0
- drfast_api-0.1.0/src/drfast/permissions.py +54 -0
- drfast_api-0.1.0/src/drfast/routers.py +42 -0
- drfast_api-0.1.0/src/drfast/serializers.py +214 -0
- drfast_api-0.1.0/src/drfast/settings.py +45 -0
- drfast_api-0.1.0/src/drfast/views.py +230 -0
- drfast_api-0.1.0/tests/test_cli.py +28 -0
- drfast_api-0.1.0/tests/test_middleware.py +42 -0
- drfast_api-0.1.0/tests/test_serializers.py +28 -0
- drfast_api-0.1.0/uv.lock +2455 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
quality:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: astral-sh/setup-uv@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.11"
|
|
19
|
+
- run: uv sync
|
|
20
|
+
- run: uv run ruff check .
|
|
21
|
+
- run: uv run mypy src
|
|
22
|
+
- run: uv run pytest
|
|
23
|
+
- run: uv run bandit -q -r src
|
|
24
|
+
- run: uv run pip-audit --skip-editable
|
|
25
|
+
- run: uv build
|
|
26
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: Publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ["v*"]
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
id-token: write
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
pypi:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
environment: pypi
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: astral-sh/setup-uv@v5
|
|
18
|
+
- run: uv build
|
|
19
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
20
|
+
|
drfast_api-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DRFast API contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: drfast-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: DRF-inspired async APIs for FastAPI and Tortoise ORM
|
|
5
|
+
Project-URL: Documentation, https://github.com/drfast-api/drfast-api#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/drfast-api/drfast-api/issues
|
|
7
|
+
Project-URL: Source, https://github.com/drfast-api/drfast-api
|
|
8
|
+
Author: DRFast API contributors
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Framework :: FastAPI
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: email-validator<3,>=2.2
|
|
21
|
+
Requires-Dist: fastapi-users<16,>=15.0.5
|
|
22
|
+
Requires-Dist: fastapi<1,>=0.115
|
|
23
|
+
Requires-Dist: pydantic-settings<3,>=2.3
|
|
24
|
+
Requires-Dist: pydantic<3,>=2.7
|
|
25
|
+
Requires-Dist: tortoise-orm<2,>=1
|
|
26
|
+
Requires-Dist: uvicorn[standard]<1,>=0.30
|
|
27
|
+
Provides-Extra: docs
|
|
28
|
+
Requires-Dist: sphinx<9,>=8; extra == 'docs'
|
|
29
|
+
Provides-Extra: postgres
|
|
30
|
+
Requires-Dist: asyncpg<1,>=0.29; extra == 'postgres'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# DRFast API
|
|
34
|
+
|
|
35
|
+
DRFast API brings familiar Django REST Framework patterns to fully async FastAPI applications backed by Tortoise ORM.
|
|
36
|
+
|
|
37
|
+
It is pre-1.0 software. The public surface includes serializers, model viewsets, routers, permissions, middleware, settings, Tortoise lifecycle integration, FastAPI Users integration, and the `drfast` management CLI.
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv add drfast-api
|
|
43
|
+
drfast startproject config
|
|
44
|
+
cd config
|
|
45
|
+
drfast migrate
|
|
46
|
+
drfast runserver
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Generated projects use SQLite locally. Set `DATABASE_URL` to a PostgreSQL URL and install `drfast-api[postgres]` for production.
|
|
50
|
+
|
|
51
|
+
## Application structure
|
|
52
|
+
|
|
53
|
+
Projects explicitly list Tortoise model modules in `Settings.installed_apps`. A generated app keeps models, serializers, and views separate:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
class TodoSerializer(ModelSerializer[Todo]):
|
|
57
|
+
model = Todo
|
|
58
|
+
id = UUIDField(read_only=True)
|
|
59
|
+
title = CharField()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class TodoViewSet(ModelViewSet):
|
|
63
|
+
model = Todo
|
|
64
|
+
serializer_class = TodoSerializer
|
|
65
|
+
ordering_fields = ("created_at", "title")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Register it with `DefaultRouter`, then include the router in the FastAPI application. Viewset handlers, serializer hooks, permission methods, and middleware hooks are asynchronous.
|
|
69
|
+
|
|
70
|
+
`drfast` delegates migration operations to Tortoise’s current built-in migration CLI:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
drfast init
|
|
74
|
+
drfast makemigrations --name add_todos
|
|
75
|
+
drfast migrate
|
|
76
|
+
drfast history
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The starter’s authentication uses FastAPI Users with DRFast’s Tortoise adapter. It enables registration and bearer JWT login; password reset and email verification require application-provided delivery hooks before they are enabled.
|
|
80
|
+
|
|
81
|
+
## Configuration
|
|
82
|
+
|
|
83
|
+
Copy `.env.example` to `.env` in generated projects. `SECRET_KEY` must be changed and `DEBUG=false` set for production. SQLite is suitable for local development and isolated tests; production should use PostgreSQL, explicit migrations, and an `asyncpg` connection URL.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
uv sync
|
|
89
|
+
uv run ruff check .
|
|
90
|
+
uv run mypy src
|
|
91
|
+
uv run pytest
|
|
92
|
+
uv run bandit -q -r src
|
|
93
|
+
uv run pip-audit --skip-editable
|
|
94
|
+
uv run python -m build
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The CI workflow also runs Bandit and pip-audit. Configure the PyPI trusted publisher for the `pypi` GitHub environment before tagging a release.
|
|
98
|
+
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# DRFast API
|
|
2
|
+
|
|
3
|
+
DRFast API brings familiar Django REST Framework patterns to fully async FastAPI applications backed by Tortoise ORM.
|
|
4
|
+
|
|
5
|
+
It is pre-1.0 software. The public surface includes serializers, model viewsets, routers, permissions, middleware, settings, Tortoise lifecycle integration, FastAPI Users integration, and the `drfast` management CLI.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
uv add drfast-api
|
|
11
|
+
drfast startproject config
|
|
12
|
+
cd config
|
|
13
|
+
drfast migrate
|
|
14
|
+
drfast runserver
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Generated projects use SQLite locally. Set `DATABASE_URL` to a PostgreSQL URL and install `drfast-api[postgres]` for production.
|
|
18
|
+
|
|
19
|
+
## Application structure
|
|
20
|
+
|
|
21
|
+
Projects explicitly list Tortoise model modules in `Settings.installed_apps`. A generated app keeps models, serializers, and views separate:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
class TodoSerializer(ModelSerializer[Todo]):
|
|
25
|
+
model = Todo
|
|
26
|
+
id = UUIDField(read_only=True)
|
|
27
|
+
title = CharField()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TodoViewSet(ModelViewSet):
|
|
31
|
+
model = Todo
|
|
32
|
+
serializer_class = TodoSerializer
|
|
33
|
+
ordering_fields = ("created_at", "title")
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Register it with `DefaultRouter`, then include the router in the FastAPI application. Viewset handlers, serializer hooks, permission methods, and middleware hooks are asynchronous.
|
|
37
|
+
|
|
38
|
+
`drfast` delegates migration operations to Tortoise’s current built-in migration CLI:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
drfast init
|
|
42
|
+
drfast makemigrations --name add_todos
|
|
43
|
+
drfast migrate
|
|
44
|
+
drfast history
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The starter’s authentication uses FastAPI Users with DRFast’s Tortoise adapter. It enables registration and bearer JWT login; password reset and email verification require application-provided delivery hooks before they are enabled.
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
Copy `.env.example` to `.env` in generated projects. `SECRET_KEY` must be changed and `DEBUG=false` set for production. SQLite is suitable for local development and isolated tests; production should use PostgreSQL, explicit migrations, and an `asyncpg` connection URL.
|
|
52
|
+
|
|
53
|
+
## Development
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
uv sync
|
|
57
|
+
uv run ruff check .
|
|
58
|
+
uv run mypy src
|
|
59
|
+
uv run pytest
|
|
60
|
+
uv run bandit -q -r src
|
|
61
|
+
uv run pip-audit --skip-editable
|
|
62
|
+
uv run python -m build
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The CI workflow also runs Bandit and pip-audit. Configure the PyPI trusted publisher for the `pypi` GitHub environment before tagging a release.
|
|
66
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Sphinx configuration for DRFast API."""
|
|
2
|
+
|
|
3
|
+
project = "DRFast API"
|
|
4
|
+
copyright = "2026, DRFast API contributors"
|
|
5
|
+
author = "DRFast API contributors"
|
|
6
|
+
|
|
7
|
+
extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon"]
|
|
8
|
+
templates_path = ["_templates"]
|
|
9
|
+
exclude_patterns: list[str] = []
|
|
10
|
+
|
|
11
|
+
html_theme = "alabaster"
|
|
12
|
+
autodoc_typehints = "description"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "drfast-api"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "DRF-inspired async APIs for FastAPI and Tortoise ORM"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "DRFast API contributors" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
15
|
+
"Framework :: FastAPI",
|
|
16
|
+
"Framework :: AsyncIO",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"fastapi>=0.115,<1",
|
|
25
|
+
"fastapi-users>=15.0.5,<16",
|
|
26
|
+
"email-validator>=2.2,<3",
|
|
27
|
+
"pydantic>=2.7,<3",
|
|
28
|
+
"pydantic-settings>=2.3,<3",
|
|
29
|
+
"tortoise-orm>=1,<2",
|
|
30
|
+
"uvicorn[standard]>=0.30,<1",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
postgres = ["asyncpg>=0.29,<1"]
|
|
35
|
+
docs = ["sphinx>=8,<9"]
|
|
36
|
+
|
|
37
|
+
[dependency-groups]
|
|
38
|
+
dev = [
|
|
39
|
+
"httpx>=0.27,<1",
|
|
40
|
+
"pytest>=9.0.3,<10",
|
|
41
|
+
"pytest-asyncio>=0.23,<1",
|
|
42
|
+
"ruff>=0.8,<1",
|
|
43
|
+
"mypy>=1.13,<2",
|
|
44
|
+
"bandit>=1.7,<2",
|
|
45
|
+
"pip-audit>=2.7,<3",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[project.scripts]
|
|
49
|
+
drfast = "drfast.cli:main"
|
|
50
|
+
|
|
51
|
+
[project.urls]
|
|
52
|
+
Documentation = "https://github.com/drfast-api/drfast-api#readme"
|
|
53
|
+
Issues = "https://github.com/drfast-api/drfast-api/issues"
|
|
54
|
+
Source = "https://github.com/drfast-api/drfast-api"
|
|
55
|
+
|
|
56
|
+
[tool.hatch.build.targets.wheel]
|
|
57
|
+
packages = ["src/drfast"]
|
|
58
|
+
|
|
59
|
+
[tool.pytest.ini_options]
|
|
60
|
+
asyncio_mode = "auto"
|
|
61
|
+
testpaths = ["tests"]
|
|
62
|
+
|
|
63
|
+
[tool.ruff]
|
|
64
|
+
target-version = "py311"
|
|
65
|
+
line-length = 100
|
|
66
|
+
src = ["src"]
|
|
67
|
+
|
|
68
|
+
[tool.ruff.lint]
|
|
69
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
70
|
+
|
|
71
|
+
[tool.mypy]
|
|
72
|
+
python_version = "3.11"
|
|
73
|
+
strict = true
|
|
74
|
+
files = ["src"]
|
|
75
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""DRF-inspired primitives for async FastAPI applications."""
|
|
2
|
+
|
|
3
|
+
from drfast.filters import FilterSet
|
|
4
|
+
from drfast.middleware import BaseMiddleware
|
|
5
|
+
from drfast.models import Model, SoftDeleteModel, TimestampedModel
|
|
6
|
+
from drfast.pagination import LimitOffsetPagination
|
|
7
|
+
from drfast.permissions import AllowAny, BasePermission, IsAdminUser, IsAuthenticated
|
|
8
|
+
from drfast.routers import DefaultRouter
|
|
9
|
+
from drfast.serializers import (
|
|
10
|
+
BooleanField,
|
|
11
|
+
CharField,
|
|
12
|
+
EmailField,
|
|
13
|
+
IntegerField,
|
|
14
|
+
ModelSerializer,
|
|
15
|
+
Serializer,
|
|
16
|
+
UUIDField,
|
|
17
|
+
)
|
|
18
|
+
from drfast.settings import DRFastSettings
|
|
19
|
+
from drfast.views import APIView, ModelViewSet
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"APIView",
|
|
23
|
+
"AllowAny",
|
|
24
|
+
"BaseMiddleware",
|
|
25
|
+
"BasePermission",
|
|
26
|
+
"BooleanField",
|
|
27
|
+
"CharField",
|
|
28
|
+
"DRFastSettings",
|
|
29
|
+
"DefaultRouter",
|
|
30
|
+
"EmailField",
|
|
31
|
+
"FilterSet",
|
|
32
|
+
"IntegerField",
|
|
33
|
+
"IsAdminUser",
|
|
34
|
+
"IsAuthenticated",
|
|
35
|
+
"LimitOffsetPagination",
|
|
36
|
+
"Model",
|
|
37
|
+
"ModelSerializer",
|
|
38
|
+
"ModelViewSet",
|
|
39
|
+
"Serializer",
|
|
40
|
+
"SoftDeleteModel",
|
|
41
|
+
"TimestampedModel",
|
|
42
|
+
"UUIDField",
|
|
43
|
+
]
|
|
44
|
+
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Current FastAPI Users integration backed by Tortoise ORM.
|
|
2
|
+
|
|
3
|
+
FastAPI Users no longer ships a Tortoise adapter. This module maintains the
|
|
4
|
+
small persistence bridge while leaving its authentication and security flows
|
|
5
|
+
to FastAPI Users.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import AsyncGenerator, Callable
|
|
11
|
+
from typing import Any, Generic, Protocol, Self, TypeVar
|
|
12
|
+
from uuid import UUID
|
|
13
|
+
|
|
14
|
+
from fastapi import Depends, Request
|
|
15
|
+
from fastapi_users import BaseUserManager, FastAPIUsers
|
|
16
|
+
from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy
|
|
17
|
+
from fastapi_users.db import BaseUserDatabase
|
|
18
|
+
from fastapi_users.manager import UUIDIDMixin
|
|
19
|
+
from fastapi_users.models import UserProtocol
|
|
20
|
+
from tortoise import fields
|
|
21
|
+
|
|
22
|
+
from drfast.models import Model, TimestampedModel
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TortoiseUserProtocol(UserProtocol[UUID], Protocol):
|
|
26
|
+
"""Structural contract required by the Tortoise FastAPI Users adapter."""
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
async def get_or_none(cls, **kwargs: Any) -> Self | None: ...
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
async def create(cls, **kwargs: Any) -> Self: ...
|
|
33
|
+
|
|
34
|
+
async def save(self, *, update_fields: list[str]) -> None: ...
|
|
35
|
+
|
|
36
|
+
async def delete(self) -> None: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
UserType = TypeVar("UserType", bound=TortoiseUserProtocol)
|
|
40
|
+
AuthUserType = TypeVar("AuthUserType", bound=UserProtocol[UUID])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class FastAPIUserModel(Model, TimestampedModel):
|
|
44
|
+
"""Ready-to-use Tortoise user table base with FastAPI Users fields."""
|
|
45
|
+
|
|
46
|
+
email = fields.CharField(max_length=320, unique=True, index=True)
|
|
47
|
+
hashed_password = fields.CharField(max_length=1024)
|
|
48
|
+
is_active = fields.BooleanField(default=True)
|
|
49
|
+
is_superuser = fields.BooleanField(default=False)
|
|
50
|
+
is_verified = fields.BooleanField(default=False)
|
|
51
|
+
|
|
52
|
+
class Meta:
|
|
53
|
+
abstract = True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TortoiseUserDatabase(BaseUserDatabase[UserType, UUID], Generic[UserType]):
|
|
57
|
+
"""FastAPI Users persistence adapter for a Tortoise UUID user model."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, user_model: type[UserType]) -> None:
|
|
60
|
+
self.user_model = user_model
|
|
61
|
+
|
|
62
|
+
async def get(self, id: UUID) -> UserType | None:
|
|
63
|
+
return await self.user_model.get_or_none(id=id)
|
|
64
|
+
|
|
65
|
+
async def get_by_email(self, email: str) -> UserType | None:
|
|
66
|
+
return await self.user_model.get_or_none(email=email)
|
|
67
|
+
|
|
68
|
+
async def create(self, create_dict: dict[str, Any]) -> UserType:
|
|
69
|
+
return await self.user_model.create(**create_dict)
|
|
70
|
+
|
|
71
|
+
async def update(self, user: UserType, update_dict: dict[str, Any]) -> UserType:
|
|
72
|
+
for key, value in update_dict.items():
|
|
73
|
+
setattr(user, key, value)
|
|
74
|
+
await user.save(update_fields=list(update_dict))
|
|
75
|
+
return user
|
|
76
|
+
|
|
77
|
+
async def delete(self, user: UserType) -> None:
|
|
78
|
+
await user.delete()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class DRFastUserManager(UUIDIDMixin, BaseUserManager[UserType, UUID], Generic[UserType]):
|
|
82
|
+
"""Base manager applications subclass to add password and event policies."""
|
|
83
|
+
|
|
84
|
+
reset_password_token_secret: str
|
|
85
|
+
verification_token_secret: str
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def jwt_authentication(
|
|
89
|
+
secret: str,
|
|
90
|
+
lifetime_seconds: int = 3600,
|
|
91
|
+
) -> AuthenticationBackend[AuthUserType, UUID]:
|
|
92
|
+
"""Build FastAPI Users' bearer/JWT backend for generated projects."""
|
|
93
|
+
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
|
94
|
+
|
|
95
|
+
def get_strategy() -> JWTStrategy[AuthUserType, UUID]:
|
|
96
|
+
return JWTStrategy(secret=secret, lifetime_seconds=lifetime_seconds)
|
|
97
|
+
|
|
98
|
+
return AuthenticationBackend[AuthUserType, UUID](
|
|
99
|
+
name="jwt", transport=bearer_transport, get_strategy=get_strategy
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_fastapi_users(
|
|
104
|
+
get_user_manager: Callable[..., AsyncGenerator[DRFastUserManager[UserType], None]],
|
|
105
|
+
backend: AuthenticationBackend[UserType, UUID],
|
|
106
|
+
) -> FastAPIUsers[UserType, UUID]:
|
|
107
|
+
"""Create a FastAPI Users facade from application dependencies."""
|
|
108
|
+
return FastAPIUsers(get_user_manager, [backend])
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def current_user_middleware(
|
|
112
|
+
current_active_user: Callable[..., Any],
|
|
113
|
+
) -> Callable[[Request, Any], Any]:
|
|
114
|
+
"""Adapt a FastAPI Users dependency for DRFast permission classes.
|
|
115
|
+
|
|
116
|
+
Use this with a normal FastAPI dependency on protected routes when request
|
|
117
|
+
state is desired by custom `BasePermission` implementations.
|
|
118
|
+
"""
|
|
119
|
+
async def dependency( # noqa: B008 - FastAPI resolves dependencies from the signature.
|
|
120
|
+
request: Request, user: Any = Depends(current_active_user) # noqa: B008
|
|
121
|
+
) -> Any:
|
|
122
|
+
request.state.user = user
|
|
123
|
+
return user
|
|
124
|
+
|
|
125
|
+
return dependency
|
|
126
|
+
|