├── README.md ├── backend ├── backend │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── base │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ └── models.cpython-39.pyc │ ├── admin.py │ ├── api │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-39.pyc │ │ │ ├── serializers.cpython-39.pyc │ │ │ ├── urls.cpython-39.pyc │ │ │ └── views.cpython-39.pyc │ │ ├── serializers.py │ │ ├── urls.py │ │ └── views.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-39.pyc │ │ │ └── __init__.cpython-39.pyc │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── manage.py └── requirements.txt ├── desktop wallpaper.jpg ├── frontend ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.js │ ├── components │ └── Header.js │ ├── context │ └── AuthContext.js │ ├── index.js │ ├── pages │ ├── HomePage.js │ └── LoginPage.js │ └── utils │ ├── PrivateRoute.js │ ├── axiosInstance.js │ ├── fetchInstance.js │ ├── useAxios.js │ └── useFetch.js └── requirements.txt /README.md: -------------------------------------------------------------------------------- 1 | # Installation guide 2 | 3 | git clone https://github.com/divanov11/refresh-token-fetchwrapper 4 | 5 | #Setup Backend 6 | 7 | 1. cd refresh-token-fetchwrapper/backend 8 | 2. pip install -r requirements.txt 9 | 3. python manage.py createsuperuser 10 | 4. python manage.py runserver 11 | 12 | #Setup Frontend 13 | 14 | 1. cd refresh-token-fetchwrapper/frontend 15 | 2. npm install 16 | 3. npm start 17 | -------------------------------------------------------------------------------- /backend/backend/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/backend/__init__.py -------------------------------------------------------------------------------- /backend/backend/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/backend/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /backend/backend/__pycache__/settings.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/backend/__pycache__/settings.cpython-39.pyc -------------------------------------------------------------------------------- /backend/backend/__pycache__/urls.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/backend/__pycache__/urls.cpython-39.pyc -------------------------------------------------------------------------------- /backend/backend/__pycache__/wsgi.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/backend/__pycache__/wsgi.cpython-39.pyc -------------------------------------------------------------------------------- /backend/backend/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for backend 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/3.2/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', 'backend.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /backend/backend/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for backend project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.8. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from datetime import timedelta 14 | from pathlib import Path 15 | 16 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 17 | BASE_DIR = Path(__file__).resolve().parent.parent 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = 'django-insecure-ifo8u$qv@&7z7b%u5&^p$lci6@7a(j^x61p7pw8#zi15v66!&6' 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = True 28 | 29 | ALLOWED_HOSTS = [] 30 | 31 | 32 | # Application definition 33 | 34 | INSTALLED_APPS = [ 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | 42 | 'base.apps.BaseConfig', 43 | 44 | 'rest_framework', 45 | 'rest_framework_simplejwt.token_blacklist', 46 | "corsheaders", 47 | ] 48 | 49 | 50 | REST_FRAMEWORK = { 51 | 'DEFAULT_AUTHENTICATION_CLASSES': ( 52 | 53 | 'rest_framework_simplejwt.authentication.JWTAuthentication', 54 | ) 55 | } 56 | 57 | 58 | SIMPLE_JWT = { 59 | 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=3), 60 | 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 61 | 'ROTATE_REFRESH_TOKENS': True, 62 | 'BLACKLIST_AFTER_ROTATION': True, 63 | 'UPDATE_LAST_LOGIN': False, 64 | 65 | 'ALGORITHM': 'HS256', 66 | 'VERIFYING_KEY': None, 67 | 'AUDIENCE': None, 68 | 'ISSUER': None, 69 | 'JWK_URL': None, 70 | 'LEEWAY': 0, 71 | 72 | 'AUTH_HEADER_TYPES': ('Bearer',), 73 | 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 74 | 'USER_ID_FIELD': 'id', 75 | 'USER_ID_CLAIM': 'user_id', 76 | 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 77 | 78 | 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 79 | 'TOKEN_TYPE_CLAIM': 'token_type', 80 | 81 | 'JTI_CLAIM': 'jti', 82 | 83 | 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 84 | 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 85 | 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), 86 | } 87 | 88 | MIDDLEWARE = [ 89 | 'django.middleware.security.SecurityMiddleware', 90 | 91 | "corsheaders.middleware.CorsMiddleware", 92 | 93 | 'django.contrib.sessions.middleware.SessionMiddleware', 94 | 'django.middleware.common.CommonMiddleware', 95 | 'django.middleware.csrf.CsrfViewMiddleware', 96 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 97 | 'django.contrib.messages.middleware.MessageMiddleware', 98 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 99 | ] 100 | 101 | ROOT_URLCONF = 'backend.urls' 102 | 103 | TEMPLATES = [ 104 | { 105 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 106 | 'DIRS': [], 107 | 'APP_DIRS': True, 108 | 'OPTIONS': { 109 | 'context_processors': [ 110 | 'django.template.context_processors.debug', 111 | 'django.template.context_processors.request', 112 | 'django.contrib.auth.context_processors.auth', 113 | 'django.contrib.messages.context_processors.messages', 114 | ], 115 | }, 116 | }, 117 | ] 118 | 119 | WSGI_APPLICATION = 'backend.wsgi.application' 120 | 121 | 122 | # Database 123 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 124 | 125 | DATABASES = { 126 | 'default': { 127 | 'ENGINE': 'django.db.backends.sqlite3', 128 | 'NAME': BASE_DIR / 'db.sqlite3', 129 | } 130 | } 131 | 132 | 133 | # Password validation 134 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 135 | 136 | AUTH_PASSWORD_VALIDATORS = [ 137 | { 138 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 139 | }, 140 | { 141 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 142 | }, 143 | { 144 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 145 | }, 146 | { 147 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 148 | }, 149 | ] 150 | 151 | 152 | # Internationalization 153 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 154 | 155 | LANGUAGE_CODE = 'en-us' 156 | 157 | TIME_ZONE = 'UTC' 158 | 159 | USE_I18N = True 160 | 161 | USE_L10N = True 162 | 163 | USE_TZ = True 164 | 165 | 166 | # Static files (CSS, JavaScript, Images) 167 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 168 | 169 | STATIC_URL = '/static/' 170 | 171 | # Default primary key field type 172 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 173 | 174 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 175 | 176 | 177 | CORS_ALLOW_ALL_ORIGINS = True 178 | -------------------------------------------------------------------------------- /backend/backend/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path, include 3 | 4 | urlpatterns = [ 5 | path('admin/', admin.site.urls), 6 | path('api/', include('base.api.urls')) 7 | ] 8 | -------------------------------------------------------------------------------- /backend/backend/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for backend 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/3.2/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', 'backend.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /backend/base/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/__init__.py -------------------------------------------------------------------------------- /backend/base/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/__pycache__/admin.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/__pycache__/admin.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/__pycache__/apps.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/__pycache__/apps.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/__pycache__/models.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/__pycache__/models.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | 5 | from .models import Note 6 | admin.site.register(Note) 7 | -------------------------------------------------------------------------------- /backend/base/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/api/__init__.py -------------------------------------------------------------------------------- /backend/base/api/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/api/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/api/__pycache__/serializers.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/api/__pycache__/serializers.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/api/__pycache__/urls.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/api/__pycache__/urls.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/api/__pycache__/views.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/api/__pycache__/views.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/api/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework.serializers import ModelSerializer 2 | from base.models import Note 3 | 4 | 5 | class NoteSerializer(ModelSerializer): 6 | class Meta: 7 | model = Note 8 | fields = '__all__' 9 | -------------------------------------------------------------------------------- /backend/base/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from . import views 3 | from .views import MyTokenObtainPairView 4 | 5 | from rest_framework_simplejwt.views import ( 6 | TokenRefreshView, 7 | ) 8 | 9 | 10 | urlpatterns = [ 11 | path('', views.getRoutes), 12 | path('notes/', views.getNotes), 13 | 14 | path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), 15 | path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), 16 | ] 17 | -------------------------------------------------------------------------------- /backend/base/api/views.py: -------------------------------------------------------------------------------- 1 | from django.http import JsonResponse 2 | from rest_framework import permissions 3 | from rest_framework.response import Response 4 | from rest_framework.decorators import api_view, permission_classes 5 | from rest_framework.permissions import IsAuthenticated 6 | 7 | from rest_framework_simplejwt.serializers import TokenObtainPairSerializer 8 | from rest_framework_simplejwt.views import TokenObtainPairView 9 | 10 | 11 | from .serializers import NoteSerializer 12 | from base.models import Note 13 | 14 | 15 | class MyTokenObtainPairSerializer(TokenObtainPairSerializer): 16 | @classmethod 17 | def get_token(cls, user): 18 | token = super().get_token(user) 19 | 20 | # Add custom claims 21 | token['username'] = user.username 22 | # ... 23 | 24 | return token 25 | 26 | 27 | class MyTokenObtainPairView(TokenObtainPairView): 28 | serializer_class = MyTokenObtainPairSerializer 29 | 30 | 31 | @api_view(['GET']) 32 | def getRoutes(request): 33 | routes = [ 34 | '/api/token', 35 | '/api/token/refresh', 36 | ] 37 | 38 | return Response(routes) 39 | 40 | 41 | @api_view(['GET']) 42 | @permission_classes([IsAuthenticated]) 43 | def getNotes(request): 44 | user = request.user 45 | notes = user.note_set.all() 46 | serializer = NoteSerializer(notes, many=True) 47 | return Response(serializer.data) 48 | -------------------------------------------------------------------------------- /backend/base/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class BaseConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'base' 7 | -------------------------------------------------------------------------------- /backend/base/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.8 on 2021-10-16 22:22 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Note', 19 | fields=[ 20 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('body', models.TextField()), 22 | ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /backend/base/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/migrations/__init__.py -------------------------------------------------------------------------------- /backend/base/migrations/__pycache__/0001_initial.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/migrations/__pycache__/0001_initial.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/migrations/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/base/migrations/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /backend/base/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import User 3 | 4 | # Create your models here. 5 | 6 | 7 | class Note(models.Model): 8 | user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) 9 | body = models.TextField() 10 | -------------------------------------------------------------------------------- /backend/base/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /backend/base/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /backend/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/db.sqlite3 -------------------------------------------------------------------------------- /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', 'backend.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 | -------------------------------------------------------------------------------- /backend/requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/backend/requirements.txt -------------------------------------------------------------------------------- /desktop wallpaper.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/desktop wallpaper.jpg -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.14.1", 7 | "@testing-library/react": "^11.2.7", 8 | "@testing-library/user-event": "^12.8.3", 9 | "axios": "^0.23.0", 10 | "dayjs": "^1.10.7", 11 | "jwt-decode": "^3.1.2", 12 | "react": "^17.0.2", 13 | "react-dom": "^17.0.2", 14 | "react-router-dom": "^5.3.0", 15 | "react-scripts": "4.0.3", 16 | "web-vitals": "^1.1.2" 17 | }, 18 | "scripts": { 19 | "start": "react-scripts start", 20 | "build": "react-scripts build", 21 | "test": "react-scripts test", 22 | "eject": "react-scripts eject" 23 | }, 24 | "eslintConfig": { 25 | "extends": [ 26 | "react-app", 27 | "react-app/jest" 28 | ] 29 | }, 30 | "browserslist": { 31 | "production": [ 32 | ">0.2%", 33 | "not dead", 34 | "not op_mini all" 35 | ], 36 | "development": [ 37 | "last 1 chrome version", 38 | "last 1 firefox version", 39 | "last 1 safari version" 40 | ] 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/frontend/public/logo512.png -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/frontend/src/App.css -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import './App.css'; 2 | import { BrowserRouter as Router, Route } from 'react-router-dom' 3 | import PrivateRoute from './utils/PrivateRoute' 4 | import { AuthProvider } from './context/AuthContext' 5 | 6 | import HomePage from './pages/HomePage' 7 | import LoginPage from './pages/LoginPage' 8 | import Header from './components/Header' 9 | 10 | function App() { 11 | return ( 12 |
13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 |
21 | ); 22 | } 23 | 24 | export default App; 25 | -------------------------------------------------------------------------------- /frontend/src/components/Header.js: -------------------------------------------------------------------------------- 1 | import React, {useContext} from 'react' 2 | import { Link } from 'react-router-dom' 3 | import AuthContext from '../context/AuthContext' 4 | 5 | const Header = () => { 6 | let {user, logoutUser} = useContext(AuthContext) 7 | return ( 8 |
9 | Home 10 | | 11 | {user ? ( 12 |

Logout

13 | ): ( 14 | Login 15 | )} 16 | 17 | {user &&

Hello {user.username}

} 18 | 19 |
20 | ) 21 | } 22 | 23 | export default Header 24 | -------------------------------------------------------------------------------- /frontend/src/context/AuthContext.js: -------------------------------------------------------------------------------- 1 | import { createContext, useState, useEffect } from 'react' 2 | import jwt_decode from "jwt-decode"; 3 | import { useHistory } from 'react-router-dom' 4 | 5 | const AuthContext = createContext() 6 | 7 | export default AuthContext; 8 | 9 | 10 | export const AuthProvider = ({children}) => { 11 | let [authTokens, setAuthTokens] = useState(()=> localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null) 12 | let [user, setUser] = useState(()=> localStorage.getItem('authTokens') ? jwt_decode(localStorage.getItem('authTokens')) : null) 13 | let [loading, setLoading] = useState(true) 14 | 15 | const history = useHistory() 16 | 17 | let loginUser = async (e )=> { 18 | e.preventDefault() 19 | let response = await fetch('http://127.0.0.1:8000/api/token/', { 20 | method:'POST', 21 | headers:{ 22 | 'Content-Type':'application/json' 23 | }, 24 | body:JSON.stringify({'username':e.target.username.value, 'password':e.target.password.value}) 25 | }) 26 | let data = await response.json() 27 | 28 | if(response.status === 200){ 29 | setAuthTokens(data) 30 | setUser(jwt_decode(data.access)) 31 | localStorage.setItem('authTokens', JSON.stringify(data)) 32 | history.push('/') 33 | }else{ 34 | alert('Something went wrong!') 35 | } 36 | } 37 | 38 | 39 | let logoutUser = () => { 40 | setAuthTokens(null) 41 | setUser(null) 42 | localStorage.removeItem('authTokens') 43 | history.push('/login') 44 | } 45 | 46 | 47 | // let updateToken = async ()=> { 48 | 49 | // let response = await fetch('http://127.0.0.1:8000/api/token/refresh/', { 50 | // method:'POST', 51 | // headers:{ 52 | // 'Content-Type':'application/json' 53 | // }, 54 | // body:JSON.stringify({'refresh':authTokens?.refresh}) 55 | // }) 56 | 57 | // let data = await response.json() 58 | 59 | // if (response.status === 200){ 60 | // setAuthTokens(data) 61 | // setUser(jwt_decode(data.access)) 62 | // localStorage.setItem('authTokens', JSON.stringify(data)) 63 | // }else{ 64 | // logoutUser() 65 | // } 66 | 67 | // if(loading){ 68 | // setLoading(false) 69 | // } 70 | // } 71 | 72 | let contextData = { 73 | user:user, 74 | authTokens:authTokens, 75 | setAuthTokens:setAuthTokens, 76 | setUser:setUser, 77 | loginUser:loginUser, 78 | logoutUser:logoutUser, 79 | } 80 | 81 | 82 | useEffect(()=> { 83 | 84 | if(authTokens){ 85 | setUser(jwt_decode(authTokens.access)) 86 | } 87 | setLoading(false) 88 | 89 | 90 | }, [authTokens, loading]) 91 | 92 | return( 93 | 94 | {loading ? null : children} 95 | 96 | ) 97 | } 98 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | ReactDOM.render( 6 | 7 | 8 | , 9 | document.getElementById('root') 10 | ); 11 | 12 | 13 | -------------------------------------------------------------------------------- /frontend/src/pages/HomePage.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect, useContext} from 'react' 2 | import AuthContext from '../context/AuthContext' 3 | import useFetch from '../utils/useFetch' 4 | //import fetchInstance from '../utils/fetchInstance' 5 | 6 | const HomePage = () => { 7 | let [notes, setNotes] = useState([]) 8 | let {authTokens, logoutUser} = useContext(AuthContext) 9 | 10 | let api = useFetch() 11 | 12 | useEffect(()=> { 13 | getNotes() 14 | }, []) 15 | 16 | 17 | let getNotes = async() => { 18 | let {response, data} = await api('/api/notes/') 19 | 20 | if(response.status === 200){ 21 | setNotes(data) 22 | } 23 | 24 | } 25 | 26 | return ( 27 |
28 |

You are logged to the home page!

29 | 30 | 31 | 36 |
37 | ) 38 | } 39 | 40 | export default HomePage 41 | -------------------------------------------------------------------------------- /frontend/src/pages/LoginPage.js: -------------------------------------------------------------------------------- 1 | import React, {useContext} from 'react' 2 | import AuthContext from '../context/AuthContext' 3 | 4 | const LoginPage = () => { 5 | let {loginUser} = useContext(AuthContext) 6 | 7 | return ( 8 |
9 |
10 | 11 | 12 | 13 |
14 |
15 | ) 16 | } 17 | 18 | export default LoginPage 19 | -------------------------------------------------------------------------------- /frontend/src/utils/PrivateRoute.js: -------------------------------------------------------------------------------- 1 | import { Route, Redirect } from 'react-router-dom' 2 | import { useContext } from 'react' 3 | import AuthContext from '../context/AuthContext' 4 | 5 | const PrivateRoute = ({children, ...rest}) => { 6 | let {user} = useContext(AuthContext) 7 | return( 8 | {!user ? : children} 9 | ) 10 | } 11 | 12 | export default PrivateRoute; -------------------------------------------------------------------------------- /frontend/src/utils/axiosInstance.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import jwt_decode from "jwt-decode"; 3 | import dayjs from 'dayjs' 4 | 5 | const baseURL = 'http://127.0.0.1:8000' 6 | 7 | let authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null 8 | 9 | const axiosInstance = axios.create({ 10 | baseURL, 11 | headers:{Authorization: `Bearer ${authTokens?.access}`} 12 | }); 13 | 14 | axiosInstance.interceptors.request.use(async req => { 15 | if(!authTokens){ 16 | authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null 17 | req.headers.Authorization = `Bearer ${authTokens?.access}` 18 | } 19 | 20 | const user = jwt_decode(authTokens.access) 21 | const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; 22 | 23 | if(!isExpired) return req 24 | 25 | const response = await axios.post(`${baseURL}/api/token/refresh/`, { 26 | refresh: authTokens.refresh 27 | }); 28 | 29 | localStorage.setItem('authTokens', JSON.stringify(response.data)) 30 | req.headers.Authorization = `Bearer ${response.data.access}` 31 | return req 32 | }) 33 | 34 | 35 | export default axiosInstance; -------------------------------------------------------------------------------- /frontend/src/utils/fetchInstance.js: -------------------------------------------------------------------------------- 1 | import jwt_decode from "jwt-decode"; 2 | import dayjs from 'dayjs' 3 | 4 | let baseURL = 'http://127.0.0.1:8000' 5 | 6 | let originalRequest = async (url, config)=> { 7 | url = `${baseURL}${url}` 8 | let response = await fetch(url, config) 9 | let data = await response.json() 10 | console.log('REQUESTING:', data) 11 | return {response, data} 12 | } 13 | 14 | let refreshToken = async (authTokens) => { 15 | 16 | let response = await fetch('http://127.0.0.1:8000/api/token/refresh/', { 17 | method:'POST', 18 | headers:{ 19 | 'Content-Type':'application/json' 20 | }, 21 | body:JSON.stringify({'refresh':authTokens.refresh}) 22 | }) 23 | let data = await response.json() 24 | localStorage.setItem('authTokens', JSON.stringify(data)) 25 | return data 26 | } 27 | 28 | 29 | let customFetcher = async (url, config={}) => { 30 | let authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null 31 | 32 | // const user = jwt_decode(authTokens.access) 33 | // const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; 34 | 35 | // if(isExpired){ 36 | // authTokens = await refreshToken(authTokens) 37 | // } 38 | 39 | //Proceed with request 40 | 41 | config['headers'] = { 42 | Authorization:`Bearer ${authTokens?.access}` 43 | } 44 | 45 | 46 | console.log('Before Request') 47 | let {response, data} = await originalRequest(url, config) 48 | console.log('After Request') 49 | 50 | if (response.statusText === 'Unauthorized'){ 51 | authTokens = await refreshToken(authTokens) 52 | 53 | config['headers'] = { 54 | Authorization:`Bearer ${authTokens?.access}` 55 | } 56 | 57 | let newResponse = await originalRequest(url, config) 58 | response = newResponse.response 59 | data = newResponse.data 60 | 61 | } 62 | 63 | return {response, data} 64 | } 65 | export default customFetcher; -------------------------------------------------------------------------------- /frontend/src/utils/useAxios.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import jwt_decode from "jwt-decode"; 3 | import dayjs from 'dayjs' 4 | import { useContext } from 'react' 5 | import AuthContext from '../context/AuthContext' 6 | 7 | 8 | const baseURL = 'http://127.0.0.1:8000' 9 | 10 | 11 | const useAxios = () => { 12 | const {authTokens, setUser, setAuthTokens} = useContext(AuthContext) 13 | 14 | const axiosInstance = axios.create({ 15 | baseURL, 16 | headers:{Authorization: `Bearer ${authTokens?.access}`} 17 | }); 18 | 19 | 20 | axiosInstance.interceptors.request.use(async req => { 21 | 22 | const user = jwt_decode(authTokens.access) 23 | const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; 24 | 25 | if(!isExpired) return req 26 | 27 | const response = await axios.post(`${baseURL}/api/token/refresh/`, { 28 | refresh: authTokens.refresh 29 | }); 30 | 31 | localStorage.setItem('authTokens', JSON.stringify(response.data)) 32 | 33 | setAuthTokens(response.data) 34 | setUser(jwt_decode(response.data.access)) 35 | 36 | req.headers.Authorization = `Bearer ${response.data.access}` 37 | return req 38 | }) 39 | 40 | return axiosInstance 41 | } 42 | 43 | export default useAxios; -------------------------------------------------------------------------------- /frontend/src/utils/useFetch.js: -------------------------------------------------------------------------------- 1 | import { useContext } from 'react' 2 | import jwt_decode from "jwt-decode"; 3 | import dayjs from 'dayjs' 4 | import AuthContext from '../context/AuthContext'; 5 | 6 | 7 | let useFetch = () => { 8 | let config = {} 9 | 10 | let {authTokens, setAuthTokens, setUser} = useContext(AuthContext) 11 | 12 | let baseURL = 'http://127.0.0.1:8000' 13 | 14 | let originalRequest = async (url, config)=> { 15 | url = `${baseURL}${url}` 16 | let response = await fetch(url, config) 17 | let data = await response.json() 18 | console.log('REQUESTING:', data) 19 | return {response, data} 20 | } 21 | 22 | let refreshToken = async (authTokens) => { 23 | 24 | let response = await fetch('http://127.0.0.1:8000/api/token/refresh/', { 25 | method:'POST', 26 | headers:{ 27 | 'Content-Type':'application/json' 28 | }, 29 | body:JSON.stringify({'refresh':authTokens.refresh}) 30 | }) 31 | let data = await response.json() 32 | localStorage.setItem('authTokens', JSON.stringify(data)) 33 | setAuthTokens(data) 34 | setUser(jwt_decode(data.access)) 35 | return data 36 | } 37 | 38 | let callFetch = async (url) => { 39 | const user = jwt_decode(authTokens.access) 40 | const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; 41 | 42 | if(isExpired){ 43 | authTokens = await refreshToken(authTokens) 44 | } 45 | 46 | 47 | config['headers'] = { 48 | Authorization:`Bearer ${authTokens?.access}` 49 | } 50 | 51 | let {response, data} = await originalRequest(url, config) 52 | return {response, data} 53 | } 54 | 55 | return callFetch 56 | } 57 | 58 | export default useFetch; -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divanov11/refresh-token-fetchwrapper/88da845323951dc726c7ddc1215a6e6730aa4d3d/requirements.txt --------------------------------------------------------------------------------