├── .gitignore ├── LICENSE ├── README.md ├── django_react_cross_origin ├── README.md ├── backend │ ├── api │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── djangocookieauth │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt └── frontend │ ├── .eslintrc.cjs │ ├── .gitignore │ ├── README.md │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── public │ └── vite.svg │ ├── src │ ├── App.jsx │ ├── assets │ │ └── react.svg │ └── main.jsx │ └── vite.config.js ├── django_react_drf_same_origin ├── README.md ├── backend │ ├── Dockerfile │ ├── api │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── djangocookieauth │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt ├── docker-compose.yml ├── frontend │ ├── .eslintrc.cjs │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── public │ │ └── vite.svg │ ├── src │ │ ├── App.jsx │ │ ├── assets │ │ │ └── react.svg │ │ └── main.jsx │ └── vite.config.js └── nginx │ ├── Dockerfile │ └── nginx.conf ├── django_react_same_origin ├── README.md ├── backend │ ├── Dockerfile │ ├── api │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── djangocookieauth │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt ├── docker-compose.yml ├── frontend │ ├── .eslintrc.cjs │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── public │ │ └── vite.svg │ ├── src │ │ ├── App.jsx │ │ ├── assets │ │ │ └── react.svg │ │ └── main.jsx │ └── vite.config.js └── nginx │ ├── Dockerfile │ └── nginx.conf └── django_react_templates ├── README.md ├── api ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py ├── djangocookieauth ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── frontend ├── .eslintrc.cjs ├── .gitignore ├── README.md ├── index.html ├── package-lock.json ├── package.json ├── public │ └── vite.svg ├── src │ ├── App.jsx │ ├── assets │ │ └── react.svg │ └── main.jsx └── vite.config.js ├── manage.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | 3 | # Created by https://www.toptal.com/developers/gitignore/api/django,pycharm+all 4 | # Edit at https://www.toptal.com/developers/gitignore?templates=django,pycharm+all 5 | 6 | ### Django ### 7 | *.log 8 | *.pot 9 | *.pyc 10 | __pycache__/ 11 | local_settings.py 12 | db.sqlite3 13 | db.sqlite3-journal 14 | media 15 | 16 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 17 | # in your Git repository. Update and uncomment the following line accordingly. 18 | # /staticfiles/ 19 | 20 | ### Django.Python Stack ### 21 | # Byte-compiled / optimized / DLL files 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | pip-wheel-metadata/ 43 | share/python-wheels/ 44 | *.egg-info/ 45 | .installed.cfg 46 | *.egg 47 | MANIFEST 48 | 49 | # PyInstaller 50 | # Usually these files are written by a python script from a template 51 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 52 | *.manifest 53 | *.spec 54 | 55 | # Installer logs 56 | pip-log.txt 57 | pip-delete-this-directory.txt 58 | 59 | # Unit test / coverage reports 60 | htmlcov/ 61 | .tox/ 62 | .nox/ 63 | .coverage 64 | .coverage.* 65 | .cache 66 | nosetests.xml 67 | coverage.xml 68 | *.cover 69 | *.py,cover 70 | .hypothesis/ 71 | .pytest_cache/ 72 | pytestdebug.log 73 | 74 | # Translations 75 | *.mo 76 | 77 | # Django stuff: 78 | 79 | # Flask stuff: 80 | instance/ 81 | .webassets-cache 82 | 83 | # Scrapy stuff: 84 | .scrapy 85 | 86 | # Sphinx documentation 87 | docs/_build/ 88 | doc/_build/ 89 | 90 | # PyBuilder 91 | target/ 92 | 93 | # Jupyter Notebook 94 | .ipynb_checkpoints 95 | 96 | # IPython 97 | profile_default/ 98 | ipython_config.py 99 | 100 | # pyenv 101 | .python-version 102 | 103 | # pipenv 104 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 105 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 106 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 107 | # install all needed dependencies. 108 | #Pipfile.lock 109 | 110 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 111 | __pypackages__/ 112 | 113 | # Celery stuff 114 | celerybeat-schedule 115 | celerybeat.pid 116 | 117 | # SageMath parsed files 118 | *.sage.py 119 | 120 | # Environments 121 | .env 122 | .venv 123 | env/ 124 | venv/ 125 | ENV/ 126 | env.bak/ 127 | venv.bak/ 128 | pythonenv* 129 | 130 | # Spyder project settings 131 | .spyderproject 132 | .spyproject 133 | 134 | # Rope project settings 135 | .ropeproject 136 | 137 | # mkdocs documentation 138 | /site 139 | 140 | # mypy 141 | .mypy_cache/ 142 | .dmypy.json 143 | dmypy.json 144 | 145 | # Pyre type checker 146 | .pyre/ 147 | 148 | # pytype static type analyzer 149 | .pytype/ 150 | 151 | # profiling data 152 | .prof 153 | 154 | ### PyCharm+all ### 155 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 156 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 157 | 158 | # User-specific stuff 159 | .idea/**/workspace.xml 160 | .idea/**/tasks.xml 161 | .idea/**/usage.statistics.xml 162 | .idea/**/dictionaries 163 | .idea/**/shelf 164 | 165 | # Generated files 166 | .idea/**/contentModel.xml 167 | 168 | # Sensitive or high-churn files 169 | .idea/**/dataSources/ 170 | .idea/**/dataSources.ids 171 | .idea/**/dataSources.local.xml 172 | .idea/**/sqlDataSources.xml 173 | .idea/**/dynamic.xml 174 | .idea/**/uiDesigner.xml 175 | .idea/**/dbnavigator.xml 176 | 177 | # Gradle 178 | .idea/**/gradle.xml 179 | .idea/**/libraries 180 | 181 | # Gradle and Maven with auto-import 182 | # When using Gradle or Maven with auto-import, you should exclude module files, 183 | # since they will be recreated, and may cause churn. Uncomment if using 184 | # auto-import. 185 | # .idea/artifacts 186 | # .idea/compiler.xml 187 | # .idea/jarRepositories.xml 188 | # .idea/modules.xml 189 | # .idea/*.iml 190 | # .idea/modules 191 | # *.iml 192 | # *.ipr 193 | 194 | # CMake 195 | cmake-build-*/ 196 | 197 | # Mongo Explorer plugin 198 | .idea/**/mongoSettings.xml 199 | 200 | # File-based project format 201 | *.iws 202 | 203 | # IntelliJ 204 | out/ 205 | 206 | # mpeltonen/sbt-idea plugin 207 | .idea_modules/ 208 | 209 | # JIRA plugin 210 | atlassian-ide-plugin.xml 211 | 212 | # Cursive Clojure plugin 213 | .idea/replstate.xml 214 | 215 | # Crashlytics plugin (for Android Studio and IntelliJ) 216 | com_crashlytics_export_strings.xml 217 | crashlytics.properties 218 | crashlytics-build.properties 219 | fabric.properties 220 | 221 | # Editor-based Rest Client 222 | .idea/httpRequests 223 | 224 | # Android studio 3.1+ serialized cache file 225 | .idea/caches/build_file_checksums.ser 226 | 227 | ### PyCharm+all Patch ### 228 | # Ignores the whole .idea folder and all .iml files 229 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 230 | 231 | .idea/ 232 | 233 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 234 | 235 | *.iml 236 | modules.xml 237 | .idea/misc.xml 238 | *.ipr 239 | 240 | # Sonarlint plugin 241 | .idea/sonarlint 242 | 243 | # End of https://www.toptal.com/developers/gitignore/api/django,pycharm+all 244 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Nik Tomazic 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django SPA Cookie Auth 2 | 3 | [https://testdriven.io/blog/django-spa-auth/](https://testdriven.io/blog/django-spa-auth/) 4 | 5 | 1. [Django + React SPA served up via Django Templates](https://github.com/duplxey/django-spa-cookie-auth/tree/master/django_react_templates) 6 | 2. [Django + React SPA (same origin)](https://github.com/duplxey/django-spa-cookie-auth/tree/master/django_react_same_origin) 7 | 3. [Django + DRF + React SPA (same origin)](https://github.com/duplxey/django-spa-cookie-auth/tree/master/django_react_drf_same_origin) 8 | 4. [Django + React SPA (cross origin)](https://github.com/duplxey/django-spa-cookie-auth/tree/master/django_react_cross_origin) 9 | -------------------------------------------------------------------------------- /django_react_cross_origin/README.md: -------------------------------------------------------------------------------- 1 | # Django + React SPA (cross origin) 2 | 3 | Cookie based authentication, frontend and backend separated, cross origin 4 | 5 | ## Getting Started 6 | 7 | Run Django: 8 | 9 | ```sh 10 | $ cd backend 11 | $ python3 -m venv venv && source venv/bin/activate 12 | (venv)$ pip install -r requirements.txt 13 | (venv)$ python manage.py migrate 14 | (venv)$ python manage.py runserver 15 | ``` 16 | 17 | Run React: 18 | 19 | ```sh 20 | $ cd frontend 21 | $ npm install 22 | $ npm run dev 23 | ``` 24 | 25 | Test at [http://localhost:5173/](http://localhost:5173/). 26 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_cross_origin/backend/api/__init__.py -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "api" 7 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_cross_origin/backend/api/migrations/__init__.py -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('csrf/', views.get_csrf, name='api-csrf'), 7 | path('login/', views.login_view, name='api-login'), 8 | path('logout/', views.logout_view, name='api-logout'), 9 | path('session/', views.session_view, name='api-session'), 10 | path('whoami/', views.whoami_view, name='api-whoami'), 11 | ] 12 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/api/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib.auth import authenticate, login, logout 4 | from django.http import JsonResponse 5 | from django.middleware.csrf import get_token 6 | from django.views.decorators.csrf import ensure_csrf_cookie 7 | from django.views.decorators.http import require_POST 8 | 9 | 10 | def get_csrf(request): 11 | response = JsonResponse({'detail': 'CSRF cookie set'}) 12 | response['X-CSRFToken'] = get_token(request) 13 | return response 14 | 15 | 16 | @require_POST 17 | def login_view(request): 18 | data = json.loads(request.body) 19 | username = data.get('username') 20 | password = data.get('password') 21 | 22 | if username is None or password is None: 23 | return JsonResponse({'detail': 'Please provide username and password.'}, status=400) 24 | 25 | user = authenticate(username=username, password=password) 26 | 27 | if user is None: 28 | return JsonResponse({'detail': 'Invalid credentials.'}, status=400) 29 | 30 | login(request, user) 31 | return JsonResponse({'detail': 'Successfully logged in.'}) 32 | 33 | 34 | def logout_view(request): 35 | if not request.user.is_authenticated: 36 | return JsonResponse({'detail': 'You\'re not logged in.'}, status=400) 37 | 38 | logout(request) 39 | return JsonResponse({'detail': 'Successfully logged out.'}) 40 | 41 | 42 | @ensure_csrf_cookie 43 | def session_view(request): 44 | if not request.user.is_authenticated: 45 | return JsonResponse({'isAuthenticated': False}) 46 | 47 | return JsonResponse({'isAuthenticated': True}) 48 | 49 | 50 | def whoami_view(request): 51 | if not request.user.is_authenticated: 52 | return JsonResponse({'isAuthenticated': False}) 53 | 54 | return JsonResponse({'username': request.user.username}) 55 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/djangocookieauth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_cross_origin/backend/djangocookieauth/__init__.py -------------------------------------------------------------------------------- /django_react_cross_origin/backend/djangocookieauth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for djangocookieauth project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/djangocookieauth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangocookieauth project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-q@3_gund87n2h1s%gt((bs9*xue+9utxjtpj1*f-&aba0w6z!g' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'api.apps.ApiConfig', 41 | 'corsheaders', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'corsheaders.middleware.CorsMiddleware', 46 | 'django.middleware.security.SecurityMiddleware', 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | ] 54 | 55 | ROOT_URLCONF = 'djangocookieauth.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'djangocookieauth.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': BASE_DIR / 'db.sqlite3', 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 120 | 121 | STATIC_URL = 'static/' 122 | 123 | # Default primary key field type 124 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 125 | 126 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 127 | 128 | CSRF_COOKIE_SAMESITE = 'Lax' 129 | SESSION_COOKIE_SAMESITE = 'Lax' 130 | CSRF_COOKIE_HTTPONLY = True 131 | SESSION_COOKIE_HTTPONLY = True 132 | CSRF_TRUSTED_ORIGINS = ['http://localhost:5173'] 133 | 134 | # PROD ONLY 135 | # CSRF_COOKIE_SECURE = True 136 | # SESSION_COOKIE_SECURE = True 137 | 138 | CORS_ALLOWED_ORIGINS = [ 139 | 'http://localhost:5173', 140 | 'http://127.0.0.1:5173', 141 | ] 142 | CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken'] 143 | CORS_ALLOW_CREDENTIALS = True 144 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/djangocookieauth/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.shortcuts import render 3 | from django.urls import path, include 4 | 5 | 6 | urlpatterns = [ 7 | path('admin/', admin.site.urls), 8 | path('api/', include('api.urls')), 9 | ] 10 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/djangocookieauth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangocookieauth project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /django_react_cross_origin/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.2.3 2 | django-cors-headers==4.2.0 3 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/README.md: -------------------------------------------------------------------------------- 1 | # React + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0" 15 | }, 16 | "devDependencies": { 17 | "@types/react": "^18.2.15", 18 | "@types/react-dom": "^18.2.7", 19 | "@vitejs/plugin-react": "^4.0.3", 20 | "eslint": "^8.45.0", 21 | "eslint-plugin-react": "^7.32.2", 22 | "eslint-plugin-react-hooks": "^4.6.0", 23 | "eslint-plugin-react-refresh": "^0.4.3", 24 | "vite": "^4.4.5" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | class App extends React.Component { 4 | 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | csrf: "", 10 | username: "", 11 | password: "", 12 | error: "", 13 | isAuthenticated: false, 14 | }; 15 | } 16 | 17 | componentDidMount = () => { 18 | this.getSession(); 19 | } 20 | 21 | getCSRF = () => { 22 | fetch("http://localhost:8000/api/csrf/", { 23 | credentials: "include", 24 | }) 25 | .then((res) => { 26 | let csrfToken = res.headers.get("X-CSRFToken"); 27 | this.setState({csrf: csrfToken}); 28 | console.log(csrfToken); 29 | }) 30 | .catch((err) => { 31 | console.log(err); 32 | }); 33 | } 34 | 35 | getSession = () => { 36 | fetch("http://localhost:8000/api/session/", { 37 | credentials: "include", 38 | }) 39 | .then((res) => res.json()) 40 | .then((data) => { 41 | console.log(data); 42 | if (data.isAuthenticated) { 43 | this.setState({isAuthenticated: true}); 44 | } else { 45 | this.setState({isAuthenticated: false}); 46 | this.getCSRF(); 47 | } 48 | }) 49 | .catch((err) => { 50 | console.log(err); 51 | }); 52 | } 53 | 54 | whoami = () => { 55 | fetch("http://localhost:8000/api/whoami/", { 56 | headers: { 57 | "Content-Type": "application/json", 58 | }, 59 | credentials: "include", 60 | }) 61 | .then((res) => res.json()) 62 | .then((data) => { 63 | console.log("You are logged in as: " + data.username); 64 | }) 65 | .catch((err) => { 66 | console.log(err); 67 | }); 68 | } 69 | 70 | handlePasswordChange = (event) => { 71 | this.setState({password: event.target.value}); 72 | } 73 | 74 | handleUserNameChange = (event) => { 75 | this.setState({username: event.target.value}); 76 | } 77 | 78 | isResponseOk(response) { 79 | if (response.status >= 200 && response.status <= 299) { 80 | return response.json(); 81 | } else { 82 | throw Error(response.statusText); 83 | } 84 | } 85 | 86 | login = (event) => { 87 | event.preventDefault(); 88 | fetch("http://localhost:8000/api/login/", { 89 | method: "POST", 90 | headers: { 91 | "Content-Type": "application/json", 92 | "X-CSRFToken": this.state.csrf, 93 | }, 94 | credentials: "include", 95 | body: JSON.stringify({username: this.state.username, password: this.state.password}), 96 | }) 97 | .then(this.isResponseOk) 98 | .then((data) => { 99 | console.log(data); 100 | this.setState({isAuthenticated: true, username: "", password: "", error: ""}); 101 | }) 102 | .catch((err) => { 103 | console.log(err); 104 | this.setState({error: "Wrong username or password."}); 105 | }); 106 | } 107 | 108 | logout = () => { 109 | fetch("http://localhost:8000/api/logout", { 110 | credentials: "include", 111 | }) 112 | .then(this.isResponseOk) 113 | .then((data) => { 114 | console.log(data); 115 | this.setState({isAuthenticated: false}); 116 | this.getCSRF(); 117 | }) 118 | .catch((err) => { 119 | console.log(err); 120 | }); 121 | }; 122 | 123 | render() { 124 | if (!this.state.isAuthenticated) { 125 | return ( 126 |
127 |

React Cookie Auth

128 |
129 |

Login

130 |
131 |
132 | 133 | 134 |
135 |
136 | 137 | 138 |
139 | {this.state.error && 140 | 141 | {this.state.error} 142 | 143 | } 144 |
145 |
146 | 147 |
148 |
149 | ); 150 | } 151 | return ( 152 |
153 |

React Cookie Auth

154 |

You are logged in!

155 | 156 | 157 |
158 | ) 159 | } 160 | } 161 | 162 | export default App; 163 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | 5 | ReactDOM.createRoot(document.getElementById('root')).render( 6 | 7 | 8 | , 9 | ) 10 | -------------------------------------------------------------------------------- /django_react_cross_origin/frontend/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/README.md: -------------------------------------------------------------------------------- 1 | # Django + DRF + React SPA (same origin) 2 | 3 | Cookie based authentication, Django REST Framework, frontend and backend separated (same origin) 4 | 5 | ## Getting Started 6 | 7 | ```sh 8 | $ docker-compose up -d --build 9 | $ docker-compose exec backend python manage.py makemigrations 10 | $ docker-compose exec backend python manage.py migrate 11 | $ docker-compose exec backend python manage.py createsuperuser 12 | ``` 13 | 14 | [http://localhost:81/](http://localhost:81/) 15 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/Dockerfile: -------------------------------------------------------------------------------- 1 | # pull official base image 2 | FROM python:3.11.4-slim-buster 3 | 4 | # set working directory 5 | WORKDIR /usr/src/app 6 | 7 | # set environment variables 8 | ENV PYTHONDONTWRITEBYTECODE 1 9 | ENV PYTHONUNBUFFERED 1 10 | 11 | # install dependencies 12 | RUN pip install --upgrade pip 13 | COPY ./requirements.txt . 14 | RUN pip install -r requirements.txt 15 | 16 | # add app 17 | COPY . . 18 | 19 | # start app 20 | CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] 21 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_drf_same_origin/backend/api/__init__.py -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "api" 7 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_drf_same_origin/backend/api/migrations/__init__.py -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('csrf/', views.get_csrf, name='api-csrf'), 7 | path('login/', views.login_view, name='api-login'), 8 | path('logout/', views.logout_view, name='api-logout'), 9 | path('session/', views.SessionView.as_view(), name='api-session'), 10 | path('whoami/', views.WhoAmIView.as_view(), name='api-whoami'), 11 | ] 12 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/api/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib.auth import authenticate, login, logout 4 | from django.http import JsonResponse 5 | from django.middleware.csrf import get_token 6 | from django.views.decorators.http import require_POST 7 | from rest_framework.authentication import SessionAuthentication, BasicAuthentication 8 | from rest_framework.permissions import IsAuthenticated 9 | from rest_framework.views import APIView 10 | 11 | 12 | def get_csrf(request): 13 | response = JsonResponse({'detail': 'CSRF cookie set'}) 14 | response['X-CSRFToken'] = get_token(request) 15 | return response 16 | 17 | 18 | @require_POST 19 | def login_view(request): 20 | data = json.loads(request.body) 21 | username = data.get('username') 22 | password = data.get('password') 23 | 24 | if username is None or password is None: 25 | return JsonResponse({'detail': 'Please provide username and password.'}, status=400) 26 | 27 | user = authenticate(username=username, password=password) 28 | 29 | if user is None: 30 | return JsonResponse({'detail': 'Invalid credentials.'}, status=400) 31 | 32 | login(request, user) 33 | return JsonResponse({'detail': 'Successfully logged in.'}) 34 | 35 | 36 | def logout_view(request): 37 | if not request.user.is_authenticated: 38 | return JsonResponse({'detail': 'You\'re not logged in.'}, status=400) 39 | 40 | logout(request) 41 | return JsonResponse({'detail': 'Successfully logged out.'}) 42 | 43 | 44 | class SessionView(APIView): 45 | authentication_classes = [SessionAuthentication, BasicAuthentication] 46 | permission_classes = [IsAuthenticated] 47 | 48 | @staticmethod 49 | def get(request, format=None): 50 | return JsonResponse({'isAuthenticated': True}) 51 | 52 | 53 | class WhoAmIView(APIView): 54 | authentication_classes = [SessionAuthentication, BasicAuthentication] 55 | permission_classes = [IsAuthenticated] 56 | 57 | @staticmethod 58 | def get(request, format=None): 59 | return JsonResponse({'username': request.user.username}) 60 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/djangocookieauth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_drf_same_origin/backend/djangocookieauth/__init__.py -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/djangocookieauth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for djangocookieauth project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/djangocookieauth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangocookieauth project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-+fnpp%po$npxzguv^e@&bt*1rjz$27uqzfjeh%!4d90-(#8e3b' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'api.apps.ApiConfig', 41 | 'rest_framework', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'djangocookieauth.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'djangocookieauth.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 119 | 120 | STATIC_URL = 'static/' 121 | 122 | # Default primary key field type 123 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 124 | 125 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 126 | 127 | CSRF_COOKIE_SAMESITE = 'Strict' 128 | SESSION_COOKIE_SAMESITE = 'Strict' 129 | CSRF_COOKIE_HTTPONLY = True 130 | SESSION_COOKIE_HTTPONLY = True 131 | CSRF_TRUSTED_ORIGINS = ['http://localhost:81'] 132 | 133 | # PROD ONLY 134 | # CSRF_COOKIE_SECURE = True 135 | # SESSION_COOKIE_SECURE = True 136 | 137 | REST_FRAMEWORK = { 138 | 'DEFAULT_RENDERER_CLASSES': [ 139 | 'rest_framework.renderers.JSONRenderer', 140 | ], 141 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 142 | 'rest_framework.authentication.SessionAuthentication', 143 | ], 144 | } 145 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/djangocookieauth/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.shortcuts import render 3 | from django.urls import path, include 4 | 5 | 6 | urlpatterns = [ 7 | path('admin/', admin.site.urls), 8 | path('api/', include('api.urls')), 9 | ] 10 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/djangocookieauth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangocookieauth project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.2.3 2 | djangorestframework==3.14.0 3 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | 5 | backend: 6 | build: ./backend 7 | volumes: 8 | - ./backend:/usr/src/app 9 | expose: 10 | - 8000 11 | 12 | frontend: 13 | stdin_open: true 14 | build: ./frontend 15 | volumes: 16 | - ./frontend:/usr/src/app 17 | - /usr/src/app/node_modules 18 | expose: 19 | - 5173 20 | environment: 21 | - NODE_ENV=development 22 | depends_on: 23 | - backend 24 | 25 | reverse_proxy: 26 | build: ./nginx 27 | ports: 28 | - 81:80 29 | depends_on: 30 | - backend 31 | - frontend 32 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/Dockerfile: -------------------------------------------------------------------------------- 1 | # pull official base image 2 | FROM node:18-slim 3 | 4 | # set working directory 5 | WORKDIR /usr/src/app 6 | 7 | # add `/usr/src/app/node_modules/.bin` to $PATH 8 | ENV PATH /usr/src/app/node_modules/.bin:$PATH 9 | 10 | # install and cache app dependencies 11 | COPY package.json . 12 | COPY package-lock.json . 13 | RUN npm ci 14 | 15 | # start app 16 | CMD ["vite", "--host"] 17 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/README.md: -------------------------------------------------------------------------------- 1 | # React + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0" 15 | }, 16 | "devDependencies": { 17 | "@types/react": "^18.2.15", 18 | "@types/react-dom": "^18.2.7", 19 | "@vitejs/plugin-react": "^4.0.3", 20 | "eslint": "^8.45.0", 21 | "eslint-plugin-react": "^7.32.2", 22 | "eslint-plugin-react-hooks": "^4.6.0", 23 | "eslint-plugin-react-refresh": "^0.4.3", 24 | "vite": "^4.4.5" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | class App extends React.Component { 4 | 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | csrf: "", 10 | username: "", 11 | password: "", 12 | error: "", 13 | isAuthenticated: false, 14 | }; 15 | } 16 | 17 | componentDidMount = () => { 18 | this.getSession(); 19 | } 20 | 21 | getCSRF = () => { 22 | fetch("/api/csrf/", { 23 | credentials: "same-origin", 24 | }) 25 | .then((res) => { 26 | let csrfToken = res.headers.get("X-CSRFToken"); 27 | this.setState({csrf: csrfToken}); 28 | console.log(csrfToken); 29 | }) 30 | .catch((err) => { 31 | console.log(err); 32 | }); 33 | } 34 | 35 | getSession = () => { 36 | fetch("/api/session/", { 37 | credentials: "same-origin", 38 | }) 39 | .then((res) => res.json()) 40 | .then((data) => { 41 | console.log(data); 42 | if (data.isAuthenticated) { 43 | this.setState({isAuthenticated: true}); 44 | } else { 45 | this.setState({isAuthenticated: false}); 46 | this.getCSRF(); 47 | } 48 | }) 49 | .catch((err) => { 50 | console.log(err); 51 | }); 52 | } 53 | 54 | whoami = () => { 55 | fetch("/api/whoami/", { 56 | headers: { 57 | "Content-Type": "application/json", 58 | }, 59 | credentials: "same-origin", 60 | }) 61 | .then((res) => res.json()) 62 | .then((data) => { 63 | console.log("You are logged in as: " + data.username); 64 | }) 65 | .catch((err) => { 66 | console.log(err); 67 | }); 68 | } 69 | 70 | handlePasswordChange = (event) => { 71 | this.setState({password: event.target.value}); 72 | } 73 | 74 | handleUserNameChange = (event) => { 75 | this.setState({username: event.target.value}); 76 | } 77 | 78 | isResponseOk(response) { 79 | if (response.status >= 200 && response.status <= 299) { 80 | return response.json(); 81 | } else { 82 | throw Error(response.statusText); 83 | } 84 | } 85 | 86 | login = (event) => { 87 | event.preventDefault(); 88 | fetch("/api/login/", { 89 | method: "POST", 90 | headers: { 91 | "Content-Type": "application/json", 92 | "X-CSRFToken": this.state.csrf, 93 | }, 94 | credentials: "same-origin", 95 | body: JSON.stringify({username: this.state.username, password: this.state.password}), 96 | }) 97 | .then(this.isResponseOk) 98 | .then((data) => { 99 | console.log(data); 100 | this.setState({isAuthenticated: true, username: "", password: "", error: ""}); 101 | }) 102 | .catch((err) => { 103 | console.log(err); 104 | this.setState({error: "Wrong username or password."}); 105 | }); 106 | } 107 | 108 | logout = () => { 109 | fetch("/api/logout", { 110 | credentials: "same-origin", 111 | }) 112 | .then(this.isResponseOk) 113 | .then((data) => { 114 | console.log(data); 115 | this.setState({isAuthenticated: false}); 116 | this.getCSRF(); 117 | }) 118 | .catch((err) => { 119 | console.log(err); 120 | }); 121 | }; 122 | 123 | render() { 124 | if (!this.state.isAuthenticated) { 125 | return ( 126 |
127 |

React Cookie Auth

128 |
129 |

Login

130 |
131 |
132 | 133 | 134 |
135 |
136 | 137 | 138 |
139 | {this.state.error && 140 | 141 | {this.state.error} 142 | 143 | } 144 |
145 |
146 | 147 |
148 |
149 | ); 150 | } 151 | return ( 152 |
153 |

React Cookie Auth

154 |

You are logged in!

155 | 156 | 157 |
158 | ) 159 | } 160 | } 161 | 162 | export default App; 163 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | 5 | ReactDOM.createRoot(document.getElementById('root')).render( 6 | 7 | 8 | , 9 | ) 10 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/frontend/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/nginx/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx:latest 2 | COPY ./nginx.conf /etc/nginx/nginx.conf 3 | -------------------------------------------------------------------------------- /django_react_drf_same_origin/nginx/nginx.conf: -------------------------------------------------------------------------------- 1 | user www-data; 2 | worker_processes auto; 3 | pid /run/nginx.pid; 4 | include /etc/nginx/modules-enabled/*.conf; 5 | 6 | events { 7 | worker_connections 1024; 8 | } 9 | 10 | http { 11 | upstream backend { 12 | server backend:8000; 13 | } 14 | 15 | upstream frontend { 16 | server frontend:5173; 17 | } 18 | 19 | server { 20 | listen 80; 21 | 22 | server_name localhost 127.0.0.1; 23 | 24 | location /api { 25 | proxy_pass http://backend; 26 | proxy_http_version 1.1; 27 | proxy_redirect default; 28 | proxy_set_header Upgrade $http_upgrade; 29 | proxy_set_header Connection "upgrade"; 30 | proxy_set_header Host $host; 31 | proxy_set_header X-Real-IP $remote_addr; 32 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 33 | proxy_set_header X-Forwarded-Host $server_name; 34 | } 35 | 36 | location /admin { 37 | proxy_pass http://backend; 38 | proxy_http_version 1.1; 39 | proxy_redirect default; 40 | proxy_set_header Upgrade $http_upgrade; 41 | proxy_set_header Connection "upgrade"; 42 | proxy_set_header Host $host; 43 | proxy_set_header X-Real-IP $remote_addr; 44 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 45 | proxy_set_header X-Forwarded-Host $server_name; 46 | } 47 | 48 | location / { 49 | proxy_pass http://frontend; 50 | proxy_http_version 1.1; 51 | proxy_redirect default; 52 | proxy_set_header Upgrade $http_upgrade; 53 | proxy_set_header Connection "upgrade"; 54 | proxy_set_header Host $host; 55 | proxy_set_header X-Real-IP $remote_addr; 56 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 57 | proxy_set_header X-Forwarded-Host $server_name; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /django_react_same_origin/README.md: -------------------------------------------------------------------------------- 1 | # Django + React SPA (same origin) 2 | 3 | Cookie based authentication, frontend and backend separated (same origin) 4 | 5 | ## Getting Started 6 | 7 | ```sh 8 | $ docker-compose up -d --build 9 | $ docker-compose exec backend python manage.py makemigrations 10 | $ docker-compose exec backend python manage.py migrate 11 | $ docker-compose exec backend python manage.py createsuperuser 12 | ``` 13 | 14 | [http://localhost:81/](http://localhost:81/) 15 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/Dockerfile: -------------------------------------------------------------------------------- 1 | # pull official base image 2 | FROM python:3.11.4-slim-buster 3 | 4 | # set working directory 5 | WORKDIR /usr/src/app 6 | 7 | # set environment variables 8 | ENV PYTHONDONTWRITEBYTECODE 1 9 | ENV PYTHONUNBUFFERED 1 10 | 11 | # install dependencies 12 | RUN pip install --upgrade pip 13 | COPY ./requirements.txt . 14 | RUN pip install -r requirements.txt 15 | 16 | # add app 17 | COPY . . 18 | 19 | # start app 20 | CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] 21 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_same_origin/backend/api/__init__.py -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "api" 7 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_same_origin/backend/api/migrations/__init__.py -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('csrf/', views.get_csrf, name='api-csrf'), 7 | path('login/', views.login_view, name='api-login'), 8 | path('logout/', views.logout_view, name='api-logout'), 9 | path('session/', views.session_view, name='api-session'), 10 | path('whoami/', views.whoami_view, name='api-whoami'), 11 | ] 12 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/api/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib.auth import authenticate, login, logout 4 | from django.http import JsonResponse 5 | from django.middleware.csrf import get_token 6 | from django.views.decorators.csrf import ensure_csrf_cookie 7 | from django.views.decorators.http import require_POST 8 | 9 | 10 | def get_csrf(request): 11 | response = JsonResponse({'detail': 'CSRF cookie set'}) 12 | response['X-CSRFToken'] = get_token(request) 13 | return response 14 | 15 | 16 | @require_POST 17 | def login_view(request): 18 | data = json.loads(request.body) 19 | username = data.get('username') 20 | password = data.get('password') 21 | 22 | if username is None or password is None: 23 | return JsonResponse({'detail': 'Please provide username and password.'}, status=400) 24 | 25 | user = authenticate(username=username, password=password) 26 | 27 | if user is None: 28 | return JsonResponse({'detail': 'Invalid credentials.'}, status=400) 29 | 30 | login(request, user) 31 | return JsonResponse({'detail': 'Successfully logged in.'}) 32 | 33 | 34 | def logout_view(request): 35 | if not request.user.is_authenticated: 36 | return JsonResponse({'detail': 'You\'re not logged in.'}, status=400) 37 | 38 | logout(request) 39 | return JsonResponse({'detail': 'Successfully logged out.'}) 40 | 41 | 42 | @ensure_csrf_cookie 43 | def session_view(request): 44 | if not request.user.is_authenticated: 45 | return JsonResponse({'isAuthenticated': False}) 46 | 47 | return JsonResponse({'isAuthenticated': True}) 48 | 49 | 50 | def whoami_view(request): 51 | if not request.user.is_authenticated: 52 | return JsonResponse({'isAuthenticated': False}) 53 | 54 | return JsonResponse({'username': request.user.username}) 55 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/djangocookieauth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_same_origin/backend/djangocookieauth/__init__.py -------------------------------------------------------------------------------- /django_react_same_origin/backend/djangocookieauth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for djangocookieauth project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/djangocookieauth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangocookieauth project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-)a4$wk&$wvc%3@=n#(sb)w@pwut5==^%rm7ozulnw25y)ptl@%' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'api.apps.ApiConfig', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'djangocookieauth.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'djangocookieauth.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': BASE_DIR / 'db.sqlite3', 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_TZ = True 114 | 115 | 116 | # Static files (CSS, JavaScript, Images) 117 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 118 | 119 | STATIC_URL = 'static/' 120 | 121 | # Default primary key field type 122 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 123 | 124 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 125 | 126 | CSRF_COOKIE_SAMESITE = 'Strict' 127 | SESSION_COOKIE_SAMESITE = 'Strict' 128 | CSRF_COOKIE_HTTPONLY = True 129 | SESSION_COOKIE_HTTPONLY = True 130 | CSRF_TRUSTED_ORIGINS = ['http://localhost:81'] 131 | 132 | # PROD ONLY 133 | # CSRF_COOKIE_SECURE = True 134 | # SESSION_COOKIE_SECURE = True 135 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/djangocookieauth/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.shortcuts import render 3 | from django.urls import path, include 4 | 5 | 6 | urlpatterns = [ 7 | path('admin/', admin.site.urls), 8 | path('api/', include('api.urls')), 9 | ] 10 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/djangocookieauth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangocookieauth project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /django_react_same_origin/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.2.3 2 | -------------------------------------------------------------------------------- /django_react_same_origin/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | 5 | backend: 6 | build: ./backend 7 | volumes: 8 | - ./backend:/usr/src/app 9 | expose: 10 | - 8000 11 | 12 | frontend: 13 | stdin_open: true 14 | build: ./frontend 15 | volumes: 16 | - ./frontend:/usr/src/app 17 | - /usr/src/app/node_modules 18 | expose: 19 | - 5173 20 | environment: 21 | - NODE_ENV=development 22 | depends_on: 23 | - backend 24 | 25 | reverse_proxy: 26 | build: ./nginx 27 | ports: 28 | - 81:80 29 | depends_on: 30 | - backend 31 | - frontend 32 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/Dockerfile: -------------------------------------------------------------------------------- 1 | # pull official base image 2 | FROM node:18-slim 3 | 4 | # set working directory 5 | WORKDIR /usr/src/app 6 | 7 | # add `/usr/src/app/node_modules/.bin` to $PATH 8 | ENV PATH /usr/src/app/node_modules/.bin:$PATH 9 | 10 | # install and cache app dependencies 11 | COPY package.json . 12 | COPY package-lock.json . 13 | RUN npm ci 14 | 15 | # start app 16 | CMD ["vite", "--host"] 17 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/README.md: -------------------------------------------------------------------------------- 1 | # React + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0" 15 | }, 16 | "devDependencies": { 17 | "@types/react": "^18.2.15", 18 | "@types/react-dom": "^18.2.7", 19 | "@vitejs/plugin-react": "^4.0.3", 20 | "eslint": "^8.45.0", 21 | "eslint-plugin-react": "^7.32.2", 22 | "eslint-plugin-react-hooks": "^4.6.0", 23 | "eslint-plugin-react-refresh": "^0.4.3", 24 | "vite": "^4.4.5" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | class App extends React.Component { 4 | 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | csrf: "", 10 | username: "", 11 | password: "", 12 | error: "", 13 | isAuthenticated: false, 14 | }; 15 | } 16 | 17 | componentDidMount = () => { 18 | this.getSession(); 19 | } 20 | 21 | getCSRF = () => { 22 | fetch("/api/csrf/", { 23 | credentials: "same-origin", 24 | }) 25 | .then((res) => { 26 | let csrfToken = res.headers.get("X-CSRFToken"); 27 | this.setState({csrf: csrfToken}); 28 | console.log(csrfToken); 29 | }) 30 | .catch((err) => { 31 | console.log(err); 32 | }); 33 | } 34 | 35 | getSession = () => { 36 | fetch("/api/session/", { 37 | credentials: "same-origin", 38 | }) 39 | .then((res) => res.json()) 40 | .then((data) => { 41 | console.log(data); 42 | if (data.isAuthenticated) { 43 | this.setState({isAuthenticated: true}); 44 | } else { 45 | this.setState({isAuthenticated: false}); 46 | this.getCSRF(); 47 | } 48 | }) 49 | .catch((err) => { 50 | console.log(err); 51 | }); 52 | } 53 | 54 | whoami = () => { 55 | fetch("/api/whoami/", { 56 | headers: { 57 | "Content-Type": "application/json", 58 | }, 59 | credentials: "same-origin", 60 | }) 61 | .then((res) => res.json()) 62 | .then((data) => { 63 | console.log("You are logged in as: " + data.username); 64 | }) 65 | .catch((err) => { 66 | console.log(err); 67 | }); 68 | } 69 | 70 | handlePasswordChange = (event) => { 71 | this.setState({password: event.target.value}); 72 | } 73 | 74 | handleUserNameChange = (event) => { 75 | this.setState({username: event.target.value}); 76 | } 77 | 78 | isResponseOk(response) { 79 | if (response.status >= 200 && response.status <= 299) { 80 | return response.json(); 81 | } else { 82 | throw Error(response.statusText); 83 | } 84 | } 85 | 86 | login = (event) => { 87 | event.preventDefault(); 88 | fetch("/api/login/", { 89 | method: "POST", 90 | headers: { 91 | "Content-Type": "application/json", 92 | "X-CSRFToken": this.state.csrf, 93 | }, 94 | credentials: "same-origin", 95 | body: JSON.stringify({username: this.state.username, password: this.state.password}), 96 | }) 97 | .then(this.isResponseOk) 98 | .then((data) => { 99 | console.log(data); 100 | this.setState({isAuthenticated: true, username: "", password: "", error: ""}); 101 | }) 102 | .catch((err) => { 103 | console.log(err); 104 | this.setState({error: "Wrong username or password."}); 105 | }); 106 | } 107 | 108 | logout = () => { 109 | fetch("/api/logout", { 110 | credentials: "same-origin", 111 | }) 112 | .then(this.isResponseOk) 113 | .then((data) => { 114 | console.log(data); 115 | this.setState({isAuthenticated: false}); 116 | this.getCSRF(); 117 | }) 118 | .catch((err) => { 119 | console.log(err); 120 | }); 121 | }; 122 | 123 | render() { 124 | if (!this.state.isAuthenticated) { 125 | return ( 126 |
127 |

React Cookie Auth

128 |
129 |

Login

130 |
131 |
132 | 133 | 134 |
135 |
136 | 137 | 138 |
139 | {this.state.error && 140 | 141 | {this.state.error} 142 | 143 | } 144 |
145 |
146 | 147 |
148 |
149 | ); 150 | } 151 | return ( 152 |
153 |

React Cookie Auth

154 |

You are logged in!

155 | 156 | 157 |
158 | ) 159 | } 160 | } 161 | 162 | export default App; 163 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | 5 | ReactDOM.createRoot(document.getElementById('root')).render( 6 | 7 | 8 | , 9 | ) 10 | -------------------------------------------------------------------------------- /django_react_same_origin/frontend/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /django_react_same_origin/nginx/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx:latest 2 | COPY ./nginx.conf /etc/nginx/nginx.conf 3 | -------------------------------------------------------------------------------- /django_react_same_origin/nginx/nginx.conf: -------------------------------------------------------------------------------- 1 | user www-data; 2 | worker_processes auto; 3 | pid /run/nginx.pid; 4 | include /etc/nginx/modules-enabled/*.conf; 5 | 6 | events { 7 | worker_connections 1024; 8 | } 9 | 10 | http { 11 | upstream backend { 12 | server backend:8000; 13 | } 14 | 15 | upstream frontend { 16 | server frontend:5173; 17 | } 18 | 19 | server { 20 | listen 80; 21 | 22 | server_name localhost 127.0.0.1; 23 | 24 | location /api { 25 | proxy_pass http://backend; 26 | proxy_http_version 1.1; 27 | proxy_redirect default; 28 | proxy_set_header Upgrade $http_upgrade; 29 | proxy_set_header Connection "upgrade"; 30 | proxy_set_header Host $host; 31 | proxy_set_header X-Real-IP $remote_addr; 32 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 33 | proxy_set_header X-Forwarded-Host $server_name; 34 | } 35 | 36 | location /admin { 37 | proxy_pass http://backend; 38 | proxy_http_version 1.1; 39 | proxy_redirect default; 40 | proxy_set_header Upgrade $http_upgrade; 41 | proxy_set_header Connection "upgrade"; 42 | proxy_set_header Host $host; 43 | proxy_set_header X-Real-IP $remote_addr; 44 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 45 | proxy_set_header X-Forwarded-Host $server_name; 46 | } 47 | 48 | location / { 49 | proxy_pass http://frontend; 50 | proxy_http_version 1.1; 51 | proxy_redirect default; 52 | proxy_set_header Upgrade $http_upgrade; 53 | proxy_set_header Connection "upgrade"; 54 | proxy_set_header Host $host; 55 | proxy_set_header X-Real-IP $remote_addr; 56 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 57 | proxy_set_header X-Forwarded-Host $server_name; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /django_react_templates/README.md: -------------------------------------------------------------------------------- 1 | # Django + React SPA served up via Django templates 2 | 3 | Cookie based authentication, frontend served with Django templates 4 | 5 | ## Getting started 6 | 7 | Create and activate a virtual environment: 8 | 9 | ```sh 10 | $ python3 -m venv venv && source venv/bin/activate 11 | (venv)$ pip install -r requirements.txt 12 | (venv)$ python manage.py migrate 13 | 14 | (venv)$ cd frontend 15 | (venv)$ npm install 16 | (venv)$ npm run build 17 | 18 | (venv)$ cd .. 19 | (venv)$ python manage.py runserver 20 | ``` 21 | 22 | Test at [http://localhost:8000/](http://localhost:8000/). 23 | -------------------------------------------------------------------------------- /django_react_templates/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_templates/api/__init__.py -------------------------------------------------------------------------------- /django_react_templates/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_react_templates/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "api" 7 | -------------------------------------------------------------------------------- /django_react_templates/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_templates/api/migrations/__init__.py -------------------------------------------------------------------------------- /django_react_templates/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django_react_templates/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_react_templates/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('login/', views.login_view, name='api-login'), 7 | path('logout/', views.logout_view, name='api-logout'), 8 | path('session/', views.session_view, name='api-session'), 9 | path('whoami/', views.whoami_view, name='api-whoami'), 10 | ] 11 | -------------------------------------------------------------------------------- /django_react_templates/api/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib.auth import authenticate, login, logout 4 | from django.http import JsonResponse 5 | from django.views.decorators.csrf import ensure_csrf_cookie 6 | from django.views.decorators.http import require_POST 7 | 8 | 9 | @require_POST 10 | def login_view(request): 11 | data = json.loads(request.body) 12 | username = data.get('username') 13 | password = data.get('password') 14 | 15 | if username is None or password is None: 16 | return JsonResponse({'detail': 'Please provide username and password.'}, status=400) 17 | 18 | user = authenticate(username=username, password=password) 19 | 20 | if user is None: 21 | return JsonResponse({'detail': 'Invalid credentials.'}, status=400) 22 | 23 | login(request, user) 24 | return JsonResponse({'detail': 'Successfully logged in.'}) 25 | 26 | 27 | def logout_view(request): 28 | if not request.user.is_authenticated: 29 | return JsonResponse({'detail': 'You\'re not logged in.'}, status=400) 30 | 31 | logout(request) 32 | return JsonResponse({'detail': 'Successfully logged out.'}) 33 | 34 | 35 | @ensure_csrf_cookie 36 | def session_view(request): 37 | if not request.user.is_authenticated: 38 | return JsonResponse({'isAuthenticated': False}) 39 | 40 | return JsonResponse({'isAuthenticated': True}) 41 | 42 | 43 | def whoami_view(request): 44 | if not request.user.is_authenticated: 45 | return JsonResponse({'isAuthenticated': False}) 46 | 47 | return JsonResponse({'username': request.user.username}) 48 | -------------------------------------------------------------------------------- /django_react_templates/djangocookieauth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-spa-cookie-auth/ef47ea89100ed91e8ba9508523cdc0f621dda077/django_react_templates/djangocookieauth/__init__.py -------------------------------------------------------------------------------- /django_react_templates/djangocookieauth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for djangocookieauth project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_react_templates/djangocookieauth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangocookieauth project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-4mm@r&4e#_&s9-_)86c75r02030323-%s!98jvtj69ia1tsh+a' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'api.apps.ApiConfig', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'djangocookieauth.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [BASE_DIR.joinpath('frontend')], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'djangocookieauth.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': BASE_DIR / 'db.sqlite3', 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_TZ = True 114 | 115 | 116 | # Static files (CSS, JavaScript, Images) 117 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 118 | 119 | STATIC_URL = '/static/' 120 | 121 | STATICFILES_DIRS = ( 122 | BASE_DIR.joinpath('frontend', 'dist'), 123 | ) 124 | 125 | # Default primary key field type 126 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 127 | 128 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 129 | 130 | CSRF_COOKIE_SAMESITE = 'Strict' 131 | SESSION_COOKIE_SAMESITE = 'Strict' 132 | CSRF_COOKIE_HTTPONLY = False # False since we will grab it via universal-cookies 133 | SESSION_COOKIE_HTTPONLY = True 134 | 135 | # PROD ONLY 136 | # CSRF_COOKIE_SECURE = True 137 | # SESSION_COOKIE_SECURE = True 138 | -------------------------------------------------------------------------------- /django_react_templates/djangocookieauth/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.shortcuts import render 3 | from django.urls import path, include 4 | 5 | 6 | def index_view(request): 7 | return render(request, 'dist/index.html') 8 | 9 | 10 | urlpatterns = [ 11 | path('admin/', admin.site.urls), 12 | path('api/', include('api.urls')), 13 | path('', index_view, name='index'), 14 | ] 15 | -------------------------------------------------------------------------------- /django_react_templates/djangocookieauth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangocookieauth project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django_react_templates/frontend/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /django_react_templates/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /django_react_templates/frontend/README.md: -------------------------------------------------------------------------------- 1 | # React + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | -------------------------------------------------------------------------------- /django_react_templates/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /django_react_templates/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0", 15 | "universal-cookie": "^4.0.4" 16 | }, 17 | "devDependencies": { 18 | "@types/react": "^18.2.15", 19 | "@types/react-dom": "^18.2.7", 20 | "@vitejs/plugin-react": "^4.0.3", 21 | "eslint": "^8.45.0", 22 | "eslint-plugin-react": "^7.32.2", 23 | "eslint-plugin-react-hooks": "^4.6.0", 24 | "eslint-plugin-react-refresh": "^0.4.3", 25 | "vite": "^4.4.5" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /django_react_templates/frontend/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_templates/frontend/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Cookies from "universal-cookie"; 3 | 4 | const cookies = new Cookies(); 5 | 6 | class App extends React.Component { 7 | 8 | constructor(props) { 9 | super(props); 10 | 11 | this.state = { 12 | username: "", 13 | password: "", 14 | error: "", 15 | isAuthenticated: false, 16 | }; 17 | } 18 | 19 | componentDidMount = () => { 20 | this.getSession(); 21 | } 22 | 23 | getSession = () => { 24 | fetch("/api/session/", { 25 | credentials: "same-origin", 26 | }) 27 | .then((res) => res.json()) 28 | .then((data) => { 29 | console.log(data); 30 | if (data.isAuthenticated) { 31 | this.setState({isAuthenticated: true}); 32 | } else { 33 | this.setState({isAuthenticated: false}); 34 | } 35 | }) 36 | .catch((err) => { 37 | console.log(err); 38 | }); 39 | } 40 | 41 | whoami = () => { 42 | fetch("/api/whoami/", { 43 | headers: { 44 | "Content-Type": "application/json", 45 | }, 46 | credentials: "same-origin", 47 | }) 48 | .then((res) => res.json()) 49 | .then((data) => { 50 | console.log("You are logged in as: " + data.username); 51 | }) 52 | .catch((err) => { 53 | console.log(err); 54 | }); 55 | } 56 | 57 | handlePasswordChange = (event) => { 58 | this.setState({password: event.target.value}); 59 | } 60 | 61 | handleUserNameChange = (event) => { 62 | this.setState({username: event.target.value}); 63 | } 64 | 65 | isResponseOk(response) { 66 | if (response.status >= 200 && response.status <= 299) { 67 | return response.json(); 68 | } else { 69 | throw Error(response.statusText); 70 | } 71 | } 72 | 73 | login = (event) => { 74 | event.preventDefault(); 75 | fetch("/api/login/", { 76 | method: "POST", 77 | headers: { 78 | "Content-Type": "application/json", 79 | "X-CSRFToken": cookies.get("csrftoken"), 80 | }, 81 | credentials: "same-origin", 82 | body: JSON.stringify({username: this.state.username, password: this.state.password}), 83 | }) 84 | .then(this.isResponseOk) 85 | .then((data) => { 86 | console.log(data); 87 | this.setState({isAuthenticated: true, username: "", password: "", error: ""}); 88 | }) 89 | .catch((err) => { 90 | console.log(err); 91 | this.setState({error: "Wrong username or password."}); 92 | }); 93 | } 94 | 95 | logout = () => { 96 | fetch("/api/logout", { 97 | credentials: "same-origin", 98 | }) 99 | .then(this.isResponseOk) 100 | .then((data) => { 101 | console.log(data); 102 | this.setState({isAuthenticated: false}); 103 | }) 104 | .catch((err) => { 105 | console.log(err); 106 | }); 107 | }; 108 | 109 | render() { 110 | if (!this.state.isAuthenticated) { 111 | return ( 112 |
113 |

React Cookie Auth

114 |
115 |

Login

116 |
117 |
118 | 119 | 120 |
121 |
122 | 123 | 124 |
125 | {this.state.error && 126 | 127 | {this.state.error} 128 | 129 | } 130 |
131 |
132 | 133 |
134 |
135 | ); 136 | } 137 | return ( 138 |
139 |

React Cookie Auth

140 |

You are logged in!

141 | 142 | 143 |
144 | ) 145 | } 146 | } 147 | 148 | export default App; 149 | -------------------------------------------------------------------------------- /django_react_templates/frontend/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /django_react_templates/frontend/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | 5 | ReactDOM.createRoot(document.getElementById('root')).render( 6 | 7 | 8 | , 9 | ) 10 | -------------------------------------------------------------------------------- /django_react_templates/frontend/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | base: '/static/' 8 | }) 9 | -------------------------------------------------------------------------------- /django_react_templates/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocookieauth.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /django_react_templates/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.2.3 2 | --------------------------------------------------------------------------------