├── .env.local ├── .gitignore ├── README.md ├── custom_storages.py ├── full_auth ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── requirements.txt └── users ├── __init__.py ├── admin.py ├── apps.py ├── authentication.py ├── migrations ├── 0001_initial.py └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py /.env.local: -------------------------------------------------------------------------------- 1 | DEVELOPMENT_MODE='True' 2 | DJANGO_SECRET_KEY='' 3 | DEBUG='True' 4 | AWS_SES_ACCESS_KEY_ID='' 5 | AWS_SES_SECRET_ACCESS_KEY='' 6 | AWS_SES_REGION_NAME='' 7 | AWS_SES_FROM_EMAIL='' 8 | DOMAIN='localhost:3000' 9 | AUTH_COOKIE_SECURE='False' 10 | GOOGLE_AUTH_KEY='' 11 | GOOGLE_AUTH_SECRET_KEY='' 12 | FACEBOOK_AUTH_KEY='' 13 | FACEBOOK_AUTH_SECRET_KEY='' 14 | REDIRECT_URLS='http://localhost:3000/auth/google,http://localhost:3000/auth/facebook' 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/django 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=django 3 | 4 | ### Django ### 5 | *.log 6 | *.pot 7 | *.pyc 8 | __pycache__/ 9 | local_settings.py 10 | db.sqlite3 11 | db.sqlite3-journal 12 | media 13 | 14 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 15 | # in your Git repository. Update and uncomment the following line accordingly. 16 | # /staticfiles/ 17 | 18 | ### Django.Python Stack ### 19 | # Byte-compiled / optimized / DLL files 20 | *.py[cod] 21 | *$py.class 22 | 23 | # C extensions 24 | *.so 25 | 26 | # Distribution / packaging 27 | .Python 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | wheels/ 40 | share/python-wheels/ 41 | *.egg-info/ 42 | .installed.cfg 43 | *.egg 44 | MANIFEST 45 | 46 | # PyInstaller 47 | # Usually these files are written by a python script from a template 48 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 49 | *.manifest 50 | *.spec 51 | 52 | # Installer logs 53 | pip-log.txt 54 | pip-delete-this-directory.txt 55 | 56 | # Unit test / coverage reports 57 | htmlcov/ 58 | .tox/ 59 | .nox/ 60 | .coverage 61 | .coverage.* 62 | .cache 63 | nosetests.xml 64 | coverage.xml 65 | *.cover 66 | *.py,cover 67 | .hypothesis/ 68 | .pytest_cache/ 69 | cover/ 70 | 71 | # Translations 72 | *.mo 73 | 74 | # Django stuff: 75 | 76 | # Flask stuff: 77 | instance/ 78 | .webassets-cache 79 | 80 | # Scrapy stuff: 81 | .scrapy 82 | 83 | # Sphinx documentation 84 | docs/_build/ 85 | 86 | # PyBuilder 87 | .pybuilder/ 88 | target/ 89 | 90 | # Jupyter Notebook 91 | .ipynb_checkpoints 92 | 93 | # IPython 94 | profile_default/ 95 | ipython_config.py 96 | 97 | # pyenv 98 | # For a library or package, you might want to ignore these files since the code is 99 | # intended to run in multiple environments; otherwise, check them in: 100 | # .python-version 101 | 102 | # pipenv 103 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 104 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 105 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 106 | # install all needed dependencies. 107 | #Pipfile.lock 108 | 109 | # poetry 110 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 111 | # This is especially recommended for binary packages to ensure reproducibility, and is more 112 | # commonly ignored for libraries. 113 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 114 | #poetry.lock 115 | 116 | # pdm 117 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 118 | #pdm.lock 119 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 120 | # in version control. 121 | # https://pdm.fming.dev/#use-with-ide 122 | .pdm.toml 123 | 124 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 125 | __pypackages__/ 126 | 127 | # Celery stuff 128 | celerybeat-schedule 129 | celerybeat.pid 130 | 131 | # SageMath parsed files 132 | *.sage.py 133 | 134 | # Environments 135 | .env 136 | .venv 137 | env/ 138 | venv/ 139 | ENV/ 140 | env.bak/ 141 | venv.bak/ 142 | 143 | # Spyder project settings 144 | .spyderproject 145 | .spyproject 146 | 147 | # Rope project settings 148 | .ropeproject 149 | 150 | # mkdocs documentation 151 | /site 152 | 153 | # mypy 154 | .mypy_cache/ 155 | .dmypy.json 156 | dmypy.json 157 | 158 | # Pyre type checker 159 | .pyre/ 160 | 161 | # pytype static type analyzer 162 | .pytype/ 163 | 164 | # Cython debug symbols 165 | cython_debug/ 166 | 167 | # PyCharm 168 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 169 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 170 | # and can be added to the global gitignore or merged into this file. For a more nuclear 171 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 172 | #.idea/ 173 | 174 | # End of https://www.toptal.com/developers/gitignore/api/django 175 | 176 | .vscode 177 | .DS_Store 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Full Auth API 2 | 3 | --- 4 | 5 | ### To setup the project locally, follow these steps: 6 | 7 | - open the `.env.local` file 8 | - fill out the value for `DJANGO_SECRET_KEY` 9 | - go to [AWS](https://aws.amazon.com) 10 | - log into your aws account, or create one if you don't have one 11 | - navigate to the `Simple Email Service (SES)` 12 | - validate 2 emails, one which will be the sender email, and the other the receiver email 13 | - go to the `SMTP settings`, and click on `Create SMTP credentials` 14 | - after creating the IAM user, next navigate to `IAM` 15 | - under `Access management`, click on `users` 16 | - click on the `SES` user that was created 17 | - click on `Add permissions`, then add the `AmazonSESReadOnlyAccess` permission 18 | - then go to `Security credentials`, and create a new access key 19 | - take the access key and secret, and use them as the values in the `AWS_SES_ACCESS_KEY_ID` and `AWS_SES_SECRET_ACCESS_KEY` environment variables 20 | - fill in the region where you set up the Simple Email Service in the `AWS_SES_REGION_NAME` environment variable 21 | - fill in the email that will be sending emails in the `AWS_SES_FROM_EMAIL` environment variable 22 | - go to google cloud [HERE](https://console.cloud.google.com) 23 | - in the settings, hover over `APIs & Services`, and click on `OAuth consent screen` 24 | - fill in the details for the OAuth consent screen 25 | - create an `External` user type 26 | - add the `Authorized domains` 27 | - under `scopes`, click `ADD OR REMOVE SCOPES`, add the `../auth/userinfo.email`, `../auth/userinfo.profile`, and `openid` scopes 28 | - under `Test users`, add your receiver email 29 | - next go to the settings again, hover over `APIS & Services`, and click on `Credentials` 30 | - click on `CREATE CREDENTIALS`, then click on `OAuth client ID` 31 | - take the access key and secret, and use them as the values in the `GOOGLE_AUTH_KEY` and `GOOGLE_AUTH_SECRET_KEY` environment variables 32 | - for `Application type`, you can select `Web application` 33 | - under `Authorized JavaScript origins`, add `http://localhost:3000` 34 | - under `Authorized redirect URIs`, add `http://localhost:3000/auth/google` 35 | - to have this work in your production environment, do the following: 36 | - under `Authorized JavaScript origins`, add `https://your-domain.com` 37 | - under `Authorized redirect URIs`, add `https://your-domain.com/auth/google` 38 | - go to facebook developers [HERE](https://developers.facebook.com) 39 | - navigate to `My Apps`, click on `Create App`, then click `Set up Facebook Login`, then click `Next` 40 | - select `Website` and `No, I'm not building a game`, then click `Next` 41 | - fill in your app name, then click `Create app` 42 | - click on `Use cases`, then under `Authentication and account creation`, click the `Edit` button 43 | - under the `email` permissions, click `Add` 44 | - navigate to `Basic` under `Settings` 45 | - take the `App ID` and `App secret`, and use them as the values in the `FACEBOOK_AUTH_KEY` and `FACEBOOK_AUTH_SECRET_KEY` environment variables 46 | - under `App domains`, add `localhost`, and this is also where you can add your production domain 47 | - navigate to `Roles` under `App Roles` 48 | - click on `Add Testers`, and put into the field the value of a Facebook ID you will use to log into the app with 49 | - to get the value of a Facebook ID, simply log into the Facebook account, go to the profile page, then grab the ID from the URL 50 | - to activate the tester account, with your tester account navigate to facebook developers [HERE](https://developers.facebook.com) 51 | - navigate to `My Apps`, and in the dropdown you will see a prompt to accept the account as a tester on the app 52 | - next go to `Products`, under `Facebook Login` click `Configure`, then `Settings` 53 | - for things to work in your development environment you don't need to fill in anything on this screen 54 | - to have this work in your production environment, under `Valid OAuth Redirect URIs`, add `https://your-domain.com/auth/facebook` 55 | 56 | --- 57 | 58 | ### Deployment on Digitalocean: 59 | 60 | - to deploy, go to the following link [HERE](https://www.youtube.com/watch?v=2pZmxh8Tf78) 61 | - next go to the timestamp at `2:47:14`, this is where I show the Digitalocean deployment 62 | -------------------------------------------------------------------------------- /custom_storages.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from storages.backends.s3boto3 import S3Boto3Storage 3 | 4 | 5 | class CustomS3Boto3Storage(S3Boto3Storage): 6 | location = settings.AWS_MEDIA_LOCATION 7 | -------------------------------------------------------------------------------- /full_auth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linkedweb/full-auth-api/0823e1aad86e5e508e3ec7b2cf1a0e30b25c106b/full_auth/__init__.py -------------------------------------------------------------------------------- /full_auth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for full_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.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', 'full_auth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /full_auth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for full_auth project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.2.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.2/ref/settings/ 11 | """ 12 | 13 | import sys 14 | import dj_database_url 15 | from os import getenv, path 16 | from pathlib import Path 17 | from django.core.management.utils import get_random_secret_key 18 | import dotenv 19 | 20 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 21 | BASE_DIR = Path(__file__).resolve().parent.parent 22 | 23 | dotenv_file = BASE_DIR / '.env.local' 24 | 25 | if path.isfile(dotenv_file): 26 | dotenv.load_dotenv(dotenv_file) 27 | 28 | DEVELOPMENT_MODE = getenv('DEVELOPMENT_MODE', 'False') == 'True' 29 | 30 | # Quick-start development settings - unsuitable for production 31 | # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ 32 | 33 | # SECURITY WARNING: keep the secret key used in production secret! 34 | SECRET_KEY = getenv('DJANGO_SECRET_KEY', get_random_secret_key()) 35 | 36 | # SECURITY WARNING: don't run with debug turned on in production! 37 | DEBUG = getenv('DEBUG', 'False') == 'True' 38 | 39 | ALLOWED_HOSTS = getenv('DJANGO_ALLOWED_HOSTS', 40 | '127.0.0.1,localhost').split(',') 41 | 42 | 43 | # Application definition 44 | 45 | INSTALLED_APPS = [ 46 | 'django.contrib.admin', 47 | 'django.contrib.auth', 48 | 'django.contrib.contenttypes', 49 | 'django.contrib.sessions', 50 | 'django.contrib.messages', 51 | 'django.contrib.staticfiles', 52 | 'corsheaders', 53 | 'rest_framework', 54 | 'djoser', 55 | 'storages', 56 | 'social_django', 57 | 'users', 58 | ] 59 | 60 | MIDDLEWARE = [ 61 | 'django.middleware.security.SecurityMiddleware', 62 | 'django.contrib.sessions.middleware.SessionMiddleware', 63 | 'corsheaders.middleware.CorsMiddleware', 64 | 'django.middleware.common.CommonMiddleware', 65 | 'django.middleware.csrf.CsrfViewMiddleware', 66 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 67 | 'django.contrib.messages.middleware.MessageMiddleware', 68 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 69 | ] 70 | 71 | ROOT_URLCONF = 'full_auth.urls' 72 | 73 | TEMPLATES = [ 74 | { 75 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 76 | 'DIRS': [], 77 | 'APP_DIRS': True, 78 | 'OPTIONS': { 79 | 'context_processors': [ 80 | 'django.template.context_processors.debug', 81 | 'django.template.context_processors.request', 82 | 'django.contrib.auth.context_processors.auth', 83 | 'django.contrib.messages.context_processors.messages', 84 | ], 85 | }, 86 | }, 87 | ] 88 | 89 | WSGI_APPLICATION = 'full_auth.wsgi.application' 90 | 91 | 92 | # Database 93 | # https://docs.djangoproject.com/en/4.2/ref/settings/#databases 94 | 95 | if DEVELOPMENT_MODE is True: 96 | DATABASES = { 97 | 'default': { 98 | 'ENGINE': 'django.db.backends.sqlite3', 99 | 'NAME': BASE_DIR / 'db.sqlite3', 100 | } 101 | } 102 | elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': 103 | if getenv('DATABASE_URL', None) is None: 104 | raise Exception('DATABASE_URL environment variable not defined') 105 | DATABASES = { 106 | 'default': dj_database_url.parse(getenv('DATABASE_URL')), 107 | } 108 | 109 | # Email settings 110 | 111 | EMAIL_BACKEND = 'django_ses.SESBackend' 112 | DEFAULT_FROM_EMAIL = getenv('AWS_SES_FROM_EMAIL') 113 | 114 | AWS_SES_ACCESS_KEY_ID = getenv('AWS_SES_ACCESS_KEY_ID') 115 | AWS_SES_SECRET_ACCESS_KEY = getenv('AWS_SES_SECRET_ACCESS_KEY') 116 | AWS_SES_REGION_NAME = getenv('AWS_SES_REGION_NAME') 117 | AWS_SES_REGION_ENDPOINT = f'email.{AWS_SES_REGION_NAME}.amazonaws.com' 118 | AWS_SES_FROM_EMAIL = getenv('AWS_SES_FROM_EMAIL') 119 | USE_SES_V2 = True 120 | 121 | DOMAIN = getenv('DOMAIN') 122 | SITE_NAME = 'Full Auth' 123 | 124 | # Password validation 125 | # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators 126 | 127 | AUTH_PASSWORD_VALIDATORS = [ 128 | { 129 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 130 | }, 131 | { 132 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 133 | }, 134 | { 135 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 136 | }, 137 | { 138 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 139 | }, 140 | ] 141 | 142 | 143 | # Internationalization 144 | # https://docs.djangoproject.com/en/4.2/topics/i18n/ 145 | 146 | LANGUAGE_CODE = 'en-us' 147 | 148 | TIME_ZONE = 'UTC' 149 | 150 | USE_I18N = True 151 | 152 | USE_TZ = True 153 | 154 | 155 | # Static files (CSS, JavaScript, Images) 156 | # https://docs.djangoproject.com/en/4.2/howto/static-files/ 157 | 158 | if DEVELOPMENT_MODE is True: 159 | STATIC_URL = 'static/' 160 | STATIC_ROOT = BASE_DIR / 'static' 161 | MEDIA_URL = 'media/' 162 | MEDIA_ROOT = BASE_DIR / 'media' 163 | else: 164 | AWS_S3_ACCESS_KEY_ID = getenv('AWS_S3_ACCESS_KEY_ID') 165 | AWS_S3_SECRET_ACCESS_KEY = getenv('AWS_S3_SECRET_ACCESS_KEY') 166 | AWS_STORAGE_BUCKET_NAME = getenv('AWS_STORAGE_BUCKET_NAME') 167 | AWS_S3_REGION_NAME = getenv('AWS_S3_REGION_NAME') 168 | AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com' 169 | AWS_S3_OBJECT_PARAMETERS = { 170 | 'CacheControl': 'max-age=86400' 171 | } 172 | AWS_DEFAULT_ACL = 'public-read' 173 | AWS_LOCATION = 'static' 174 | AWS_MEDIA_LOCATION = 'media' 175 | AWS_S3_CUSTOM_DOMAIN = getenv('AWS_S3_CUSTOM_DOMAIN') 176 | STORAGES = { 177 | 'default': {'BACKEND': 'custom_storages.CustomS3Boto3Storage'}, 178 | 'staticfiles': {'BACKEND': 'storages.backends.s3boto3.S3StaticStorage'} 179 | } 180 | 181 | AUTHENTICATION_BACKENDS = [ 182 | 'social_core.backends.google.GoogleOAuth2', 183 | 'social_core.backends.facebook.FacebookOAuth2', 184 | 'django.contrib.auth.backends.ModelBackend', 185 | ] 186 | 187 | REST_FRAMEWORK = { 188 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 189 | 'users.authentication.CustomJWTAuthentication', 190 | ], 191 | 'DEFAULT_PERMISSION_CLASSES': [ 192 | 'rest_framework.permissions.IsAuthenticated', 193 | ] 194 | } 195 | 196 | DJOSER = { 197 | 'PASSWORD_RESET_CONFIRM_URL': 'password-reset/{uid}/{token}', 198 | 'SEND_ACTIVATION_EMAIL': True, 199 | 'ACTIVATION_URL': 'activation/{uid}/{token}', 200 | 'USER_CREATE_PASSWORD_RETYPE': True, 201 | 'PASSWORD_RESET_CONFIRM_RETYPE': True, 202 | 'TOKEN_MODEL': None, 203 | 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': getenv('REDIRECT_URLS').split(',') 204 | } 205 | 206 | AUTH_COOKIE = 'access' 207 | AUTH_COOKIE_MAX_AGE = 60 * 60 * 24 208 | AUTH_COOKIE_SECURE = getenv('AUTH_COOKIE_SECURE', 'True') == 'True' 209 | AUTH_COOKIE_HTTP_ONLY = True 210 | AUTH_COOKIE_PATH = '/' 211 | AUTH_COOKIE_SAMESITE = 'None' 212 | 213 | SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = getenv('GOOGLE_AUTH_KEY') 214 | SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = getenv('GOOGLE_AUTH_SECRET_KEY') 215 | SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 216 | 'https://www.googleapis.com/auth/userinfo.email', 217 | 'https://www.googleapis.com/auth/userinfo.profile', 218 | 'openid' 219 | ] 220 | SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = ['first_name', 'last_name'] 221 | 222 | SOCIAL_AUTH_FACEBOOK_KEY = getenv('FACEBOOK_AUTH_KEY') 223 | SOCIAL_AUTH_FACEBOOK_SECRET = getenv('FACEBOOK_AUTH_SECRET_KEY') 224 | SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] 225 | SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 226 | 'fields': 'email, first_name, last_name' 227 | } 228 | 229 | CORS_ALLOWED_ORIGINS = getenv( 230 | 'CORS_ALLOWED_ORIGINS', 231 | 'http://localhost:3000,http://127.0.0.1:3000' 232 | ).split(',') 233 | CORS_ALLOW_CREDENTIALS = True 234 | 235 | # Default primary key field type 236 | # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field 237 | 238 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 239 | 240 | AUTH_USER_MODEL = 'users.UserAccount' 241 | -------------------------------------------------------------------------------- /full_auth/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('djoser.urls')), 7 | path('api/', include('users.urls')), 8 | ] 9 | -------------------------------------------------------------------------------- /full_auth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for full_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.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', 'full_auth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /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', 'full_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.6.0 2 | boto3==1.26.137 3 | botocore==1.29.137 4 | certifi==2023.5.7 5 | cffi==1.15.1 6 | charset-normalizer==3.1.0 7 | cryptography==40.0.2 8 | defusedxml==0.7.1 9 | dj-database-url==2.0.0 10 | Django==4.2.1 11 | django-cors-headers==4.0.0 12 | django-ses==3.5.0 13 | django-storages==1.13.2 14 | django-templated-mail==1.1.1 15 | djangorestframework==3.14.0 16 | djangorestframework-simplejwt==5.2.2 17 | djoser==2.2.0 18 | gunicorn==20.1.0 19 | idna==3.4 20 | jmespath==1.0.1 21 | oauthlib==3.2.2 22 | psycopg2==2.9.6 23 | pycparser==2.21 24 | PyJWT==2.7.0 25 | python-dateutil==2.8.2 26 | python-dotenv==1.0.0 27 | python3-openid==3.2.0 28 | pytz==2023.3 29 | requests==2.30.0 30 | requests-oauthlib==1.3.1 31 | s3transfer==0.6.1 32 | six==1.16.0 33 | social-auth-app-django==5.2.0 34 | social-auth-core==4.4.2 35 | sqlparse==0.4.4 36 | typing_extensions==4.5.0 37 | urllib3==1.26.15 38 | -------------------------------------------------------------------------------- /users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linkedweb/full-auth-api/0823e1aad86e5e508e3ec7b2cf1a0e30b25c106b/users/__init__.py -------------------------------------------------------------------------------- /users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /users/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class UsersConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'users' 7 | -------------------------------------------------------------------------------- /users/authentication.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from rest_framework_simplejwt.authentication import JWTAuthentication 3 | 4 | 5 | class CustomJWTAuthentication(JWTAuthentication): 6 | def authenticate(self, request): 7 | try: 8 | header = self.get_header(request) 9 | 10 | if header is None: 11 | raw_token = request.COOKIES.get(settings.AUTH_COOKIE) 12 | else: 13 | raw_token = self.get_raw_token(header) 14 | 15 | if raw_token is None: 16 | return None 17 | 18 | validated_token = self.get_validated_token(raw_token) 19 | 20 | return self.get_user(validated_token), validated_token 21 | except: 22 | return None 23 | -------------------------------------------------------------------------------- /users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.2.1 on 2023-05-21 16:15 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ('auth', '0012_alter_user_first_name_max_length'), 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='UserAccount', 17 | fields=[ 18 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('password', models.CharField(max_length=128, verbose_name='password')), 20 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 21 | ('first_name', models.CharField(max_length=255)), 22 | ('last_name', models.CharField(max_length=255)), 23 | ('email', models.EmailField(max_length=255, unique=True)), 24 | ('is_active', models.BooleanField(default=True)), 25 | ('is_staff', models.BooleanField(default=False)), 26 | ('is_superuser', models.BooleanField(default=False)), 27 | ('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')), 28 | ('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')), 29 | ], 30 | options={ 31 | 'abstract': False, 32 | }, 33 | ), 34 | ] 35 | -------------------------------------------------------------------------------- /users/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linkedweb/full-auth-api/0823e1aad86e5e508e3ec7b2cf1a0e30b25c106b/users/migrations/__init__.py -------------------------------------------------------------------------------- /users/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import ( 3 | BaseUserManager, 4 | AbstractBaseUser, 5 | PermissionsMixin 6 | ) 7 | 8 | 9 | class UserAccountManager(BaseUserManager): 10 | def create_user(self, email, password=None, **kwargs): 11 | if not email: 12 | raise ValueError('Users must have an email address') 13 | 14 | email = self.normalize_email(email) 15 | email = email.lower() 16 | 17 | user = self.model( 18 | email=email, 19 | **kwargs 20 | ) 21 | 22 | user.set_password(password) 23 | user.save(using=self._db) 24 | 25 | return user 26 | 27 | def create_superuser(self, email, password=None, **kwargs): 28 | user = self.create_user( 29 | email, 30 | password=password, 31 | **kwargs 32 | ) 33 | 34 | user.is_staff = True 35 | user.is_superuser = True 36 | user.save(using=self._db) 37 | 38 | return user 39 | 40 | 41 | class UserAccount(AbstractBaseUser, PermissionsMixin): 42 | first_name = models.CharField(max_length=255) 43 | last_name = models.CharField(max_length=255) 44 | email = models.EmailField(unique=True, max_length=255) 45 | 46 | is_active = models.BooleanField(default=True) 47 | is_staff = models.BooleanField(default=False) 48 | is_superuser = models.BooleanField(default=False) 49 | 50 | objects = UserAccountManager() 51 | 52 | USERNAME_FIELD = 'email' 53 | REQUIRED_FIELDS = ['first_name', 'last_name'] 54 | 55 | def __str__(self): 56 | return self.email 57 | -------------------------------------------------------------------------------- /users/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /users/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, re_path 2 | from .views import ( 3 | CustomProviderAuthView, 4 | CustomTokenObtainPairView, 5 | CustomTokenRefreshView, 6 | CustomTokenVerifyView, 7 | LogoutView 8 | ) 9 | 10 | urlpatterns = [ 11 | re_path( 12 | r'^o/(?P\S+)/$', 13 | CustomProviderAuthView.as_view(), 14 | name='provider-auth' 15 | ), 16 | path('jwt/create/', CustomTokenObtainPairView.as_view()), 17 | path('jwt/refresh/', CustomTokenRefreshView.as_view()), 18 | path('jwt/verify/', CustomTokenVerifyView.as_view()), 19 | path('logout/', LogoutView.as_view()), 20 | ] 21 | -------------------------------------------------------------------------------- /users/views.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from rest_framework.views import APIView 3 | from rest_framework.response import Response 4 | from rest_framework import status 5 | from djoser.social.views import ProviderAuthView 6 | from rest_framework_simplejwt.views import ( 7 | TokenObtainPairView, 8 | TokenRefreshView, 9 | TokenVerifyView 10 | ) 11 | 12 | 13 | class CustomProviderAuthView(ProviderAuthView): 14 | def post(self, request, *args, **kwargs): 15 | response = super().post(request, *args, **kwargs) 16 | 17 | if response.status_code == 201: 18 | access_token = response.data.get('access') 19 | refresh_token = response.data.get('refresh') 20 | 21 | response.set_cookie( 22 | 'access', 23 | access_token, 24 | max_age=settings.AUTH_COOKIE_MAX_AGE, 25 | path=settings.AUTH_COOKIE_PATH, 26 | secure=settings.AUTH_COOKIE_SECURE, 27 | httponly=settings.AUTH_COOKIE_HTTP_ONLY, 28 | samesite=settings.AUTH_COOKIE_SAMESITE 29 | ) 30 | response.set_cookie( 31 | 'refresh', 32 | refresh_token, 33 | max_age=settings.AUTH_COOKIE_MAX_AGE, 34 | path=settings.AUTH_COOKIE_PATH, 35 | secure=settings.AUTH_COOKIE_SECURE, 36 | httponly=settings.AUTH_COOKIE_HTTP_ONLY, 37 | samesite=settings.AUTH_COOKIE_SAMESITE 38 | ) 39 | 40 | return response 41 | 42 | 43 | class CustomTokenObtainPairView(TokenObtainPairView): 44 | def post(self, request, *args, **kwargs): 45 | response = super().post(request, *args, **kwargs) 46 | 47 | if response.status_code == 200: 48 | access_token = response.data.get('access') 49 | refresh_token = response.data.get('refresh') 50 | 51 | response.set_cookie( 52 | 'access', 53 | access_token, 54 | max_age=settings.AUTH_COOKIE_MAX_AGE, 55 | path=settings.AUTH_COOKIE_PATH, 56 | secure=settings.AUTH_COOKIE_SECURE, 57 | httponly=settings.AUTH_COOKIE_HTTP_ONLY, 58 | samesite=settings.AUTH_COOKIE_SAMESITE 59 | ) 60 | response.set_cookie( 61 | 'refresh', 62 | refresh_token, 63 | max_age=settings.AUTH_COOKIE_MAX_AGE, 64 | path=settings.AUTH_COOKIE_PATH, 65 | secure=settings.AUTH_COOKIE_SECURE, 66 | httponly=settings.AUTH_COOKIE_HTTP_ONLY, 67 | samesite=settings.AUTH_COOKIE_SAMESITE 68 | ) 69 | 70 | return response 71 | 72 | 73 | class CustomTokenRefreshView(TokenRefreshView): 74 | def post(self, request, *args, **kwargs): 75 | refresh_token = request.COOKIES.get('refresh') 76 | 77 | if refresh_token: 78 | request.data['refresh'] = refresh_token 79 | 80 | response = super().post(request, *args, **kwargs) 81 | 82 | if response.status_code == 200: 83 | access_token = response.data.get('access') 84 | 85 | response.set_cookie( 86 | 'access', 87 | access_token, 88 | max_age=settings.AUTH_COOKIE_MAX_AGE, 89 | path=settings.AUTH_COOKIE_PATH, 90 | secure=settings.AUTH_COOKIE_SECURE, 91 | httponly=settings.AUTH_COOKIE_HTTP_ONLY, 92 | samesite=settings.AUTH_COOKIE_SAMESITE 93 | ) 94 | 95 | return response 96 | 97 | 98 | class CustomTokenVerifyView(TokenVerifyView): 99 | def post(self, request, *args, **kwargs): 100 | access_token = request.COOKIES.get('access') 101 | 102 | if access_token: 103 | request.data['token'] = access_token 104 | 105 | return super().post(request, *args, **kwargs) 106 | 107 | 108 | class LogoutView(APIView): 109 | def post(self, request, *args, **kwargs): 110 | response = Response(status=status.HTTP_204_NO_CONTENT) 111 | response.delete_cookie('access') 112 | response.delete_cookie('refresh') 113 | 114 | return response 115 | --------------------------------------------------------------------------------