├── .gitignore ├── README.md ├── accounts ├── __init__.py ├── admin.py ├── apps.py ├── managers.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_user_auth_provider.py │ └── __init__.py ├── models.py ├── serializers.py ├── tests.py ├── urls.py ├── utils.py └── views.py ├── django_rest_auth ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── frontend └── client-app │ ├── .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 │ ├── Login.jsx │ ├── PasswordResetRequest.jsx │ ├── Profile.jsx │ ├── ResetPassword.jsx │ ├── Signup.jsx │ └── VerifyEmail.jsx │ ├── index.css │ ├── index.js │ └── utils │ └── AxiosInstance.js ├── manage.py ├── requirements.txt └── social_accounts ├── __init__.py ├── admin.py ├── apps.py ├── github.py ├── helpers.py ├── migrations └── __init__.py ├── models.py ├── serializers.py ├── tests.py ├── urls.py └── views.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react 2 | ### About the project 3 | this is a Rest API project developed with django rest framework to build a complete authentication system with simple-jwt and 4 | social Oauth with google signin and github signin, testing it with a react client , features in the auth system includes email signup, login, logout, 5 | email verification with email OTP, forget password reset and login with google and github. and proper implementation and uses of refresh and access token on 6 | the react frontend, the access token is made to expired in few second and the refresh token automatically renew the access token. 7 | 8 | ` 9 | clone or fork the repos. 10 | ` 11 | > 12 | ` 13 | pip install -r requirements.txt. 14 | setup your env variables. 15 | ` 16 | > 17 | ` 18 | cd frontend 19 | ` 20 | > 21 | ` 22 | cd client-app 23 | ` 24 | > 25 | ` 26 | npm install 27 | ` 28 | -------------------------------------------------------------------------------- /accounts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/accounts/__init__.py -------------------------------------------------------------------------------- /accounts/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import User, OneTimePassword 3 | # Register your models here. 4 | 5 | admin.site.register(User) 6 | admin.site.register(OneTimePassword) -------------------------------------------------------------------------------- /accounts/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AccountsConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'accounts' 7 | -------------------------------------------------------------------------------- /accounts/managers.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import BaseUserManager 2 | from django.core.exceptions import ValidationError 3 | from django.core.validators import validate_email 4 | from django.utils.translation import gettext_lazy as _ 5 | 6 | 7 | 8 | class UserManager(BaseUserManager): 9 | def email_validator(self, email): 10 | try: 11 | validate_email(email) 12 | except ValidationError: 13 | raise ValueError(_("please enter a valid email address")) 14 | 15 | def create_user(self, email, first_name, last_name, password, **extra_fields): 16 | if email: 17 | email = self.normalize_email(email) 18 | self.email_validator(email) 19 | else: 20 | raise ValueError(_("Base User Account: An email address is required")) 21 | if not first_name: 22 | raise ValueError(_("First name is required")) 23 | if not last_name: 24 | raise ValueError(_("Last name is required")) 25 | user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) 26 | user.set_password(password) 27 | user.save(using=self._db) 28 | return user 29 | 30 | def create_superuser(self, email, first_name, last_name, password, **extra_fields): 31 | extra_fields.setdefault("is_staff", True) 32 | extra_fields.setdefault("is_superuser", True) 33 | extra_fields.setdefault("is_verified", True) 34 | 35 | if extra_fields.get("is_staff") is not True: 36 | raise ValueError(_("is staff must be true for admin user")) 37 | 38 | if extra_fields.get("is_superuser") is not True: 39 | raise ValueError(_("is superuser must be true for admin user")) 40 | 41 | user = self.create_user( 42 | email, first_name, last_name, password, **extra_fields 43 | ) 44 | user.save(using=self._db) 45 | return user 46 | -------------------------------------------------------------------------------- /accounts/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.2 on 2022-10-31 13:45 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 | ('auth', '0012_alter_user_first_name_max_length'), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='User', 19 | fields=[ 20 | ('password', models.CharField(max_length=128, verbose_name='password')), 21 | ('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)), 22 | ('email', models.EmailField(max_length=255, unique=True, verbose_name='Email Address')), 23 | ('first_name', models.CharField(max_length=100, verbose_name='First Name')), 24 | ('last_name', models.CharField(max_length=100, verbose_name='Last Name')), 25 | ('is_staff', models.BooleanField(default=False)), 26 | ('is_superuser', models.BooleanField(default=False)), 27 | ('is_verified', models.BooleanField(default=False)), 28 | ('is_active', models.BooleanField(default=True)), 29 | ('date_joined', models.DateTimeField(auto_now_add=True)), 30 | ('last_login', models.DateTimeField(auto_now=True)), 31 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), 32 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), 33 | ], 34 | options={ 35 | 'abstract': False, 36 | }, 37 | ), 38 | migrations.CreateModel( 39 | name='OneTimePassword', 40 | fields=[ 41 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 42 | ('otp', models.CharField(max_length=6)), 43 | ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 44 | ], 45 | ), 46 | ] 47 | -------------------------------------------------------------------------------- /accounts/migrations/0002_user_auth_provider.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.2 on 2022-11-02 13:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('accounts', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name='user', 15 | name='auth_provider', 16 | field=models.CharField(default='email', max_length=50), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /accounts/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/accounts/migrations/__init__.py -------------------------------------------------------------------------------- /accounts/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin 3 | from django.utils.translation import gettext_lazy as _ 4 | from rest_framework_simplejwt.tokens import RefreshToken 5 | 6 | from accounts.managers import UserManager 7 | # Create your models here. 8 | 9 | AUTH_PROVIDERS ={'email':'email', 'google':'google', 'github':'github', 'linkedin':'linkedin'} 10 | 11 | class User(AbstractBaseUser, PermissionsMixin): 12 | id = models.BigAutoField(primary_key=True, editable=False) 13 | email = models.EmailField( 14 | max_length=255, verbose_name=_("Email Address"), unique=True 15 | ) 16 | first_name = models.CharField(max_length=100, verbose_name=_("First Name")) 17 | last_name = models.CharField(max_length=100, verbose_name=_("Last Name")) 18 | is_staff = models.BooleanField(default=False) 19 | is_superuser = models.BooleanField(default=False) 20 | is_verified=models.BooleanField(default=False) 21 | is_active = models.BooleanField(default=True) 22 | date_joined = models.DateTimeField(auto_now_add=True) 23 | last_login = models.DateTimeField(auto_now=True) 24 | auth_provider=models.CharField(max_length=50, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) 25 | 26 | USERNAME_FIELD = "email" 27 | 28 | REQUIRED_FIELDS = ["first_name", "last_name"] 29 | 30 | objects = UserManager() 31 | 32 | def tokens(self): 33 | refresh = RefreshToken.for_user(self) 34 | return { 35 | "refresh":str(refresh), 36 | "access":str(refresh.access_token) 37 | } 38 | 39 | 40 | def __str__(self): 41 | return self.email 42 | 43 | @property 44 | def get_full_name(self): 45 | return f"{self.first_name.title()} {self.last_name.title()}" 46 | 47 | 48 | class OneTimePassword(models.Model): 49 | user=models.OneToOneField(User, on_delete=models.CASCADE) 50 | otp=models.CharField(max_length=6) 51 | 52 | 53 | def __str__(self): 54 | return f"{self.user.first_name} - otp code" -------------------------------------------------------------------------------- /accounts/serializers.py: -------------------------------------------------------------------------------- 1 | 2 | import json 3 | from dataclasses import field 4 | from .models import User 5 | from rest_framework import serializers 6 | from string import ascii_lowercase, ascii_uppercase 7 | from django.contrib.auth import authenticate 8 | from rest_framework.exceptions import AuthenticationFailed 9 | from django.contrib.auth.tokens import PasswordResetTokenGenerator 10 | from django.utils.encoding import smart_str, force_str, smart_bytes 11 | from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode 12 | from django.contrib.sites.shortcuts import get_current_site 13 | from django.urls import reverse 14 | from .utils import send_normal_email 15 | from rest_framework_simplejwt.tokens import RefreshToken, TokenError 16 | 17 | 18 | class UserRegisterSerializer(serializers.ModelSerializer): 19 | password = serializers.CharField(max_length=68, min_length=6, write_only=True) 20 | password2= serializers.CharField(max_length=68, min_length=6, write_only=True) 21 | 22 | class Meta: 23 | model=User 24 | fields = ['email', 'first_name', 'last_name', 'password', 'password2'] 25 | 26 | def validate(self, attrs): 27 | password=attrs.get('password', '') 28 | password2 =attrs.get('password2', '') 29 | if password !=password2: 30 | raise serializers.ValidationError("passwords do not match") 31 | 32 | return attrs 33 | 34 | def create(self, validated_data): 35 | user= User.objects.create_user( 36 | email=validated_data['email'], 37 | first_name=validated_data.get('first_name'), 38 | last_name=validated_data.get('last_name'), 39 | password=validated_data.get('password') 40 | ) 41 | return user 42 | 43 | class LoginSerializer(serializers.ModelSerializer): 44 | email = serializers.EmailField(max_length=155, min_length=6) 45 | password=serializers.CharField(max_length=68, write_only=True) 46 | full_name=serializers.CharField(max_length=255, read_only=True) 47 | access_token=serializers.CharField(max_length=255, read_only=True) 48 | refresh_token=serializers.CharField(max_length=255, read_only=True) 49 | 50 | class Meta: 51 | model = User 52 | fields = ['email', 'password', 'full_name', 'access_token', 'refresh_token'] 53 | 54 | 55 | 56 | def validate(self, attrs): 57 | email = attrs.get('email') 58 | password = attrs.get('password') 59 | request=self.context.get('request') 60 | user = authenticate(request, email=email, password=password) 61 | if not user: 62 | raise AuthenticationFailed("invalid credential try again") 63 | if not user.is_verified: 64 | raise AuthenticationFailed("Email is not verified") 65 | tokens=user.tokens() 66 | return { 67 | 'email':user.email, 68 | 'full_name':user.get_full_name, 69 | "access_token":str(tokens.get('access')), 70 | "refresh_token":str(tokens.get('refresh')) 71 | } 72 | 73 | 74 | class PasswordResetRequestSerializer(serializers.Serializer): 75 | email = serializers.EmailField(max_length=255) 76 | 77 | class Meta: 78 | fields = ['email'] 79 | 80 | def validate(self, attrs): 81 | 82 | email = attrs.get('email') 83 | if User.objects.filter(email=email).exists(): 84 | user= User.objects.get(email=email) 85 | uidb64=urlsafe_base64_encode(smart_bytes(user.id)) 86 | token = PasswordResetTokenGenerator().make_token(user) 87 | request=self.context.get('request') 88 | current_site=get_current_site(request).domain 89 | relative_link =reverse('reset-password-confirm', kwargs={'uidb64':uidb64, 'token':token}) 90 | abslink=f"http://{current_site}{relative_link}" 91 | print(abslink) 92 | email_body=f"Hi {user.first_name} use the link below to reset your password {abslink}" 93 | data={ 94 | 'email_body':email_body, 95 | 'email_subject':"Reset your Password", 96 | 'to_email':user.email 97 | } 98 | send_normal_email(data) 99 | 100 | return super().validate(attrs) 101 | 102 | 103 | class SetNewPasswordSerializer(serializers.Serializer): 104 | password=serializers.CharField(max_length=100, min_length=6, write_only=True) 105 | confirm_password=serializers.CharField(max_length=100, min_length=6, write_only=True) 106 | uidb64=serializers.CharField(min_length=1, write_only=True) 107 | token=serializers.CharField(min_length=3, write_only=True) 108 | 109 | class Meta: 110 | fields = ['password', 'confirm_password', 'uidb64', 'token'] 111 | 112 | def validate(self, attrs): 113 | try: 114 | token=attrs.get('token') 115 | uidb64=attrs.get('uidb64') 116 | password=attrs.get('password') 117 | confirm_password=attrs.get('confirm_password') 118 | 119 | user_id=force_str(urlsafe_base64_decode(uidb64)) 120 | user=User.objects.get(id=user_id) 121 | if not PasswordResetTokenGenerator().check_token(user, token): 122 | raise AuthenticationFailed("reset link is invalid or has expired", 401) 123 | if password != confirm_password: 124 | raise AuthenticationFailed("passwords do not match") 125 | user.set_password(password) 126 | user.save() 127 | return user 128 | except Exception as e: 129 | return AuthenticationFailed("link is invalid or has expired") 130 | 131 | 132 | 133 | class LogoutUserSerializer(serializers.Serializer): 134 | refresh_token=serializers.CharField() 135 | 136 | default_error_message = { 137 | 'bad_token': ('Token is expired or invalid') 138 | } 139 | 140 | def validate(self, attrs): 141 | self.token = attrs.get('refresh_token') 142 | 143 | return attrs 144 | 145 | def save(self, **kwargs): 146 | try: 147 | token=RefreshToken(self.token) 148 | token.blacklist() 149 | except TokenError: 150 | return self.fail('bad_token') 151 | 152 | 153 | 154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /accounts/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /accounts/urls.py: -------------------------------------------------------------------------------- 1 | from unicodedata import name 2 | from django.urls import path 3 | from .views import ( 4 | RegisterView, 5 | VerifyUserEmail, 6 | LoginUserView, 7 | TestingAuthenticatedReq, 8 | PasswordResetConfirm, 9 | PasswordResetRequestView,SetNewPasswordView, LogoutApiView) 10 | from rest_framework_simplejwt.views import (TokenRefreshView,) 11 | 12 | urlpatterns = [ 13 | path('register/', RegisterView.as_view(), name='register'), 14 | path('verify-email/', VerifyUserEmail.as_view(), name='verify'), 15 | path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), 16 | path('login/', LoginUserView.as_view(), name='login-user'), 17 | path('get-something/', TestingAuthenticatedReq.as_view(), name='just-for-testing'), 18 | path('password-reset/', PasswordResetRequestView.as_view(), name='password-reset'), 19 | path('password-reset-confirm///', PasswordResetConfirm.as_view(), name='reset-password-confirm'), 20 | path('set-new-password/', SetNewPasswordView.as_view(), name='set-new-password'), 21 | path('logout/', LogoutApiView.as_view(), name='logout') 22 | ] -------------------------------------------------------------------------------- /accounts/utils.py: -------------------------------------------------------------------------------- 1 | from django.core.mail import EmailMessage 2 | import random 3 | from django.conf import settings 4 | from .models import User, OneTimePassword 5 | from django.contrib.sites.shortcuts import get_current_site 6 | 7 | 8 | 9 | def send_generated_otp_to_email(email, request): 10 | subject = "One time passcode for Email verification" 11 | otp=random.randint(1000, 9999) 12 | current_site=get_current_site(request).domain 13 | user = User.objects.get(email=email) 14 | email_body=f"Hi {user.first_name} thanks for signing up on {current_site} please verify your email with the \n one time passcode {otp}" 15 | from_email=settings.EMAIL_HOST 16 | otp_obj=OneTimePassword.objects.create(user=user, otp=otp) 17 | #send the email 18 | d_email=EmailMessage(subject=subject, body=email_body, from_email=from_email, to=[user.email]) 19 | d_email.send() 20 | 21 | 22 | def send_normal_email(data): 23 | email=EmailMessage( 24 | subject=data['email_subject'], 25 | body=data['email_body'], 26 | from_email=settings.EMAIL_HOST_USER, 27 | to=[data['to_email']] 28 | ) 29 | email.send() -------------------------------------------------------------------------------- /accounts/views.py: -------------------------------------------------------------------------------- 1 | from ast import Expression 2 | from multiprocessing import context 3 | from django.shortcuts import render 4 | from rest_framework.generics import GenericAPIView 5 | from rest_framework.response import Response 6 | from accounts.models import OneTimePassword 7 | from accounts.serializers import PasswordResetRequestSerializer,LogoutUserSerializer, UserRegisterSerializer, LoginSerializer, SetNewPasswordSerializer 8 | from rest_framework import status 9 | from .utils import send_generated_otp_to_email 10 | from django.utils.http import urlsafe_base64_decode 11 | from django.utils.encoding import smart_str, DjangoUnicodeDecodeError 12 | from django.contrib.auth.tokens import PasswordResetTokenGenerator 13 | from rest_framework.permissions import IsAuthenticated 14 | from .models import User 15 | # Create your views here. 16 | 17 | 18 | class RegisterView(GenericAPIView): 19 | serializer_class = UserRegisterSerializer 20 | 21 | def post(self, request): 22 | user = request.data 23 | serializer=self.serializer_class(data=user) 24 | if serializer.is_valid(raise_exception=True): 25 | serializer.save() 26 | user_data=serializer.data 27 | send_generated_otp_to_email(user_data['email'], request) 28 | return Response({ 29 | 'data':user_data, 30 | 'message':'thanks for signing up a passcode has be sent to verify your email' 31 | }, status=status.HTTP_201_CREATED) 32 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 33 | 34 | 35 | 36 | 37 | class VerifyUserEmail(GenericAPIView): 38 | def post(self, request): 39 | try: 40 | passcode = request.data.get('otp') 41 | user_pass_obj=OneTimePassword.objects.get(otp=passcode) 42 | user=user_pass_obj.user 43 | if not user.is_verified: 44 | user.is_verified=True 45 | user.save() 46 | return Response({ 47 | 'message':'account email verified successfully' 48 | }, status=status.HTTP_200_OK) 49 | return Response({'message':'passcode is invalid user is already verified'}, status=status.HTTP_204_NO_CONTENT) 50 | except OneTimePassword.DoesNotExist as identifier: 51 | return Response({'message':'passcode not provided'}, status=status.HTTP_400_BAD_REQUEST) 52 | 53 | 54 | class LoginUserView(GenericAPIView): 55 | serializer_class=LoginSerializer 56 | def post(self, request): 57 | serializer= self.serializer_class(data=request.data, context={'request': request}) 58 | serializer.is_valid(raise_exception=True) 59 | return Response(serializer.data, status=status.HTTP_200_OK) 60 | 61 | 62 | class PasswordResetRequestView(GenericAPIView): 63 | serializer_class=PasswordResetRequestSerializer 64 | 65 | def post(self, request): 66 | serializer=self.serializer_class(data=request.data, context={'request':request}) 67 | serializer.is_valid(raise_exception=True) 68 | return Response({'message':'we have sent you a link to reset your password'}, status=status.HTTP_200_OK) 69 | # return Response({'message':'user with that email does not exist'}, status=status.HTTP_400_BAD_REQUEST) 70 | 71 | 72 | 73 | 74 | class PasswordResetConfirm(GenericAPIView): 75 | 76 | def get(self, request, uidb64, token): 77 | try: 78 | user_id=smart_str(urlsafe_base64_decode(uidb64)) 79 | user=User.objects.get(id=user_id) 80 | 81 | if not PasswordResetTokenGenerator().check_token(user, token): 82 | return Response({'message':'token is invalid or has expired'}, status=status.HTTP_401_UNAUTHORIZED) 83 | return Response({'success':True, 'message':'credentials is valid', 'uidb64':uidb64, 'token':token}, status=status.HTTP_200_OK) 84 | 85 | except DjangoUnicodeDecodeError as identifier: 86 | return Response({'message':'token is invalid or has expired'}, status=status.HTTP_401_UNAUTHORIZED) 87 | 88 | class SetNewPasswordView(GenericAPIView): 89 | serializer_class=SetNewPasswordSerializer 90 | 91 | def patch(self, request): 92 | serializer=self.serializer_class(data=request.data) 93 | serializer.is_valid(raise_exception=True) 94 | return Response({'success':True, 'message':"password reset is succesful"}, status=status.HTTP_200_OK) 95 | 96 | 97 | class TestingAuthenticatedReq(GenericAPIView): 98 | permission_classes=[IsAuthenticated] 99 | 100 | def get(self, request): 101 | 102 | data={ 103 | 'msg':'its works' 104 | } 105 | return Response(data, status=status.HTTP_200_OK) 106 | 107 | class LogoutApiView(GenericAPIView): 108 | serializer_class=LogoutUserSerializer 109 | permission_classes = [IsAuthenticated] 110 | 111 | def post(self, request): 112 | serializer=self.serializer_class(data=request.data) 113 | serializer.is_valid(raise_exception=True) 114 | serializer.save() 115 | return Response(status=status.HTTP_204_NO_CONTENT) 116 | -------------------------------------------------------------------------------- /django_rest_auth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/django_rest_auth/__init__.py -------------------------------------------------------------------------------- /django_rest_auth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for django_rest_auth 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.1/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', 'django_rest_auth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_rest_auth/settings.py: -------------------------------------------------------------------------------- 1 | import environ 2 | from pathlib import Path 3 | from datetime import timedelta 4 | 5 | env = environ.Env( 6 | # set casting, default value 7 | DEBUG=(bool, False) 8 | ) 9 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 10 | BASE_DIR = Path(__file__).resolve().parent.parent 11 | 12 | # Take environment variables from .env file 13 | environ.Env.read_env(BASE_DIR / '.env') 14 | 15 | # Quick-start development settings - unsuitable for production 16 | # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ 17 | 18 | # SECURITY WARNING: keep the secret key used in production secret! 19 | SECRET_KEY = env('SECRET_KEY') 20 | # SECURITY WARNING: don't run with debug turned on in production! 21 | 22 | 23 | # False if not in os.environ because of casting above 24 | DEBUG = env('DEBUG') 25 | 26 | 27 | ALLOWED_HOSTS = ['*', 'http://localhost:3000'] 28 | 29 | 30 | # Application definition 31 | 32 | INSTALLED_APPS = [ 33 | 'django.contrib.admin', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sessions', 37 | 'django.contrib.messages', 38 | 'django.contrib.staticfiles', 39 | 'accounts', 40 | 'social_accounts', 41 | 'rest_framework', 42 | 'corsheaders', 43 | 'rest_framework_simplejwt.token_blacklist', 44 | 45 | ] 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | "corsheaders.middleware.CorsMiddleware", 51 | 'django.middleware.common.CommonMiddleware', 52 | 'django.middleware.csrf.CsrfViewMiddleware', 53 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 54 | 'django.contrib.messages.middleware.MessageMiddleware', 55 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 56 | ] 57 | 58 | CORS_ALLOW_ALL_ORIGINS=True 59 | CORS_ALLOW_CREDENTIALS=True 60 | CSRF_TRUSTED_ORIGINS = [ 61 | "http://localhost:3000", 62 | ] 63 | ROOT_URLCONF = 'django_rest_auth.urls' 64 | 65 | 66 | TEMPLATES = [ 67 | { 68 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 69 | 'DIRS': [], 70 | 'APP_DIRS': True, 71 | 'OPTIONS': { 72 | 'context_processors': [ 73 | 'django.template.context_processors.debug', 74 | 'django.template.context_processors.request', 75 | 'django.contrib.auth.context_processors.auth', 76 | 'django.contrib.messages.context_processors.messages', 77 | ], 78 | }, 79 | }, 80 | ] 81 | 82 | WSGI_APPLICATION = 'django_rest_auth.wsgi.application' 83 | 84 | AUTH_USER_MODEL='accounts.User' 85 | 86 | 87 | # Database 88 | # https://docs.djangoproject.com/en/4.1/ref/settings/#databases 89 | 90 | DATABASES = { 91 | 'default': { 92 | 'ENGINE': 'django.db.backends.sqlite3', 93 | 'NAME': BASE_DIR / 'db.sqlite3', 94 | } 95 | } 96 | 97 | REST_FRAMEWORK={ 98 | 'NON_FIELD_ERRORS_KEY':'error', 99 | 'DEFAULT_AUTHENTICATION_CLASSES': ( 100 | 'rest_framework.authentication.SessionAuthentication', 101 | 'rest_framework_simplejwt.authentication.JWTAuthentication', 102 | ) 103 | 104 | } 105 | SIMPLE_JWT = { 106 | 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 107 | 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 108 | 'AUTH_HEADER_TYPES': ('Bearer',), 109 | } 110 | 111 | DOMAIN='localhost:3000' 112 | SITE_NAME = 'Henry Ultimate Authentication Course' 113 | 114 | GOOGLE_CLIENT_ID=env("GOOGLE_CLIENT_ID") 115 | GOOGLE_CLIENT_SECRET=env("GOOGLE_CLIENT_SECRET") 116 | GITHUB_SECRET=env("GITHUB_SECRET") 117 | GITHUB_CLIENT_ID=env("GITHUB_CLIENT_ID") 118 | SOCIAL_AUTH_PASSWORD="jgk348030gjw03" 119 | 120 | 121 | # Password validation 122 | # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators 123 | 124 | AUTH_PASSWORD_VALIDATORS = [ 125 | { 126 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 127 | }, 128 | { 129 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 130 | }, 131 | { 132 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 133 | }, 134 | { 135 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 136 | }, 137 | ] 138 | 139 | 140 | # Internationalization 141 | # https://docs.djangoproject.com/en/4.1/topics/i18n/ 142 | 143 | LANGUAGE_CODE = 'en-us' 144 | 145 | TIME_ZONE = 'UTC' 146 | 147 | USE_I18N = True 148 | 149 | USE_TZ = True 150 | 151 | 152 | # Static files (CSS, JavaScript, Images) 153 | # https://docs.djangoproject.com/en/4.1/howto/static-files/ 154 | 155 | STATIC_URL = 'static/' 156 | 157 | # Default primary key field type 158 | # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field 159 | 160 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 161 | EMAIL_HOST='smtp.mailtrap.io' 162 | EMAIL_HOST_USER=env('EMAIL_HOST_USER') 163 | EMAIL_HOST_PASSWORD=env('EMAIL_HOST_PASSWORD') 164 | DEFAULT_FROM_EMAIL='info@henryjwtauth.com' 165 | EMAIL_USE_TLS=True 166 | EMAIL_PORT = '2525' -------------------------------------------------------------------------------- /django_rest_auth/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.contrib import admin 3 | from django.urls import path, include 4 | 5 | urlpatterns = [ 6 | path('admin/', admin.site.urls), 7 | path('api/v1/auth/', include("accounts.urls")), 8 | path('api/v1/auth/', include('social_accounts.urls')) 9 | ] 10 | -------------------------------------------------------------------------------- /django_rest_auth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_rest_auth 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.1/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', 'django_rest_auth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /frontend/client-app/.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/client-app/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 your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may 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/client-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@react-oauth/google": "^0.2.8", 7 | "@testing-library/jest-dom": "^5.16.5", 8 | "@testing-library/react": "^13.4.0", 9 | "@testing-library/user-event": "^13.5.0", 10 | "axios": "^1.1.3", 11 | "dayjs": "^1.11.6", 12 | "jwt-decode": "^3.1.2", 13 | "proxy": "^1.0.2", 14 | "react": "^18.2.0", 15 | "react-dom": "^18.2.0", 16 | "react-github-login": "^1.0.3", 17 | "react-google-login": "^5.2.2", 18 | "react-router-dom": "^6.4.2", 19 | "react-scripts": "5.0.1", 20 | "react-toastify": "^9.1.1", 21 | "web-vitals": "^2.1.4" 22 | }, 23 | "scripts": { 24 | "start": "react-scripts start", 25 | "build": "react-scripts build", 26 | "test": "react-scripts test", 27 | "eject": "react-scripts eject" 28 | }, 29 | "eslintConfig": { 30 | "extends": [ 31 | "react-app", 32 | "react-app/jest" 33 | ] 34 | }, 35 | "browserslist": { 36 | "production": [ 37 | ">0.2%", 38 | "not dead", 39 | "not op_mini all" 40 | ], 41 | "development": [ 42 | "last 1 chrome version", 43 | "last 1 firefox version", 44 | "last 1 safari version" 45 | ] 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /frontend/client-app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/frontend/client-app/public/favicon.ico -------------------------------------------------------------------------------- /frontend/client-app/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 19 | 28 | React App 29 | 30 | 31 | 32 |
33 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /frontend/client-app/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/frontend/client-app/public/logo192.png -------------------------------------------------------------------------------- /frontend/client-app/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/frontend/client-app/public/logo512.png -------------------------------------------------------------------------------- /frontend/client-app/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/client-app/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/client-app/src/App.css: -------------------------------------------------------------------------------- 1 | 2 | 3 | .auth-btn-container{ 4 | background-color: #dddddd; 5 | position: relative; 6 | display: flex; 7 | justify-content: center; 8 | align-items: center; 9 | flex-direction: column; 10 | height: 100vh; 11 | width: 100vw; 12 | } 13 | 14 | .form-container{ 15 | width: 100%; 16 | height: 100vh; 17 | display: flex; 18 | align-items: center; 19 | justify-content: center; 20 | padding: 20px auto; 21 | } 22 | .wrapper{ 23 | margin-top: 2rem; 24 | max-width: 600px; 25 | padding: 0 20px; 26 | display: flex; 27 | justify-content: center; 28 | flex-direction: column; 29 | align-items: center; 30 | } 31 | 32 | form{ 33 | padding: 22px; 34 | margin-top: 10px; 35 | margin-bottom: 1rem; 36 | margin-right: auto; 37 | margin-left: auto; 38 | max-width: 600px; 39 | width: 60%; 40 | background-color: #fff; 41 | border-radius: 10px; 42 | box-shadow: 0 15px 35px rgba(50,50,93,.1),0 5px 15px rgba(0,0,0,.07); 43 | 44 | } 45 | .googleContainer{ 46 | width: 100%; 47 | padding: 10px; 48 | display: flex; 49 | justify-content: center; 50 | margin-bottom: 2rem; 51 | 52 | } 53 | .githubContainer{ 54 | width: 100%; 55 | padding: 10px; 56 | display: flex; 57 | justify-content: center; 58 | margin-bottom: 10px; 59 | } 60 | .githubContainer button{ 61 | padding: 4px 8px; 62 | width: 280px; 63 | height: 44px; 64 | font-weight: 600; 65 | border-radius: 10px; 66 | } 67 | .githubContainer button:hover{ 68 | background-color: #3d3d3d; 69 | color: #fff; 70 | cursor: pointer; 71 | } 72 | 73 | 74 | .form-group{ 75 | width: 100%; 76 | margin-bottom: 10px; 77 | } 78 | h2 { 79 | border-bottom: 1px solid white; 80 | color: #3d3d3d; 81 | font-family: sans-serif; 82 | font-size: 34px; 83 | font-weight: 600; 84 | line-height: 24px; 85 | padding: 8px; 86 | text-align: center; 87 | } 88 | .container{ 89 | width: 100%; 90 | display: flex; 91 | justify-content: center; 92 | flex-direction: column; 93 | align-items: center; 94 | } 95 | 96 | input { 97 | border: 1px solid #d9d9d9; 98 | border-radius: 4px; 99 | box-sizing: border-box; 100 | padding: 12px; 101 | width: 100%; 102 | outline: none; 103 | } 104 | input:focus{ 105 | border-color: #848fdf; 106 | border-width: 1px; 107 | } 108 | 109 | label { 110 | color: #3d3d3d; 111 | display: block; 112 | font-family: sans-serif; 113 | font-size: 14px; 114 | font-weight: 500; 115 | margin-bottom: 5px; 116 | } 117 | .submitButton { 118 | background-color: #6976d9; 119 | color: white; 120 | font-family: sans-serif; 121 | font-size: 14px; 122 | margin: 20px 0px; 123 | } 124 | .vbtn{ 125 | padding:10px 22px; 126 | outline: none; 127 | font-size: 14px; 128 | font-weight: 600; 129 | background-color: #6976d9; 130 | border: none; 131 | color: #fff; 132 | border-radius: 5px; 133 | } 134 | h3{ 135 | margin: 0 136 | } 137 | .logout-btn{ 138 | padding:10px 22px; 139 | outline: none; 140 | width: 164px; 141 | font-size: 14px; 142 | font-weight: 600; 143 | background-color: #e7461e; 144 | border: none; 145 | color: #fff; 146 | border-radius: 5px; 147 | } 148 | -------------------------------------------------------------------------------- /frontend/client-app/src/App.js: -------------------------------------------------------------------------------- 1 | import './App.css'; 2 | import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; 3 | import Profile from './components/Profile'; 4 | import Signup from './components/Signup'; 5 | import Login from './components/Login'; 6 | import VerifyEmail from './components/VerifyEmail'; 7 | import { ToastContainer} from 'react-toastify'; 8 | import 'react-toastify/dist/ReactToastify.css'; 9 | import PasswordResetRequest from './components/PasswordResetRequest'; 10 | import ResetPassword from './components/ResetPassword'; 11 | 12 | function App() { 13 | return ( 14 |
15 | 16 | 17 | 18 | }/> 19 | }/> 20 | }/> 21 | }/> 22 | }/> 23 | }/> 24 | 25 | 26 |
27 | ); 28 | } 29 | 30 | export default App; 31 | -------------------------------------------------------------------------------- /frontend/client-app/src/components/Login.jsx: -------------------------------------------------------------------------------- 1 | import React, {useEffect, useState} from 'react' 2 | import { Link, useNavigate, useSearchParams } from "react-router-dom"; 3 | import { toast } from 'react-toastify'; 4 | import AxiosInstance from "../utils/AxiosInstance"; 5 | 6 | const Login = () => { 7 | const navigate=useNavigate() 8 | const [searchparams] = useSearchParams() 9 | const [logindata, setLogindata]=useState({ 10 | email:"", 11 | password:"" 12 | }) 13 | 14 | 15 | const handleOnchange=(e)=>{ 16 | setLogindata({...logindata, [e.target.name]:e.target.value}) 17 | } 18 | const handleLoginWithGoogle = (response)=>{ 19 | console.log("id_token", response.credential) 20 | } 21 | 22 | const handleLoginWithGithub =()=>{ 23 | window.location.assign(`https://github.com/login/oauth/authorize/?client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}`) 24 | } 25 | 26 | const send_github__code_to_server = async()=>{ 27 | if (searchparams) { 28 | try { 29 | const urlparam = searchparams.get('code') 30 | const resp = await AxiosInstance.post('auth/github/', {'code':urlparam}) 31 | const result = resp.data 32 | console.log('server res: ',result) 33 | if (resp.status===200) { 34 | const user ={ 35 | 'email':result.email, 36 | 'names':result.full_name 37 | } 38 | localStorage.setItem('token', JSON.stringify(result.access_token)) 39 | localStorage.setItem('refresh_token', JSON.stringify(result.refresh_token)) 40 | localStorage.setItem('user', JSON.stringify(user)) 41 | navigate('/dashboard') 42 | toast.success('login successful') 43 | } 44 | } catch (error) { 45 | if (error.response) { 46 | 47 | console.log(error.response.data); 48 | toast.error(error.response.data.detail) 49 | } 50 | } 51 | } 52 | 53 | } 54 | let code =searchparams.get('code') 55 | useEffect(() => { 56 | if (code) { 57 | send_github__code_to_server() 58 | } 59 | }, [code]) 60 | 61 | 62 | 63 | useEffect(() => { 64 | /* global google */ 65 | google.accounts.id.initialize({ 66 | client_id:process.env.REACT_APP_GOOGLE_CLIENT_ID, 67 | callback: handleLoginWithGoogle 68 | }); 69 | google.accounts.id.renderButton( 70 | document.getElementById("signInDiv"), 71 | {theme:"outline", size:"large", text:"continue_with", shape:"circle", width:"280"} 72 | ); 73 | 74 | }, []) 75 | 76 | 77 | const handleSubmit = async(e)=>{ 78 | e.preventDefault() 79 | if (logindata) { 80 | const res = await AxiosInstance.post('auth/login/', logindata) 81 | const response= res.data 82 | const user={ 83 | 'full_name':response.full_name, 84 | 'email':response.email 85 | } 86 | 87 | 88 | if (res.status === 200) { 89 | localStorage.setItem('token', JSON.stringify(response.access_token)) 90 | localStorage.setItem('refresh_token', JSON.stringify(response.refresh_token)) 91 | localStorage.setItem('user', JSON.stringify(user)) 92 | await navigate('/dashboard') 93 | toast.success('login successful') 94 | }else{ 95 | toast.error('something went wrong') 96 | } 97 | } 98 | 99 | } 100 | 101 | return ( 102 |
103 | 104 |
105 |
106 |

Login into your account

107 |
108 |
109 | 110 | 115 | 116 |
117 | 118 |
119 | 120 | 125 |
126 | 127 | 128 |

forgot password

129 |
130 |

Or

131 |
132 | 133 |
134 |
135 |
136 |
137 |
138 |
139 | 140 |
141 | ) 142 | } 143 | 144 | export default Login -------------------------------------------------------------------------------- /frontend/client-app/src/components/PasswordResetRequest.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | import { toast } from 'react-toastify' 3 | import AxiosInstance from '../utils/AxiosInstance' 4 | 5 | const PasswordResetRequest = () => { 6 | const [email, setEmail]=useState("") 7 | 8 | const handleSubmit = async(e)=>{ 9 | e.preventDefault() 10 | if (email) { 11 | const res = await AxiosInstance.post('auth/password-reset/', {'email':email}) 12 | if (res.status === 200) { 13 | console.log(res.data) 14 | toast.success('a link to reset your password has be sent to your email') 15 | 16 | } 17 | setEmail("") 18 | } 19 | 20 | 21 | 22 | } 23 | 24 | 25 | return ( 26 |
27 |

Enter your registered email

28 |
29 |
30 |
31 | 32 | setEmail(e.target.value)} 37 | /> 38 |
39 | 40 |
41 |
42 |
43 | ) 44 | } 45 | 46 | export default PasswordResetRequest -------------------------------------------------------------------------------- /frontend/client-app/src/components/Profile.jsx: -------------------------------------------------------------------------------- 1 | import React, {useEffect} from 'react' 2 | import { useNavigate } from "react-router-dom"; 3 | import { toast } from 'react-toastify'; 4 | import AxiosInstance from "../utils/AxiosInstance"; 5 | 6 | const Profile = () => { 7 | const jwt=localStorage.getItem('token') 8 | const user = JSON.parse(localStorage.getItem('user')) 9 | const navigate = useNavigate(); 10 | 11 | useEffect(() => { 12 | if (jwt === null && !user) { 13 | navigate('/login') 14 | }else{ 15 | getSomeData() 16 | } 17 | 18 | }, [jwt, user]) 19 | 20 | const getSomeData =async ()=>{ 21 | const res =await AxiosInstance.get('auth/get-something/') 22 | console.log(res.data) 23 | } 24 | const refresh=JSON.parse(localStorage.getItem('refresh_token')) 25 | 26 | 27 | const handleLogout = async ()=>{ 28 | const res = await AxiosInstance.post('auth/logout/', {'refresh_token':refresh}) 29 | if (res.status === 204) { 30 | localStorage.removeItem('token') 31 | localStorage.removeItem('refresh_token') 32 | localStorage.removeItem('user') 33 | navigate('/login') 34 | toast.warn("logout successful") 35 | } 36 | } 37 | return ( 38 |
39 |

hi {user && user.full_name}

40 |

welcome to your profile

41 | 42 |
43 | ) 44 | } 45 | 46 | export default Profile -------------------------------------------------------------------------------- /frontend/client-app/src/components/ResetPassword.jsx: -------------------------------------------------------------------------------- 1 | import React, {useState} from 'react' 2 | import { useParams, useNavigate } from "react-router-dom"; 3 | import { toast } from 'react-toastify'; 4 | import AxiosInstance from '../utils/AxiosInstance'; 5 | 6 | const ResetPassword = () => { 7 | const navigate=useNavigate() 8 | const {uid, token}=useParams() 9 | const [newpasswords, setNewPassword]=useState({ 10 | password:"", 11 | confirm_password:"", 12 | }) 13 | const {password, confirm_password}=newpasswords 14 | 15 | const handleChange=(e)=>{ 16 | setNewPassword({...newpasswords, [e.target.name]:e.target.value}) 17 | } 18 | 19 | const data={ 20 | "password":password, 21 | "confirm_password":confirm_password, 22 | "uidb64":uid, 23 | "token": token, 24 | } 25 | const handleSubmit =async (e)=>{ 26 | e.preventDefault() 27 | if (data) { 28 | const res = await AxiosInstance.patch('auth/set-new-password/', data) 29 | const response = res.data 30 | if (res.status === 200) { 31 | navigate('/login') 32 | toast.success(response.message) 33 | } 34 | console.log(response) 35 | } 36 | 37 | } 38 | return ( 39 |
40 |
41 |
42 |

Enter your New Password

43 |
44 |
45 | 46 | 52 |
53 |
54 | 55 | 61 |
62 | 63 |
64 |
65 |
66 |
67 | ) 68 | } 69 | 70 | export default ResetPassword -------------------------------------------------------------------------------- /frontend/client-app/src/components/Signup.jsx: -------------------------------------------------------------------------------- 1 | import React, {useEffect, useState} from 'react' 2 | import axios from "axios" 3 | import { toast } from "react-toastify"; 4 | import { useNavigate } from "react-router-dom"; 5 | 6 | const Signup = () => { 7 | const navigate=useNavigate() 8 | const [formdata, setFormdata]=useState({ 9 | email:"", 10 | first_name:"", 11 | last_name:"", 12 | password:"", 13 | password2:"" 14 | }) 15 | const [error, setError]=useState('') 16 | 17 | const handleOnchange = (e)=>{ 18 | setFormdata({...formdata, [e.target.name]:e.target.value}) 19 | } 20 | 21 | 22 | const handleSigninWithGoogle = async (response)=>{ 23 | const payload=response.credential 24 | const server_res= await axios.post("http://localhost:8000/api/v1/auth/google/", {'access_token':payload}) 25 | console.log(server_res.data) 26 | } 27 | 28 | useEffect(() => { 29 | /* global google */ 30 | google.accounts.id.initialize({ 31 | client_id:process.env.REACT_APP_GOOGLE_CLIENT_ID, 32 | callback: handleSigninWithGoogle 33 | }); 34 | google.accounts.id.renderButton( 35 | document.getElementById("signInDiv"), 36 | {theme:"outline", size:"large", text:"continue_with", shape:"circle", width:"280"} 37 | ); 38 | 39 | }, []) 40 | 41 | const {email, first_name, last_name, password, password2}=formdata 42 | 43 | const handleSubmit =async (e)=>{ 44 | e.preventDefault() 45 | const response = await axios.post('http://localhost:8000/api/v1/auth/register/',formdata) 46 | console.log(response.data) 47 | const result=response.data 48 | if (response.status === 201) { 49 | navigate("/otp/verify") 50 | toast.success(result.message) 51 | } 52 | 53 | 54 | 55 | } 56 | 57 | return ( 58 |
59 |
60 |
61 |

create account

62 |
63 |
64 | 65 | 70 |
71 |
72 | 73 | 78 |
79 |
80 | 81 | 86 |
87 |
88 | 89 | 94 |
95 |
96 | 97 | 102 |
103 | 104 | 105 |
106 |

Or

107 |
108 | 109 |
110 |
111 |
112 |
113 |
114 |
115 | 116 |
117 | ) 118 | } 119 | 120 | export default Signup -------------------------------------------------------------------------------- /frontend/client-app/src/components/VerifyEmail.jsx: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import React, {useState} from 'react' 3 | import { useNavigate } from "react-router-dom"; 4 | import { toast } from "react-toastify"; 5 | 6 | const VerifyEmail = () => { 7 | const [otp, setOtp]=useState("") 8 | const navigate=useNavigate() 9 | 10 | const handleOtpSubmit = async(e)=>{ 11 | e.preventDefault() 12 | if (otp) { 13 | const res = await axios.post('http://localhost:8000/api/v1/auth/verify-email/', {'otp':otp}) 14 | const resp = res.data 15 | if (res.status === 200) { 16 | navigate('/login') 17 | toast.success(resp.message) 18 | } 19 | 20 | } 21 | 22 | } 23 | return ( 24 |
25 |
26 |
27 |
28 | 29 | setOtp(e.target.value)} 34 | /> 35 |
36 | 37 |
38 |
39 |
40 | ) 41 | } 42 | 43 | export default VerifyEmail -------------------------------------------------------------------------------- /frontend/client-app/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | background: #f2f2f2; 5 | scroll-behavior: smooth; 6 | } 7 | 8 | code { 9 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 10 | monospace; 11 | } 12 | -------------------------------------------------------------------------------- /frontend/client-app/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | 6 | 7 | const root = ReactDOM.createRoot(document.getElementById('root')); 8 | root.render( 9 | 10 | ); 11 | 12 | -------------------------------------------------------------------------------- /frontend/client-app/src/utils/AxiosInstance.js: -------------------------------------------------------------------------------- 1 | import axios from "axios" 2 | import jwt_decode from "jwt-decode"; 3 | import dayjs from "dayjs"; 4 | 5 | 6 | let accessToken=localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')) : "" 7 | let refresh_token=localStorage.getItem('refresh_token') ? JSON.parse(localStorage.getItem('refresh_token')) : "" 8 | 9 | console.log('access: ',accessToken) 10 | const baseURL= 'http://localhost:8000/api/v1/' 11 | 12 | const AxiosInstance = axios.create({ 13 | baseURL:baseURL, 14 | 'Content-type':'application/json', 15 | headers: {Authorization: localStorage.getItem('token') ? `Bearer ${accessToken}` : ""}, 16 | }); 17 | 18 | AxiosInstance.interceptors.request.use(async req =>{ 19 | if (accessToken) { 20 | // accessToken=localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')) : null 21 | req.headers.Authorization = localStorage.getItem('token') ? `Bearer ${accessToken}` : "" 22 | const user = jwt_decode(accessToken) 23 | const isExpired=dayjs.unix(user.exp).diff(dayjs()) < 1 24 | if(!isExpired) return req 25 | const resp =await axios.post(`${baseURL}auth/token/refresh/`, { 26 | refresh:refresh_token 27 | }) 28 | console.log('new_accesstoken: ',resp.data.access) 29 | localStorage.setItem('token', JSON.stringify(resp.data.access)) 30 | req.headers.Authorization = `Bearer ${resp.data.access}` 31 | return req 32 | }else{ 33 | req.headers.Authorization = localStorage.getItem('token') ? `Bearer ${JSON.parse(localStorage.getItem('token'))}` : " " 34 | return req 35 | } 36 | 37 | 38 | 39 | }) 40 | 41 | export default AxiosInstance; -------------------------------------------------------------------------------- /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', 'django_rest_auth.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 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.5.2 2 | cachetools==5.2.0 3 | certifi==2022.9.24 4 | charset-normalizer==2.1.1 5 | Django==4.1.2 6 | django-cors-headers==3.13.0 7 | django-environ==0.9.0 8 | djangorestframework==3.14.0 9 | djangorestframework-simplejwt==5.2.2 10 | google-api-core==2.10.2 11 | google-api-python-client==2.65.0 12 | google-auth==2.14.0 13 | google-auth-httplib2==0.1.0 14 | googleapis-common-protos==1.56.4 15 | httplib2==0.21.0 16 | idna==3.4 17 | protobuf==4.21.9 18 | pyasn1==0.4.8 19 | pyasn1-modules==0.2.8 20 | PyJWT==2.6.0 21 | pyparsing==3.0.9 22 | pytz==2022.5 23 | requests==2.28.1 24 | rsa==4.9 25 | six==1.16.0 26 | sqlparse==0.4.3 27 | tzdata==2022.6 28 | uritemplate==4.1.1 29 | urllib3==1.26.12 30 | -------------------------------------------------------------------------------- /social_accounts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/social_accounts/__init__.py -------------------------------------------------------------------------------- /social_accounts/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /social_accounts/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SocialAccountsConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'social_accounts' 7 | -------------------------------------------------------------------------------- /social_accounts/github.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from django.conf import settings 3 | from rest_framework.exceptions import AuthenticationFailed 4 | 5 | 6 | 7 | class Github(): 8 | @staticmethod 9 | def exchange_code_for_token(code): 10 | params_payload={"client_id":settings.GITHUB_CLIENT_ID, "client_secret":settings.GITHUB_SECRET, "code":code} 11 | get_access_token=requests.post("https://github.com/login/oauth/access_token", params=params_payload, headers={'Accept': 'application/json'}) 12 | payload=get_access_token.json() 13 | token=payload.get('access_token') 14 | return token 15 | 16 | 17 | @staticmethod 18 | def get_github_user(access_token): 19 | try: 20 | headers={'Authorization': f'Bearer {access_token}'} 21 | resp = requests.get('https://api.github.com/user', headers=headers) 22 | user_data=resp.json() 23 | return user_data 24 | except: 25 | raise AuthenticationFailed("invalid access_token", 401) 26 | -------------------------------------------------------------------------------- /social_accounts/helpers.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from google.auth.transport import requests 3 | from google.oauth2 import id_token 4 | from accounts.models import User 5 | from django.contrib.auth import authenticate 6 | from django.conf import settings 7 | from rest_framework.exceptions import AuthenticationFailed 8 | 9 | 10 | 11 | class Google(): 12 | @staticmethod 13 | def validate(access_token): 14 | try: 15 | id_info=id_token.verify_oauth2_token(access_token, requests.Request()) 16 | if 'accounts.google.com' in id_info['iss']: 17 | return id_info 18 | except: 19 | return "the token is either invalid or has expired" 20 | 21 | 22 | 23 | 24 | 25 | def register_social_user(provider, email, first_name, last_name): 26 | old_user=User.objects.filter(email=email) 27 | if old_user.exists(): 28 | if provider == old_user[0].auth_provider: 29 | register_user=authenticate(email=email, password=settings.SOCIAL_AUTH_PASSWORD) 30 | 31 | return { 32 | 'full_name':register_user.get_full_name, 33 | 'email':register_user.email, 34 | 'tokens':register_user.tokens() 35 | } 36 | else: 37 | raise AuthenticationFailed( 38 | detail=f"please continue your login with {old_user[0].auth_provider}" 39 | ) 40 | else: 41 | new_user={ 42 | 'email':email, 43 | 'first_name':first_name, 44 | 'last_name':last_name, 45 | 'password':settings.SOCIAL_AUTH_PASSWORD 46 | } 47 | user=User.objects.create_user(**new_user) 48 | user.auth_provider=provider 49 | user.is_verified=True 50 | user.save() 51 | login_user=authenticate(email=email, password=settings.SOCIAL_AUTH_PASSWORD) 52 | 53 | tokens=login_user.tokens() 54 | return { 55 | 'email':login_user.email, 56 | 'full_name':login_user.get_full_name, 57 | "access_token":str(tokens.get('access')), 58 | "refresh_token":str(tokens.get('refresh')) 59 | } 60 | -------------------------------------------------------------------------------- /social_accounts/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameshenry2020/complete-authentication-with-JWT-and-Social-Auth-in-django-rest-framework-and-react/4609b9ee3326f1eb2a1fe7ee7b26d9600ccf0320/social_accounts/migrations/__init__.py -------------------------------------------------------------------------------- /social_accounts/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /social_accounts/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from .helpers import Google, register_social_user 3 | from .github import Github 4 | from django.conf import settings 5 | from rest_framework.exceptions import AuthenticationFailed 6 | 7 | 8 | class GoogleSignInSerializer(serializers.Serializer): 9 | access_token=serializers.CharField(min_length=6) 10 | 11 | 12 | def validate_access_token(self, access_token): 13 | user_data=Google.validate(access_token) 14 | try: 15 | user_data['sub'] 16 | 17 | except: 18 | raise serializers.ValidationError("this token has expired or invalid please try again") 19 | 20 | if user_data['aud'] != settings.GOOGLE_CLIENT_ID: 21 | raise AuthenticationFailed('Could not verify user.') 22 | 23 | user_id=user_data['sub'] 24 | email=user_data['email'] 25 | first_name=user_data['given_name'] 26 | last_name=user_data['family_name'] 27 | provider='google' 28 | 29 | return register_social_user(provider, email, first_name, last_name) 30 | 31 | 32 | class GithubLoginSerializer(serializers.Serializer): 33 | code = serializers.CharField() 34 | 35 | def validate_code(self, code): 36 | access_token = Github.exchange_code_for_token(code) 37 | 38 | if access_token: 39 | user_data=Github.get_github_user(access_token) 40 | 41 | full_name=user_data['name'] 42 | email=user_data['email'] 43 | names=full_name.split(" ") 44 | firstName=names[1] 45 | lastName=names[0] 46 | provider='github' 47 | return register_social_user(provider, email, firstName, lastName) 48 | 49 | -------------------------------------------------------------------------------- /social_accounts/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /social_accounts/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import GoogleOauthSignInview, GithubOauthSignInView 3 | 4 | 5 | urlpatterns=[ 6 | path('google/', GoogleOauthSignInview.as_view(), name='google'), 7 | path('github/', GithubOauthSignInView.as_view(), name='github') 8 | ] -------------------------------------------------------------------------------- /social_accounts/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from rest_framework.generics import GenericAPIView 3 | from .serializers import GoogleSignInSerializer, GithubLoginSerializer 4 | from rest_framework.response import Response 5 | from rest_framework import status 6 | 7 | # Create your views here. 8 | 9 | class GoogleOauthSignInview(GenericAPIView): 10 | serializer_class=GoogleSignInSerializer 11 | 12 | def post(self, request): 13 | print(request.data) 14 | serializer=self.serializer_class(data=request.data) 15 | serializer.is_valid(raise_exception=True) 16 | data=((serializer.validated_data)['access_token']) 17 | return Response(data, status=status.HTTP_200_OK) 18 | 19 | 20 | 21 | class GithubOauthSignInView(GenericAPIView): 22 | serializer_class=GithubLoginSerializer 23 | 24 | def post(self, request): 25 | serializer=self.serializer_class(data=request.data) 26 | if serializer.is_valid(raise_exception=True): 27 | data=((serializer.validated_data)['code']) 28 | return Response(data, status=status.HTTP_200_OK) 29 | return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) --------------------------------------------------------------------------------