Yoshi Labs. / docs
DépôtRepo

Django Auth Template

Template Django REST minimal et prêt pour la production : utilisateur personnalisé, JWT avec refresh et blacklist, inscription, connexion, logout et réinitialisation de mot de passe. Minimal, production-ready Django REST template: custom user, JWT with refresh and blacklist, registration, login, logout and password reset.

PubliéReleased v1.0.0 Django 5.2 DRF SimpleJWT GitHub ↗

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.example fournisInstall script and .env.example included

02PrérequisRequirements

  • Python 3 (compatible Django 5.2)Python 3 (Django 5.2 compatible)
  • Django>=5.2,<6.0
  • djangorestframework>=3.15,<4.0
  • djangorestframework-simplejwt>=5.3,<6.0
  • django-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:

bash
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:

bash
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver
SECRET_KEY obligatoire. Le serveur refuse de démarrer si la clé est absente, plus courte que 50 caractères ou encore préfixée par 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

login → access 30 min + refresh 7 j → API · Bearer → access expiré → refresh → API · Bearer → logout · blacklist

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

tree
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

bash
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éfixe django-insecure-SECRET_KEY ≥ 50 characters, no django-insecure- prefix
  • ALLOWED_HOSTS et CSRF_TRUSTED_ORIGINS renseignésALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS set
  • CORS_ALLOWED_ORIGINS sans jokerCORS_ALLOWED_ORIGINS without wildcard
  • HSTS porté à 31536000 une fois le HTTPS validéHSTS raised to 31536000 once 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 proxies
  • USE_X_FORWARDED_PROTO désactivé si l'app est exposée sans proxyUSE_X_FORWARDED_PROTO disabled if the app is exposed without a proxy

10DépannageTroubleshooting

  • Démarrage refusé : SECRET_KEY absente, trop courte ou encore préfixée django-insecure-. Startup refused: SECRET_KEY missing, too short, or still django-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 in CORS_ALLOWED_ORIGINS, wildcards are rejected.

11ChangelogChangelog

v1.0.0 — version initiale publiée, licence MIT. — initial release, MIT license.