authforce-rs-labs 0.2.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.
Files changed (29) hide show
  1. authforce_rs_labs-0.2.0/LICENSE +21 -0
  2. authforce_rs_labs-0.2.0/PKG-INFO +149 -0
  3. authforce_rs_labs-0.2.0/README.md +114 -0
  4. authforce_rs_labs-0.2.0/authforce/__init__.py +27 -0
  5. authforce_rs_labs-0.2.0/authforce/config.py +59 -0
  6. authforce_rs_labs-0.2.0/authforce/dependencies.py +78 -0
  7. authforce_rs_labs-0.2.0/authforce/errors.py +78 -0
  8. authforce_rs_labs-0.2.0/authforce/models.py +105 -0
  9. authforce_rs_labs-0.2.0/authforce/oauth_state.py +53 -0
  10. authforce_rs_labs-0.2.0/authforce/providers/__init__.py +4 -0
  11. authforce_rs_labs-0.2.0/authforce/providers/apple.py +120 -0
  12. authforce_rs_labs-0.2.0/authforce/providers/google.py +163 -0
  13. authforce_rs_labs-0.2.0/authforce/py.typed +0 -0
  14. authforce_rs_labs-0.2.0/authforce/rate_limit.py +56 -0
  15. authforce_rs_labs-0.2.0/authforce/router.py +231 -0
  16. authforce_rs_labs-0.2.0/authforce/security.py +156 -0
  17. authforce_rs_labs-0.2.0/authforce/service.py +444 -0
  18. authforce_rs_labs-0.2.0/authforce_rs_labs.egg-info/PKG-INFO +149 -0
  19. authforce_rs_labs-0.2.0/authforce_rs_labs.egg-info/SOURCES.txt +27 -0
  20. authforce_rs_labs-0.2.0/authforce_rs_labs.egg-info/dependency_links.txt +1 -0
  21. authforce_rs_labs-0.2.0/authforce_rs_labs.egg-info/requires.txt +12 -0
  22. authforce_rs_labs-0.2.0/authforce_rs_labs.egg-info/top_level.txt +1 -0
  23. authforce_rs_labs-0.2.0/pyproject.toml +72 -0
  24. authforce_rs_labs-0.2.0/setup.cfg +4 -0
  25. authforce_rs_labs-0.2.0/tests/test_hardening.py +141 -0
  26. authforce_rs_labs-0.2.0/tests/test_hardening_v02.py +197 -0
  27. authforce_rs_labs-0.2.0/tests/test_router_and_providers.py +187 -0
  28. authforce_rs_labs-0.2.0/tests/test_service.py +216 -0
  29. authforce_rs_labs-0.2.0/tests/test_unlink.py +114 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roffer
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,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: authforce-rs-labs
3
+ Version: 0.2.0
4
+ Summary: Autenticazione riusabile per backend FastAPI: password, JWT, sessioni con refresh ruotato e hashato, verifica email, Google e Apple.
5
+ Author: Roffer
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Samu7le/quiz_f1_generator/tree/main/libs/authforce
8
+ Project-URL: Changelog, https://github.com/Samu7le/quiz_f1_generator/blob/main/libs/authforce/CHANGELOG.md
9
+ Keywords: fastapi,authentication,jwt,oauth,sqlalchemy,sign-in-with-apple,google-sign-in
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Security
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: fastapi>=0.110
24
+ Requires-Dist: sqlalchemy[asyncio]>=2.0
25
+ Requires-Dist: pydantic[email]>=2.5
26
+ Requires-Dist: bcrypt>=4.1
27
+ Requires-Dist: PyJWT[crypto]>=2.8
28
+ Requires-Dist: httpx>=0.27
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
32
+ Requires-Dist: aiosqlite>=0.20; extra == "dev"
33
+ Requires-Dist: ruff>=0.5; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # AuthForce
37
+
38
+ *May the AuthForce be with you.*
39
+
40
+ Pacchetto `authforce-rs-labs` di Roffer, licenza MIT, si importa come `authforce`. Libreria di autenticazione per backend FastAPI con SQLAlchemy async. Contiene solo le parti generiche e di sicurezza del login. Le regole di un progetto (inviti, email, profilo, statistiche) restano nel progetto e chiamano i metodi della libreria.
41
+
42
+ Installazione: `pip install authforce-rs-labs`. Per i test: `pip install "authforce-rs-labs[dev]"`. Versioni in [CHANGELOG.md](CHANGELOG.md).
43
+
44
+ ## Cosa fa
45
+
46
+ | Area | Contenuto |
47
+ |---|---|
48
+ | Password | bcrypt (`security.hash_password`, `verify_password`). Oltre 72 byte `PasswordTooLong` alla registrazione e credenziali non valide al login |
49
+ | Access token | JWT firmato (HS256, HS384 o HS512), breve durata, tipo `access` verificato (`security.access_token_subject`) |
50
+ | Sessioni | refresh token opaco da 256 bit, salvato nel DB come SHA-256 e ruotato a ogni uso: un token già usato non vale più, anche con due refresh in parallelo. Riuso di un token già ruotato nel log e, a scelta, chiusura di tutte le sessioni. Logout, chiusura di tutte le sessioni |
51
+ | Utenti locali | registrazione, login con lo stesso errore e lo stesso tempo di risposta per email sconosciuta e password sbagliata, email normalizzate (una casella, un account), riattivazione di un account disattivato (`reactivate_on_login`, altrimenti `InactiveUser`) |
52
+ | Verifica email | token one-shot con scadenza (48 ore di default), salvato come SHA-256 |
53
+ | Google | login web (redirect e callback) e da app nativa (id_token verificato in locale con le chiavi pubbliche di Google: firma, issuer, audience, scadenza) |
54
+ | Apple | identity_token verificato (RS256, audience, issuer, `nonce` facoltativo), scambio dell'authorization code, revoca alla cancellazione dell'account |
55
+ | Login social | utente trovato per account social, poi per email (collegamento a un account locale solo se il provider garantisce l'email, altrimenti `OAuthEmailNotVerified`), altrimenti creato. Email di avviso con link "scollega" quando un login social si aggancia a un account esistente |
56
+ | Stato OAuth | parametro `state` e cookie HttpOnly contro il CSRF, confronto a tempo costante |
57
+ | Rate limit | interfaccia `RateLimiter` (il progetto passa Redis), `InMemoryRateLimiter` per un solo processo |
58
+ | FastAPI | dipendenze `current_user`, `optional_user` e `require(...)`; router base pronto per un progetto nuovo |
59
+
60
+ La configurazione rifiuta un segreto JWT più corto di 32 caratteri e un algoritmo fuori da HS256, HS384, HS512. Gli errori (`authforce.errors`) non contengono testi per l'utente: il progetto li traduce nella propria lingua. La libreria scrive nel logger `authforce` solo gli eventi di sicurezza (riuso di un refresh token), mai token o email.
61
+
62
+ ## Progetto nuovo
63
+
64
+ ```python
65
+ from datetime import timedelta
66
+ from sqlalchemy.orm import DeclarativeBase
67
+ from authforce import (AuthConfig, AuthModels, AuthService, CredentialsMixin,
68
+ EmailVerificationMixin, OAuthAccountMixin, SessionMixin, UserMixin)
69
+ from authforce.router import build_auth_router
70
+
71
+ class Base(DeclarativeBase): ...
72
+
73
+ class User(Base, UserMixin):
74
+ __tablename__ = "users"
75
+
76
+ class Credentials(Base, CredentialsMixin):
77
+ __tablename__ = "credentials"
78
+
79
+ class OAuthAccount(Base, OAuthAccountMixin):
80
+ __tablename__ = "oauth_accounts"
81
+
82
+ class Session(Base, SessionMixin):
83
+ __tablename__ = "sessions"
84
+
85
+ class EmailVerification(Base, EmailVerificationMixin):
86
+ __tablename__ = "email_verifications"
87
+
88
+ auth = AuthService(
89
+ AuthConfig(jwt_secret_key=SECRET, access_token_ttl=timedelta(minutes=30),
90
+ accept_plain_stored_tokens=False), # progetto nuovo: nessuna riga in chiaro da accettare
91
+ AuthModels(User, Credentials, OAuthAccount, Session, EmailVerification),
92
+ )
93
+ app.include_router(
94
+ build_auth_router(auth, get_session, user_response=UserOut, rate_limiter=redis_limiter,
95
+ send_verification_email=send_email),
96
+ prefix="/api/v1/auth",
97
+ )
98
+ ```
99
+
100
+ Con uno schema Postgres, ogni tabella collegata agli utenti indica la chiave esterna: `__auth_user_fk__ = "app_auth.users.id"`. Le tabelle si creano con le migrazioni del progetto (alembic autogenerate le vede dai mixin). Con `normalize_emails` conviene un indice funzionale su `lower(email)` se la tabella è grande.
101
+
102
+ ## Progetto con regole proprie
103
+
104
+ Il progetto scrive le sue rotte e chiama i metodi di `AuthService`. I metodi che non chiudono un login (`create_local_user`, `login_with_oauth`) fanno solo flush, così il progetto aggiunge le sue righe nella stessa transazione prima di `start_session`, che fa il commit.
105
+
106
+ ```python
107
+ user = await auth.create_local_user(db, email, password, username=username)
108
+ await apply_referral(db, user) # logica del progetto
109
+ tokens = await auth.start_session(db, user, ip, user_agent)
110
+ token = await auth.create_email_verification(db, user)
111
+ send_verification_email.delay(user.email, token) # logica del progetto
112
+ ```
113
+
114
+ Esempio completo: PitQuiz, in `BE/app/core/auth.py` (configurazione e modelli esistenti, senza migrazioni) e `BE/app/api/v1/auth/service/` (inviti, sponsor, email, classifiche).
115
+
116
+ ## Scelte di sicurezza e come cambiarle
117
+
118
+ Tutte in `AuthConfig`.
119
+
120
+ - `hash_stored_tokens` (acceso). Nel database ci sono gli hash dei refresh token e dei token di verifica: chi legge il database non apre sessioni. Il codice del progetto che confronta la colonna con il token del client passa da `security.hash_token`.
121
+ - `accept_plain_stored_tokens` (acceso). Per chi ha attivato l'hash dopo: le righe in chiaro restano valide finché scadono o vengono ruotate. Un valore con la forma di un hash non viene mai cercato in chiaro. Spegnerlo dopo `refresh_token_ttl` dal deploy, o subito in un progetto nuovo.
122
+ - `revoke_all_on_refresh_reuse` (spento). Un refresh token già ruotato presentato di nuovo è un token copiato oppure un client che ha perso la risposta. Acceso chiude tutte le sessioni dell'utente (OAuth 2.1); spento risponde solo `InvalidSession` e scrive nel log.
123
+ - `normalize_emails` (acceso). Minuscole e senza spazi ai bordi, anche nella ricerca sulle righe scritte prima.
124
+ - Dopo un cambio password chiamare `revoke_all_sessions` e aprire una sessione nuova: la libreria non lo fa da sola perché il progetto decide se tenere viva la sessione corrente.
125
+ - Gli access token restano validi fino alla scadenza anche dopo `revoke_all_sessions`: tenere `access_token_ttl` corto (15-30 minuti).
126
+ - IP del client per il rate limit e le sessioni: dietro un reverse proxy il server ASGI deve leggere `X-Forwarded-For` solo dai proxy fidati (uvicorn: `--proxy-headers --forwarded-allow-ips=<reti del proxy>`, mai `*`). In alternativa `build_auth_router(client_ip=header_client_ip("CF-Connecting-IP"))` se il proxy sovrascrive sempre quell'header ed è l'unico a raggiungere l'applicazione.
127
+ - Google da app nativa: `GoogleOAuth(native_client_ids=(...))` è obbligatorio, l'id_token si verifica in locale (JWKS di Google, cache delle chiavi per processo). `id_token_verifier="tokeninfo"` chiede a Google a ogni login.
128
+
129
+ ## Test e lint
130
+
131
+ ```
132
+ pip install -e ".[dev]"
133
+ pytest -q # SQLite in memoria, Google e Apple simulati
134
+ ruff check authforce tests
135
+ ```
136
+
137
+ ## Pubblicazione
138
+
139
+ Versione in `pyproject.toml` e `authforce/__init__.py`, voce nel CHANGELOG, poi da un ambiente separato da quello del progetto (twine porta dipendenze che non devono finire nella venv dell'applicazione):
140
+
141
+ ```
142
+ python -m venv /tmp/authforce-build && source /tmp/authforce-build/bin/activate
143
+ pip install build twine
144
+ cd libs/authforce && rm -rf dist && python -m build && twine check dist/*
145
+ twine upload --repository testpypi dist/* # prova su test.pypi.org
146
+ twine upload dist/* # PyPI
147
+ ```
148
+
149
+ Credenziali: token API di PyPI (`__token__` come utente), mai la password. Dopo la pubblicazione, un tag git `authforce-v0.2.0`.
@@ -0,0 +1,114 @@
1
+ # AuthForce
2
+
3
+ *May the AuthForce be with you.*
4
+
5
+ Pacchetto `authforce-rs-labs` di Roffer, licenza MIT, si importa come `authforce`. Libreria di autenticazione per backend FastAPI con SQLAlchemy async. Contiene solo le parti generiche e di sicurezza del login. Le regole di un progetto (inviti, email, profilo, statistiche) restano nel progetto e chiamano i metodi della libreria.
6
+
7
+ Installazione: `pip install authforce-rs-labs`. Per i test: `pip install "authforce-rs-labs[dev]"`. Versioni in [CHANGELOG.md](CHANGELOG.md).
8
+
9
+ ## Cosa fa
10
+
11
+ | Area | Contenuto |
12
+ |---|---|
13
+ | Password | bcrypt (`security.hash_password`, `verify_password`). Oltre 72 byte `PasswordTooLong` alla registrazione e credenziali non valide al login |
14
+ | Access token | JWT firmato (HS256, HS384 o HS512), breve durata, tipo `access` verificato (`security.access_token_subject`) |
15
+ | Sessioni | refresh token opaco da 256 bit, salvato nel DB come SHA-256 e ruotato a ogni uso: un token già usato non vale più, anche con due refresh in parallelo. Riuso di un token già ruotato nel log e, a scelta, chiusura di tutte le sessioni. Logout, chiusura di tutte le sessioni |
16
+ | Utenti locali | registrazione, login con lo stesso errore e lo stesso tempo di risposta per email sconosciuta e password sbagliata, email normalizzate (una casella, un account), riattivazione di un account disattivato (`reactivate_on_login`, altrimenti `InactiveUser`) |
17
+ | Verifica email | token one-shot con scadenza (48 ore di default), salvato come SHA-256 |
18
+ | Google | login web (redirect e callback) e da app nativa (id_token verificato in locale con le chiavi pubbliche di Google: firma, issuer, audience, scadenza) |
19
+ | Apple | identity_token verificato (RS256, audience, issuer, `nonce` facoltativo), scambio dell'authorization code, revoca alla cancellazione dell'account |
20
+ | Login social | utente trovato per account social, poi per email (collegamento a un account locale solo se il provider garantisce l'email, altrimenti `OAuthEmailNotVerified`), altrimenti creato. Email di avviso con link "scollega" quando un login social si aggancia a un account esistente |
21
+ | Stato OAuth | parametro `state` e cookie HttpOnly contro il CSRF, confronto a tempo costante |
22
+ | Rate limit | interfaccia `RateLimiter` (il progetto passa Redis), `InMemoryRateLimiter` per un solo processo |
23
+ | FastAPI | dipendenze `current_user`, `optional_user` e `require(...)`; router base pronto per un progetto nuovo |
24
+
25
+ La configurazione rifiuta un segreto JWT più corto di 32 caratteri e un algoritmo fuori da HS256, HS384, HS512. Gli errori (`authforce.errors`) non contengono testi per l'utente: il progetto li traduce nella propria lingua. La libreria scrive nel logger `authforce` solo gli eventi di sicurezza (riuso di un refresh token), mai token o email.
26
+
27
+ ## Progetto nuovo
28
+
29
+ ```python
30
+ from datetime import timedelta
31
+ from sqlalchemy.orm import DeclarativeBase
32
+ from authforce import (AuthConfig, AuthModels, AuthService, CredentialsMixin,
33
+ EmailVerificationMixin, OAuthAccountMixin, SessionMixin, UserMixin)
34
+ from authforce.router import build_auth_router
35
+
36
+ class Base(DeclarativeBase): ...
37
+
38
+ class User(Base, UserMixin):
39
+ __tablename__ = "users"
40
+
41
+ class Credentials(Base, CredentialsMixin):
42
+ __tablename__ = "credentials"
43
+
44
+ class OAuthAccount(Base, OAuthAccountMixin):
45
+ __tablename__ = "oauth_accounts"
46
+
47
+ class Session(Base, SessionMixin):
48
+ __tablename__ = "sessions"
49
+
50
+ class EmailVerification(Base, EmailVerificationMixin):
51
+ __tablename__ = "email_verifications"
52
+
53
+ auth = AuthService(
54
+ AuthConfig(jwt_secret_key=SECRET, access_token_ttl=timedelta(minutes=30),
55
+ accept_plain_stored_tokens=False), # progetto nuovo: nessuna riga in chiaro da accettare
56
+ AuthModels(User, Credentials, OAuthAccount, Session, EmailVerification),
57
+ )
58
+ app.include_router(
59
+ build_auth_router(auth, get_session, user_response=UserOut, rate_limiter=redis_limiter,
60
+ send_verification_email=send_email),
61
+ prefix="/api/v1/auth",
62
+ )
63
+ ```
64
+
65
+ Con uno schema Postgres, ogni tabella collegata agli utenti indica la chiave esterna: `__auth_user_fk__ = "app_auth.users.id"`. Le tabelle si creano con le migrazioni del progetto (alembic autogenerate le vede dai mixin). Con `normalize_emails` conviene un indice funzionale su `lower(email)` se la tabella è grande.
66
+
67
+ ## Progetto con regole proprie
68
+
69
+ Il progetto scrive le sue rotte e chiama i metodi di `AuthService`. I metodi che non chiudono un login (`create_local_user`, `login_with_oauth`) fanno solo flush, così il progetto aggiunge le sue righe nella stessa transazione prima di `start_session`, che fa il commit.
70
+
71
+ ```python
72
+ user = await auth.create_local_user(db, email, password, username=username)
73
+ await apply_referral(db, user) # logica del progetto
74
+ tokens = await auth.start_session(db, user, ip, user_agent)
75
+ token = await auth.create_email_verification(db, user)
76
+ send_verification_email.delay(user.email, token) # logica del progetto
77
+ ```
78
+
79
+ Esempio completo: PitQuiz, in `BE/app/core/auth.py` (configurazione e modelli esistenti, senza migrazioni) e `BE/app/api/v1/auth/service/` (inviti, sponsor, email, classifiche).
80
+
81
+ ## Scelte di sicurezza e come cambiarle
82
+
83
+ Tutte in `AuthConfig`.
84
+
85
+ - `hash_stored_tokens` (acceso). Nel database ci sono gli hash dei refresh token e dei token di verifica: chi legge il database non apre sessioni. Il codice del progetto che confronta la colonna con il token del client passa da `security.hash_token`.
86
+ - `accept_plain_stored_tokens` (acceso). Per chi ha attivato l'hash dopo: le righe in chiaro restano valide finché scadono o vengono ruotate. Un valore con la forma di un hash non viene mai cercato in chiaro. Spegnerlo dopo `refresh_token_ttl` dal deploy, o subito in un progetto nuovo.
87
+ - `revoke_all_on_refresh_reuse` (spento). Un refresh token già ruotato presentato di nuovo è un token copiato oppure un client che ha perso la risposta. Acceso chiude tutte le sessioni dell'utente (OAuth 2.1); spento risponde solo `InvalidSession` e scrive nel log.
88
+ - `normalize_emails` (acceso). Minuscole e senza spazi ai bordi, anche nella ricerca sulle righe scritte prima.
89
+ - Dopo un cambio password chiamare `revoke_all_sessions` e aprire una sessione nuova: la libreria non lo fa da sola perché il progetto decide se tenere viva la sessione corrente.
90
+ - Gli access token restano validi fino alla scadenza anche dopo `revoke_all_sessions`: tenere `access_token_ttl` corto (15-30 minuti).
91
+ - IP del client per il rate limit e le sessioni: dietro un reverse proxy il server ASGI deve leggere `X-Forwarded-For` solo dai proxy fidati (uvicorn: `--proxy-headers --forwarded-allow-ips=<reti del proxy>`, mai `*`). In alternativa `build_auth_router(client_ip=header_client_ip("CF-Connecting-IP"))` se il proxy sovrascrive sempre quell'header ed è l'unico a raggiungere l'applicazione.
92
+ - Google da app nativa: `GoogleOAuth(native_client_ids=(...))` è obbligatorio, l'id_token si verifica in locale (JWKS di Google, cache delle chiavi per processo). `id_token_verifier="tokeninfo"` chiede a Google a ogni login.
93
+
94
+ ## Test e lint
95
+
96
+ ```
97
+ pip install -e ".[dev]"
98
+ pytest -q # SQLite in memoria, Google e Apple simulati
99
+ ruff check authforce tests
100
+ ```
101
+
102
+ ## Pubblicazione
103
+
104
+ Versione in `pyproject.toml` e `authforce/__init__.py`, voce nel CHANGELOG, poi da un ambiente separato da quello del progetto (twine porta dipendenze che non devono finire nella venv dell'applicazione):
105
+
106
+ ```
107
+ python -m venv /tmp/authforce-build && source /tmp/authforce-build/bin/activate
108
+ pip install build twine
109
+ cd libs/authforce && rm -rf dist && python -m build && twine check dist/*
110
+ twine upload --repository testpypi dist/* # prova su test.pypi.org
111
+ twine upload dist/* # PyPI
112
+ ```
113
+
114
+ Credenziali: token API di PyPI (`__token__` come utente), mai la password. Dopo la pubblicazione, un tag git `authforce-v0.2.0`.
@@ -0,0 +1,27 @@
1
+ """authforce: autenticazione riusabile per backend FastAPI e SQLAlchemy async.
2
+
3
+ Parti generiche e di sicurezza del login. Le regole di un progetto (inviti,
4
+ email, profilo, statistiche) restano nel progetto e chiamano questi metodi.
5
+ """
6
+ from authforce import errors, oauth_state, security
7
+ from authforce.config import AuthConfig
8
+ from authforce.dependencies import AuthDependencies, http_error
9
+ from authforce.models import (
10
+ AuthModels,
11
+ CredentialsMixin,
12
+ EmailVerificationMixin,
13
+ OAuthAccountMixin,
14
+ SessionMixin,
15
+ UserMixin,
16
+ )
17
+ from authforce.rate_limit import InMemoryRateLimiter, NoRateLimit, RateLimiter
18
+ from authforce.service import AuthService, OAuthLoginResult, OAuthProfile, TokenPair, UnlinkResult
19
+
20
+ __version__ = "0.2.0"
21
+
22
+ __all__ = [
23
+ "AuthConfig", "AuthDependencies", "AuthModels", "AuthService", "CredentialsMixin",
24
+ "EmailVerificationMixin", "InMemoryRateLimiter", "NoRateLimit", "OAuthAccountMixin",
25
+ "OAuthLoginResult", "OAuthProfile", "RateLimiter", "SessionMixin", "TokenPair", "UnlinkResult", "UserMixin",
26
+ "__version__", "errors", "http_error", "oauth_state", "security",
27
+ ]
@@ -0,0 +1,59 @@
1
+ """Configurazione della libreria. Un'istanza per applicazione, costruita dalle
2
+ impostazioni del progetto (variabili d'ambiente, file .env)."""
3
+ from dataclasses import dataclass, field
4
+ from datetime import timedelta
5
+
6
+ MIN_SECRET_LENGTH = 32
7
+ # Algoritmi a segreto condiviso: jwt_secret_key e' una stringa, non una chiave
8
+ # asimmetrica. Un valore fuori lista (per esempio "none") non parte.
9
+ ALLOWED_JWT_ALGORITHMS = ("HS256", "HS384", "HS512")
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AuthConfig:
14
+ jwt_secret_key: str
15
+ jwt_algorithm: str = "HS256"
16
+ access_token_ttl: timedelta = timedelta(minutes=30)
17
+ refresh_token_ttl: timedelta = timedelta(days=30)
18
+ email_verification_ttl: timedelta = timedelta(hours=48)
19
+ # Validita' del link "non sei stato tu? scollega" mandato quando un login
20
+ # social si collega a un account esistente.
21
+ unlink_token_ttl: timedelta = timedelta(days=7)
22
+ # Un login riuscito riattiva un account disattivato dall'utente stesso.
23
+ reactivate_on_login: bool = True
24
+ # Valori di auth_provider: account solo locale, e locale piu' social.
25
+ local_provider: str = "local"
26
+ linked_provider: str = "both"
27
+ # Refresh token e token di verifica email salvati come SHA-256: una copia
28
+ # del database non basta per aprire una sessione. Il valore in chiaro
29
+ # viaggia solo verso il client.
30
+ hash_stored_tokens: bool = True
31
+ # Transizione per i progetti che avevano i token in chiaro: la ricerca
32
+ # accetta anche il valore non hashato finche' le vecchie sessioni non
33
+ # scadono o vengono ruotate. Un valore con la forma di un hash non viene
34
+ # mai cercato in chiaro. Da spegnere dopo refresh_token_ttl.
35
+ accept_plain_stored_tokens: bool = True
36
+ # Un refresh token gia' ruotato che viene presentato di nuovo indica un
37
+ # token copiato (o un client che ha perso la risposta). Con True chiude
38
+ # tutte le sessioni dell'utente, come consiglia OAuth 2.1. Con False
39
+ # risponde solo InvalidSession, piu' tollerante con i client che fanno due
40
+ # refresh in parallelo.
41
+ revoke_all_on_refresh_reuse: bool = False
42
+ # Email confrontate senza distinguere maiuscole e spazi ai bordi: una
43
+ # stessa casella non puo' diventare due account.
44
+ normalize_emails: bool = True
45
+ extra: dict = field(default_factory=dict)
46
+
47
+ def __post_init__(self) -> None:
48
+ # Fail-closed: con un segreto vuoto o corto i token sarebbero
49
+ # falsificabili. Meglio un avvio fallito.
50
+ if len(self.jwt_secret_key or "") < MIN_SECRET_LENGTH:
51
+ raise ValueError(
52
+ f"jwt_secret_key assente o troppo corta (minimo {MIN_SECRET_LENGTH} caratteri)"
53
+ )
54
+ if self.jwt_algorithm not in ALLOWED_JWT_ALGORITHMS:
55
+ raise ValueError(f"jwt_algorithm non ammesso: {self.jwt_algorithm!r} (ammessi {ALLOWED_JWT_ALGORITHMS})")
56
+
57
+ @property
58
+ def access_token_ttl_seconds(self) -> int:
59
+ return int(self.access_token_ttl.total_seconds())
@@ -0,0 +1,78 @@
1
+ """
2
+ Dipendenze FastAPI per le rotte protette, generate per un AuthService e la
3
+ dipendenza che fornisce la sessione DB del progetto.
4
+
5
+ deps = AuthDependencies(auth, get_session)
6
+
7
+ @router.get("/me")
8
+ async def me(user = Depends(deps.current_user)): ...
9
+
10
+ Messaggi in inglese di default; `messages` li sostituisce per codice
11
+ d'errore (errors.*.code).
12
+ """
13
+ from collections.abc import Callable
14
+
15
+ from fastapi import Depends, HTTPException, status
16
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
17
+ from sqlalchemy.ext.asyncio import AsyncSession
18
+
19
+ from authforce.errors import AuthError
20
+ from authforce.service import AuthService
21
+
22
+ DEFAULT_MESSAGES = {
23
+ "invalid_token": "Invalid or expired token.",
24
+ "expired_token": "Token expired.",
25
+ "user_not_found": "User not found.",
26
+ "inactive_user": "Account disabled.",
27
+ "forbidden": "Not allowed.",
28
+ }
29
+
30
+
31
+ def http_error(error: AuthError, messages: dict | None = None) -> HTTPException:
32
+ """HTTPException dell'errore; 401 con WWW-Authenticate: Bearer."""
33
+ detail = (messages or {}).get(error.code) or DEFAULT_MESSAGES.get(error.code) or error.code
34
+ headers = {"WWW-Authenticate": "Bearer"} if error.status_code == status.HTTP_401_UNAUTHORIZED else None
35
+ return HTTPException(status_code=error.status_code, detail=detail, headers=headers)
36
+
37
+
38
+ class AuthDependencies:
39
+ def __init__(self, auth: AuthService, get_session: Callable, messages: dict | None = None):
40
+ self.auth = auth
41
+ self.messages = messages or {}
42
+ bearer = HTTPBearer()
43
+ optional_bearer = HTTPBearer(auto_error=False)
44
+
45
+ async def current_user(
46
+ credentials: HTTPAuthorizationCredentials = Depends(bearer),
47
+ db: AsyncSession = Depends(get_session),
48
+ ):
49
+ try:
50
+ return await auth.user_from_access_token(db, credentials.credentials)
51
+ except AuthError as exc:
52
+ raise http_error(exc, self.messages) from exc
53
+
54
+ async def optional_user(
55
+ credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
56
+ db: AsyncSession = Depends(get_session),
57
+ ):
58
+ if credentials is None:
59
+ return None
60
+ try:
61
+ return await auth.user_from_access_token(db, credentials.credentials)
62
+ except AuthError:
63
+ return None
64
+
65
+ self.current_user = current_user
66
+ self.optional_user = optional_user
67
+
68
+ def require(self, predicate: Callable[[object], bool], code: str = "forbidden"):
69
+ """Utente autenticato che soddisfa `predicate` (es. admin), altrimenti 403."""
70
+ current_user = self.current_user
71
+
72
+ async def dependency(user=Depends(current_user)):
73
+ if not predicate(user):
74
+ raise HTTPException(status.HTTP_403_FORBIDDEN,
75
+ detail=self.messages.get(code) or DEFAULT_MESSAGES.get(code, code))
76
+ return user
77
+
78
+ return dependency
@@ -0,0 +1,78 @@
1
+ """Errori della libreria. Non contengono testi per l'utente: il progetto li
2
+ traduce in risposte HTTP con i propri messaggi e la propria lingua
3
+ (`status_code` e' il codice suggerito)."""
4
+
5
+
6
+ class AuthError(Exception):
7
+ status_code = 400
8
+ code = "auth_error"
9
+
10
+
11
+ class EmailAlreadyRegistered(AuthError):
12
+ status_code = 409
13
+ code = "email_already_registered"
14
+
15
+
16
+ class PasswordTooLong(AuthError):
17
+ """bcrypt usa al massimo 72 byte: una password piu' lunga verrebbe troncata."""
18
+ status_code = 400
19
+ code = "password_too_long"
20
+
21
+
22
+ class InvalidCredentials(AuthError):
23
+ status_code = 401
24
+ code = "invalid_credentials"
25
+
26
+
27
+ class InvalidToken(AuthError):
28
+ """Access token assente, malformato, firmato male o di tipo sbagliato."""
29
+ status_code = 401
30
+ code = "invalid_token"
31
+
32
+
33
+ class ExpiredToken(InvalidToken):
34
+ code = "expired_token"
35
+
36
+
37
+ class InvalidSession(AuthError):
38
+ """Refresh token sconosciuto, revocato o scaduto."""
39
+ status_code = 401
40
+ code = "invalid_session"
41
+
42
+
43
+ class UserNotFound(AuthError):
44
+ status_code = 404
45
+ code = "user_not_found"
46
+
47
+
48
+ class InactiveUser(AuthError):
49
+ status_code = 403
50
+ code = "inactive_user"
51
+
52
+
53
+ class InvalidVerificationToken(AuthError):
54
+ status_code = 400
55
+ code = "invalid_verification_token"
56
+
57
+
58
+ class OAuthError(AuthError):
59
+ """Token o codice del provider rifiutato."""
60
+ status_code = 401
61
+ code = "oauth_error"
62
+
63
+
64
+ class OAuthEmailNotVerified(AuthError):
65
+ """Il provider non garantisce l'email: non si collega a un account esistente."""
66
+ status_code = 403
67
+ code = "oauth_email_not_verified"
68
+
69
+
70
+ class OAuthEmailMissing(AuthError):
71
+ """Primo login social senza email (Apple la manda solo la prima volta)."""
72
+ status_code = 400
73
+ code = "oauth_email_missing"
74
+
75
+
76
+ class ProviderNotConfigured(AuthError):
77
+ status_code = 500
78
+ code = "provider_not_configured"
@@ -0,0 +1,105 @@
1
+ """
2
+ Modelli dell'autenticazione.
3
+
4
+ La libreria non crea tabelle da sola. Il progetto le dichiara sulla propria
5
+ Base SQLAlchemy e le passa ad AuthModels:
6
+
7
+ - progetto nuovo: classi che ereditano dai mixin qui sotto, con tabella e
8
+ schema a scelta;
9
+ - progetto esistente: le proprie classi, purche' abbiano gli stessi attributi
10
+ dei mixin (PitQuiz passa i modelli di app_auth senza cambiarli).
11
+
12
+ Esempio:
13
+
14
+ class User(Base, UserMixin):
15
+ __tablename__ = "users"
16
+
17
+ class Session(Base, SessionMixin):
18
+ __tablename__ = "user_sessions"
19
+ __auth_user_fk__ = "users.id"
20
+
21
+ Campi profilo facoltativi sull'utente (full_name, avatar_url): se il modello
22
+ li ha, i login social li riempiono quando sono vuoti.
23
+
24
+ `session_token` ed `email_verification.token` contengono l'hash SHA-256 del
25
+ token dato al client (64 caratteri esadecimali), vedi AuthConfig.hash_stored_tokens.
26
+ """
27
+ import uuid
28
+ from dataclasses import dataclass
29
+ from datetime import UTC, datetime
30
+
31
+ from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint, Uuid
32
+ from sqlalchemy.orm import Mapped, declared_attr, mapped_column
33
+
34
+
35
+ def _now() -> datetime:
36
+ return datetime.now(UTC)
37
+
38
+
39
+ class _UserFK:
40
+ # "<tabella>.id" o "<schema>.<tabella>.id" della tabella utenti.
41
+ __auth_user_fk__ = "users.id"
42
+
43
+ @declared_attr
44
+ def user_id(cls) -> Mapped[uuid.UUID]:
45
+ return mapped_column(
46
+ Uuid, ForeignKey(cls.__auth_user_fk__, ondelete="CASCADE"), nullable=False, index=True,
47
+ )
48
+
49
+
50
+ class UserMixin:
51
+ id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
52
+ email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
53
+ auth_provider: Mapped[str] = mapped_column(String(20), nullable=False, default="local")
54
+ is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
55
+ is_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
56
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
57
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
58
+
59
+
60
+ class CredentialsMixin(_UserFK):
61
+ id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
62
+ hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
63
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
64
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
65
+
66
+
67
+ class OAuthAccountMixin(_UserFK):
68
+ @declared_attr.directive
69
+ def __table_args__(cls):
70
+ return (UniqueConstraint("provider", "provider_user_id"),)
71
+
72
+ id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
73
+ provider: Mapped[str] = mapped_column(String(20), nullable=False)
74
+ provider_user_id: Mapped[str] = mapped_column(String(255), nullable=False)
75
+ # Apple: serve per revocare l'accesso alla cancellazione dell'account.
76
+ provider_refresh_token: Mapped[str | None] = mapped_column(Text)
77
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
78
+
79
+
80
+ class SessionMixin(_UserFK):
81
+ id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
82
+ session_token: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
83
+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
84
+ is_revoked: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
85
+ ip_address: Mapped[str | None] = mapped_column(String(45))
86
+ user_agent: Mapped[str | None] = mapped_column(Text)
87
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
88
+
89
+
90
+ class EmailVerificationMixin(_UserFK):
91
+ id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
92
+ token: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
93
+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
94
+ consumed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
95
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class AuthModels:
100
+ """Le classi ORM che la libreria legge e scrive."""
101
+ user: type
102
+ credentials: type
103
+ oauth_account: type
104
+ session: type
105
+ email_verification: type