├── web ├── __init__.py ├── middleware │ ├── __init__.py │ └── oauth.py ├── migrations │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ └── 0001_initial.cpython-39.pyc │ └── 0001_initial.py ├── tests.py ├── __pycache__ │ ├── apps.cpython-39.pyc │ ├── urls.cpython-39.pyc │ ├── admin.cpython-39.pyc │ ├── models.cpython-39.pyc │ ├── views.cpython-39.pyc │ └── __init__.cpython-39.pyc ├── apps.py ├── urls.py ├── admin.py ├── models.py ├── helpers.py └── views.py ├── AuthLib ├── __init__.py ├── __pycache__ │ ├── urls.cpython-39.pyc │ ├── __init__.cpython-39.pyc │ └── settings.cpython-39.pyc ├── asgi.py ├── wsgi.py ├── urls.py └── settings.py └── manage.py /web/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /AuthLib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/middleware/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /web/__pycache__/apps.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/apps.cpython-39.pyc -------------------------------------------------------------------------------- /web/__pycache__/urls.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/urls.cpython-39.pyc -------------------------------------------------------------------------------- /web/__pycache__/admin.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/admin.cpython-39.pyc -------------------------------------------------------------------------------- /web/__pycache__/models.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/models.cpython-39.pyc -------------------------------------------------------------------------------- /web/__pycache__/views.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/views.cpython-39.pyc -------------------------------------------------------------------------------- /AuthLib/__pycache__/urls.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/AuthLib/__pycache__/urls.cpython-39.pyc -------------------------------------------------------------------------------- /web/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /AuthLib/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/AuthLib/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /AuthLib/__pycache__/settings.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/AuthLib/__pycache__/settings.cpython-39.pyc -------------------------------------------------------------------------------- /web/migrations/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/migrations/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /web/migrations/__pycache__/0001_initial.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tatiansa/AuthLib/HEAD/web/migrations/__pycache__/0001_initial.cpython-39.pyc -------------------------------------------------------------------------------- /web/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WebConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'web' 7 | -------------------------------------------------------------------------------- /web/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from . import views 3 | 4 | app_name = 'web' 5 | urlpatterns = [ 6 | # path('login', views.login, name='login'), 7 | # path('authorize', views.authorize, name='authorize'), 8 | ] 9 | -------------------------------------------------------------------------------- /AuthLib/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for AuthLib 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', 'AuthLib.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /AuthLib/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for AuthLib 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', 'AuthLib.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', 'AuthLib.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 | -------------------------------------------------------------------------------- /AuthLib/urls.py: -------------------------------------------------------------------------------- 1 | """AuthLib URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/4.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('web/', include('web.urls')), 22 | ] 23 | -------------------------------------------------------------------------------- /web/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.auth.admin import UserAdmin 3 | from .models import CustomUser, OAuth2Token 4 | 5 | 6 | # Register your models here. 7 | class UserAdmin(UserAdmin): 8 | list_display = ('email', 'username', 'date_joined', 'last_login', 'is_staff') 9 | search_fields = ('email', 'username') 10 | readonly_fields = ('date_joined', 'last_login') 11 | filter_horizontal = () 12 | list_filter = () 13 | fieldsets = () 14 | 15 | 16 | class OAuth2Admin(admin.ModelAdmin): 17 | list_display = ('name', 'access_token', 'user') 18 | search_fields = ('name', 'access_token', 'user') 19 | readonly_fields = ('name', 'access_token', 'user') 20 | filter_horizontal = () 21 | list_filter = () 22 | fieldsets = () 23 | 24 | 25 | admin.site.register(CustomUser, UserAdmin) 26 | admin.site.register(OAuth2Token, OAuth2Admin) 27 | -------------------------------------------------------------------------------- /web/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import AbstractUser 2 | from django.db import models 3 | 4 | 5 | class CustomUser(AbstractUser): 6 | is_token_user = models.BooleanField(default=False) 7 | provider = models.CharField(max_length=40, blank=True, null=True) 8 | 9 | 10 | # Create your models here. 11 | class OAuth2Token(models.Model): 12 | name = models.CharField(max_length=40) 13 | token_type = models.CharField(max_length=40) 14 | access_token = models.CharField(max_length=200) 15 | refresh_token = models.CharField(max_length=200) 16 | expires_at = models.PositiveIntegerField(blank=True, null=True) 17 | user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default=1) 18 | expires_in = models.DateTimeField(null=True) 19 | 20 | def to_token(self): 21 | return dict( 22 | access_token=self.access_token, 23 | token_type=self.token_type, 24 | refresh_token=self.refresh_token, 25 | expires_at=self.expires_at, 26 | expires_in=self.expires_in, 27 | ) -------------------------------------------------------------------------------- /web/helpers.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from authlib.integrations.base_client import OAuth2Mixin, OpenIDMixin, BaseApp, OAuthError, BaseOAuth 3 | from authlib.integrations.django_client import DjangoIntegration 4 | from authlib.integrations.django_client.apps import DjangoAppMixin, DjangoOAuth1App 5 | from authlib.integrations.requests_client import OAuth2Session 6 | 7 | 8 | class OAuth2SessionMod(OAuth2Session): 9 | pass 10 | 11 | 12 | class DjangoOAuth2AppMod(DjangoAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): 13 | client_cls = OAuth2SessionMod 14 | 15 | def authorize_access_token(self, request, **kwargs): 16 | 17 | if request.method == 'GET': 18 | error = request.GET.get('error') 19 | if error: 20 | description = request.GET.get('error_description') 21 | raise OAuthError(error=error, description=description) 22 | params = { 23 | 'code': request.GET.get('code'), 24 | 'state': request.GET.get('state'), 25 | } 26 | else: 27 | params = { 28 | 'code': request.POST.get('code'), 29 | 'state': request.POST.get('state'), 30 | } 31 | 32 | state_data = self.framework.get_state_data(request.session, params.get('state')) 33 | self.framework.clear_state_data(request.session, params.get('state')) 34 | params = self._format_state_params(state_data, params) 35 | token = self.fetch_access_token(**params, **kwargs) 36 | 37 | # костыль для работы внутренних механизмов расшифровки id_token 38 | # вообще информация о пользователе зашифрована в этом блоку токена, но 39 | # мы почему то не передаём параметр kid и вынуждены посылать отдельный запрос 40 | if 'id_token' in token and 'nonce' in state_data: 41 | metadata = self.load_server_metadata() 42 | with self._get_oauth_client(**metadata) as client: 43 | response = requests.session().post( 44 | metadata['userinfo_endpoint'], 45 | data={ 46 | 'access_token': token['access_token'], 47 | } 48 | ) 49 | 50 | token['userinfo'] = response.json() 51 | 52 | return token 53 | 54 | 55 | class OAuthMod(BaseOAuth): 56 | oauth1_client_cls = DjangoOAuth1App 57 | oauth2_client_cls = DjangoOAuth2AppMod 58 | framework_integration_cls = DjangoIntegration -------------------------------------------------------------------------------- /web/middleware/oauth.py: -------------------------------------------------------------------------------- 1 | from authlib.integrations.base_client import OAuthError 2 | from authlib.oauth2.rfc6749 import OAuth2Token 3 | from django.shortcuts import redirect 4 | from django.utils.deprecation import MiddlewareMixin 5 | from AuthLib import settings 6 | from web import views 7 | from web.helpers import OAuthMod 8 | 9 | 10 | class OAuthMiddleware(MiddlewareMixin): 11 | 12 | def __init__(self, get_response=None): 13 | super().__init__(get_response) 14 | self.oauth = OAuthMod() 15 | 16 | def process_request(self, request): 17 | def update_token(token, refresh_token, access_token): 18 | request.session['token'] = token 19 | return None 20 | 21 | sso_client = self.oauth.register( 22 | settings.OAUTH_CLIENT_NAME, 23 | overwrite=True, 24 | **settings.OAUTH_CLIENT, 25 | update_token=update_token 26 | ) 27 | 28 | if request.path.startswith('/web/authorize'): 29 | self.clear_session(request) 30 | request.session['token'] = sso_client.authorize_access_token(request) 31 | if self.get_current_user(sso_client, request) is not None: 32 | redirect_uri = request.session.pop('redirect_uri', None) 33 | if redirect_uri is not None: 34 | return redirect(redirect_uri) 35 | 36 | return redirect(views.index) 37 | 38 | if request.session.get('token', None) is not None: 39 | current_user = self.get_current_user(sso_client, request) 40 | if current_user is not None: 41 | return self.get_response(request) 42 | 43 | # remember redirect URI for redirecting to the original URL. 44 | request.session['redirect_uri'] = request.path 45 | return sso_client.authorize_redirect(request, settings.OAUTH_CLIENT['redirect_uri']) 46 | 47 | # fetch current login user info 48 | # 1. check if it's in cache 49 | # 2. fetch from remote API when it's not in cache 50 | @staticmethod 51 | def get_current_user(sso_client, request): 52 | token = request.session.get('token', None) 53 | if token is None or 'access_token' not in token: 54 | return None 55 | 56 | if not OAuth2Token.from_dict(token).is_expired() and 'user' in request.session: 57 | return request.session['user'] 58 | 59 | try: 60 | res = sso_client.get(settings.OAUTH_CLIENT['userinfo_endpoint'], token=OAuth2Token(token)) 61 | if res.ok: 62 | request.session['user'] = res.json() 63 | return res.json() 64 | except OAuthError as e: 65 | print(e) 66 | return None 67 | 68 | @staticmethod 69 | def clear_session(request): 70 | try: 71 | del request.session['user'] 72 | del request.session['token'] 73 | except KeyError: 74 | pass 75 | 76 | def __del__(self): 77 | print('destroyed') -------------------------------------------------------------------------------- /web/views.py: -------------------------------------------------------------------------------- 1 | from authlib.integrations.django_client import OAuth 2 | 3 | from .helpers import OAuthMod 4 | from .models import CustomUser, OAuth2Token 5 | from django.http import HttpResponse 6 | from django.utils.crypto import get_random_string 7 | 8 | STATE_CODE_LENGTH = 20 9 | 10 | 11 | def update_token(name, token, refresh_token=None, access_token=None): 12 | if refresh_token: 13 | item = OAuth2Token.objects.get(name=name, refresh_token=refresh_token) 14 | elif access_token: 15 | item = OAuth2Token.objects.get(name=name, access_token=access_token) 16 | else: 17 | return 18 | # update old token 19 | item.access_token = token['access_token'] 20 | item.refresh_token = token.get('refresh_token') 21 | item.expires_at = token['expires_at'] 22 | item.save() 23 | 24 | 25 | # def fetch_token(name, request): 26 | # token = OAuth2Token.objects.get( 27 | # name=name, 28 | # user=request.user 29 | # ) 30 | # return token.to_token() 31 | 32 | 33 | # Init the OAuth 34 | # oauth = OAuthMod(fetch_token=fetch_token, update_token=update_token) 35 | # oauth.register( 36 | # name='bars_web_mchs', 37 | # ) 38 | 39 | 40 | # def login(request): 41 | # state = get_random_string(STATE_CODE_LENGTH) 42 | # redirect_uri = request.build_absolute_uri('http://127.0.0.1:8000/web/authorize') 43 | # request.session['session_state'] = state 44 | # extra_para = {'state': state} 45 | # 46 | # return oauth.bars_web_mchs.authorize_redirect(request, redirect_uri, **extra_para) 47 | # 48 | # 49 | # def authorize(request): 50 | # app_state = request.GET.get('state', '') 51 | # session_state = request.session.get('session_state', '') 52 | # token = oauth.bars_web_mchs.authorize_access_token(request) 53 | # user = oauth.bars_web_mchs.userinfo(token=token['access_token']) 54 | # 55 | # if app_state == session_state: 56 | # return HttpResponse("welcome") 57 | # else: 58 | # return HttpResponse("state not match") 59 | 60 | 61 | from datetime import datetime, timedelta 62 | 63 | 64 | def process_token(request, token, username): 65 | provider = 'bars_web_mchs' 66 | email = username 67 | 68 | try: 69 | # Retrieve the related user 70 | user = CustomUser.objects.get(email=email, provider=provider) 71 | except CustomUser.DoesNotExist: 72 | # Create user if not exists 73 | user = CustomUser.objects.create_user(username=email, email=email, provider=provider) 74 | oauth2token = dict() 75 | oauth2token['name'] = 'bars_web_mchs' 76 | oauth2token['token_type'] = token['token_type'] 77 | oauth2token['access_token'] = token['access_token'] 78 | if 'refresh_token' in token.keys(): 79 | oauth2token['refresh_token'] = token['refresh_token'] 80 | 81 | if 'expires_at' in token.keys(): 82 | oauth2token['expires_at'] = token['expires_at'] 83 | current_time = datetime.now() 84 | if 'expires_in' in token.keys(): 85 | expiry_datetime = current_time + timedelta(seconds=token['expires_in']) 86 | else: 87 | expiry_datetime = current_time + timedelta(days=10) 88 | oauth2token['expires_in'] = expiry_datetime 89 | OAuth2Token.objects.update_or_create(user=user, 90 | defaults=oauth2token) 91 | -------------------------------------------------------------------------------- /web/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.3 on 2022-11-29 15:34 2 | 3 | from django.conf import settings 4 | import django.contrib.auth.models 5 | import django.contrib.auth.validators 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | import django.utils.timezone 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | initial = True 14 | 15 | dependencies = [ 16 | ('auth', '0012_alter_user_first_name_max_length'), 17 | ] 18 | 19 | operations = [ 20 | migrations.CreateModel( 21 | name='CustomUser', 22 | fields=[ 23 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 24 | ('password', models.CharField(max_length=128, verbose_name='password')), 25 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 26 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 27 | ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), 28 | ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), 29 | ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), 30 | ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), 31 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), 32 | ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), 33 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), 34 | ('is_token_user', models.BooleanField(default=False)), 35 | ('provider', models.CharField(blank=True, max_length=40, null=True)), 36 | ('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')), 37 | ('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')), 38 | ], 39 | options={ 40 | 'verbose_name': 'user', 41 | 'verbose_name_plural': 'users', 42 | 'abstract': False, 43 | }, 44 | managers=[ 45 | ('objects', django.contrib.auth.models.UserManager()), 46 | ], 47 | ), 48 | migrations.CreateModel( 49 | name='OAuth2Token', 50 | fields=[ 51 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 52 | ('name', models.CharField(max_length=40)), 53 | ('token_type', models.CharField(max_length=40)), 54 | ('access_token', models.CharField(max_length=200)), 55 | ('refresh_token', models.CharField(max_length=200)), 56 | ('expires_at', models.PositiveIntegerField(blank=True, null=True)), 57 | ('expires_in', models.DateTimeField(null=True)), 58 | ('user', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 59 | ], 60 | ), 61 | ] 62 | -------------------------------------------------------------------------------- /AuthLib/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for AuthLib project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.1.3. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.1/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-g3v0h9x6_2(f-xprteqhpk1vpgi27%9^mw&6vn0arygmxm@$v)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'web', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | 'web.middleware.oauth.OAuthMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'AuthLib.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [BASE_DIR / 'templates'] 60 | , 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'AuthLib.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/4.1/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.postgresql', 82 | 'NAME': 'AuthLib', 83 | 'USER': 'a2', 84 | 'PASSWORD': '32167', 85 | 'HOST': 'localhost', 86 | # 'PORT': '', 87 | } 88 | } 89 | 90 | 91 | AUTH_USER_MODEL = 'web.CustomUser' 92 | # Password validation 93 | # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators 94 | 95 | AUTH_PASSWORD_VALIDATORS = [ 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 107 | }, 108 | ] 109 | 110 | 111 | # Internationalization 112 | # https://docs.djangoproject.com/en/4.1/topics/i18n/ 113 | 114 | LANGUAGE_CODE = 'en-us' 115 | 116 | TIME_ZONE = 'UTC' 117 | 118 | USE_I18N = True 119 | 120 | USE_TZ = True 121 | 122 | 123 | # Static files (CSS, JavaScript, Images) 124 | # https://docs.djangoproject.com/en/4.1/howto/static-files/ 125 | 126 | STATIC_URL = 'static/' 127 | 128 | # Default primary key field type 129 | # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field 130 | 131 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 132 | CSRF_ENABLED = False 133 | 134 | # } 135 | OAUTH_CLIENT_NAME = 136 | OAUTH_CLIENT = { 137 | 138 | } 139 | 140 | 141 | # SESSION_COOKIE_NAME = 'client_sessionid' 142 | --------------------------------------------------------------------------------