01AperçuOverview
Le template fournit une base d'authentification complète pour une API Django REST
Framework : modèle User personnalisé avec UserProfile,
jetons JWT SimpleJWT, et configuration pilotée par variables d'environnement.
The template provides a complete authentication base for a Django REST Framework
API: a custom User model with UserProfile, SimpleJWT
tokens, and environment-driven configuration.
- Modèle utilisateur personnalisé et profil séparéCustom user model and separate profile
- JWT avec refresh et blacklist pour le logoutJWT with refresh and blacklist on logout
- Inscription, connexion, refresh, logout, mot de passe oublié et resetRegister, login, refresh, logout, forgot and reset password
- Script d'installation et
.env.examplefournisInstall script and.env.exampleincluded
02PrérequisRequirements
- Python 3 (compatible Django 5.2)Python 3 (Django 5.2 compatible)
Django>=5.2,<6.0djangorestframework>=3.15,<4.0djangorestframework-simplejwt>=5.3,<6.0django-cors-headers>=4.4,<5.0,python-dotenv>=1.0,Pillow>=11.0
03Démarrage rapideQuick start
Récupérer le dépôt puis lancer le script d'installation : Clone the repository, then run the install script:
git clone https://github.com/yoshi-labs/django_user_auth_template.git
cd django_user_auth_template
cp .env.example .env # renseigner SECRET_KEY
chmod +x ./install.sh
./install.sh
Le script crée la base, applique les migrations et lance
collectstatic. Équivalent manuel :
The script creates the database, runs migrations and
collectstatic. Manual equivalent:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver
django-insecure-.
SECRET_KEY is required. The server refuses to start if the key
is missing, shorter than 50 characters, or still prefixed with
django-insecure-.
04ConfigurationConfiguration
Tout passe par .env, chargé automatiquement depuis la racine du
dépôt ; les variables déjà présentes dans l'environnement restent prioritaires.
Everything goes through .env, loaded automatically from the repository
root; variables already present in the environment take precedence.
| VariableVariable | DéfautDefault | RôlePurpose |
|---|---|---|
| SECRET_KEY | — | Obligatoire, ≥ 50 caractèresRequired, ≥ 50 characters |
| DEBUG | True | Mode développementDevelopment mode |
| ALLOWED_HOSTS | localhost,127.0.0.1 | Hôtes acceptésAllowed hosts |
| CSRF_TRUSTED_ORIGINS | localhost:8000… | Origines de confiance CSRFTrusted CSRF origins |
| CORS_ALLOWED_ORIGINS | localhost:3000 | Aucun joker acceptéNo wildcard accepted |
| DB_ENGINE / DB_NAME | sqlite3 / db.sqlite3 | Base de donnéesDatabase |
| EMAIL_* | console | Envoi des emails de resetReset email delivery |
| FRONTEND_PASSWORD_RESET_URL | localhost:3000/reset-password | Lien de reset côté frontFront-end reset link |
| PASSWORD_RESET_TIMEOUT | 86400 | Durée de validité du token (s)Reset token lifetime (s) |
| SIMPLE_JWT_ACCESS_MINUTES | 30 | Durée de l'access tokenAccess token lifetime |
| SIMPLE_JWT_REFRESH_DAYS | 7 | Durée du refresh tokenRefresh token lifetime |
| SIMPLE_JWT_ROTATE_REFRESH_TOKENS | False | Rotation à chaque refreshRotate on each refresh |
| SIMPLE_JWT_BLACKLIST_AFTER_ROTATION | True | Blacklist l'ancien refreshBlacklist the old refresh |
| THROTTLE_ANON / USER | 60/min · 1000/day | Limitation de débitRate limiting |
| THROTTLE_LOGIN / REGISTER | 5/min · 5/hour | Quotas d'authentificationAuth quotas |
| DRF_NUM_PROXIES | 0 | Proxies devant l'applicationProxies in front of the app |
| STATIC_ROOT | staticfiles | Cible de collectstaticcollectstatic target |
Référence complète et commentée : .env.example.
Full annotated reference: .env.example.
05EndpointsEndpoints
| MéthodeMethod | CheminPath | AuthAuth | DescriptionDescription |
|---|---|---|---|
| POST | /api/auth/register/ | Public | InscriptionRegister |
| POST | /api/auth/login/ | Public | Obtenir access + refreshObtain access + refresh |
| POST | /api/auth/refresh/ | Refresh | Nouvel access tokenNew access token |
| POST | /api/auth/token/refresh/ | Refresh | Alias de refreshRefresh alias |
| POST | /api/auth/logout/ | Bearer | Logout et blacklist du refreshLogout and refresh blacklist |
| POST | /api/auth/password/forgot/ | Public | Demande de réinitialisationRequest password reset |
| POST | /api/auth/password/reset/ | Token | Nouveau mot de passeSet new password |
| GET | /api/auth/me/ | Bearer | Utilisateur courantCurrent user |
| GET | /api/health/ | Public | Healthcheck de déploiementDeployment healthcheck |
06Flux d'authentificationAuthentication flow
Les durées se règlent via SIMPLE_JWT_ACCESS_MINUTES et
SIMPLE_JWT_REFRESH_DAYS. Le logout envoie le refresh token à la
blacklist pour qu'il ne puisse plus être rejoué.
Lifetimes are set with SIMPLE_JWT_ACCESS_MINUTES and
SIMPLE_JWT_REFRESH_DAYS. Logout sends the refresh token to the
blacklist so it cannot be replayed.
07Structure du projetProject structure
Django_Auth_Template/ # réglages et routage racine
auth/ # User, vues, serializers, URLs
api/ # healthcheck
install.sh # venv, migrations, collectstatic
manage.py
requirements.txt
.env.example
staticfiles/
08TestsTests
python manage.py test
09DéploiementDeployment
Avec DEBUG=False, la redirection HTTPS, les cookies sécurisés, HSTS
(60 s par défaut) et la lecture de X-Forwarded-Proto sont activés
automatiquement. Checklist :
With DEBUG=False, HTTPS redirect, secure cookies, HSTS (60 s by
default) and X-Forwarded-Proto handling are enabled automatically.
Checklist:
SECRET_KEY≥ 50 caractères, sans préfixedjango-insecure-SECRET_KEY≥ 50 characters, nodjango-insecure-prefixALLOWED_HOSTSetCSRF_TRUSTED_ORIGINSrenseignésALLOWED_HOSTSandCSRF_TRUSTED_ORIGINSsetCORS_ALLOWED_ORIGINSsans jokerCORS_ALLOWED_ORIGINSwithout wildcard- HSTS porté à
31536000une fois le HTTPS validéHSTS raised to31536000once HTTPS is validated - Cache partagé (Redis/Memcached) pour un throttling global en multi-workersShared cache (Redis/Memcached) for global throttling across workers
DRF_NUM_PROXIES= nombre de reverse proxiesnumber of reverse proxiesUSE_X_FORWARDED_PROTOdésactivé si l'app est exposée sans proxyUSE_X_FORWARDED_PROTOdisabled if the app is exposed without a proxy
10DépannageTroubleshooting
-
Démarrage refusé :
SECRET_KEYabsente, trop courte ou encore préfixéedjango-insecure-. Startup refused:SECRET_KEYmissing, too short, or stilldjango-insecure--prefixed. - Quotas de débit incohérents : le cache Django est local à chaque worker ; déclarer un cache partagé. Inconsistent rate limits: Django's cache is per worker; declare a shared cache.
-
CORS bloqué : l'origine doit figurer explicitement dans
CORS_ALLOWED_ORIGINS, les jokers sont refusés. CORS blocked: the origin must be listed inCORS_ALLOWED_ORIGINS, wildcards are rejected.
11ChangelogChangelog
v1.0.0 — version initiale publiée, licence MIT. — initial release, MIT license.