├── myproject ├── __init__.py ├── core │ ├── __init__.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_auth_backends.py │ │ └── test_views.py │ ├── migrations │ │ ├── __init__.py │ │ ├── 0002_auto_20191005_2020.py │ │ └── 0001_initial.py │ ├── apps.py │ ├── views.py │ ├── urls.py │ ├── admin.py │ ├── forms.py │ ├── models.py │ ├── auth_backends.py │ └── templates │ │ ├── core │ │ ├── index.html │ │ └── auth.html │ │ ├── includes │ │ └── nav.html │ │ └── base.html ├── wsgi.py ├── urls.py └── settings.py ├── requirements.txt ├── README.md ├── manage.py ├── contrib └── env_gen.py └── .gitignore /myproject/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /myproject/core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /myproject/core/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /myproject/core/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /myproject/core/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CoreConfig(AppConfig): 5 | name = 'core' 6 | -------------------------------------------------------------------------------- /myproject/core/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | 4 | def home(request): 5 | return render(request, 'core/index.html') 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dj-database-url==0.5.0 2 | Django==2.2.* 3 | django-extensions==2.2.1 4 | django-widget-tweaks==1.4.5 5 | python-decouple==3.1 6 | pytz==2019.2 7 | six==1.12.0 8 | sqlparse==0.3.0 9 | -------------------------------------------------------------------------------- /myproject/core/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from myproject.core import views as v 4 | 5 | app_name = 'core' 6 | 7 | 8 | urlpatterns = [ 9 | path('', v.home, name='home'), 10 | ] 11 | -------------------------------------------------------------------------------- /myproject/core/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import UserProfile 4 | 5 | 6 | @admin.register(UserProfile) 7 | class UserProfileAdmin(admin.ModelAdmin): 8 | list_display = ('__str__', 'cpf') 9 | -------------------------------------------------------------------------------- /myproject/core/forms.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.forms import AuthenticationForm 2 | 3 | 4 | class LoginForm(AuthenticationForm): 5 | def __init__(self, request=None, *args, **kwargs): 6 | super().__init__(request, *args, **kwargs) 7 | self.fields['username'].label = 'CPF' 8 | self.fields['username'].verbose_name = 'CPF' 9 | -------------------------------------------------------------------------------- /myproject/core/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import User 2 | from django.db import models 3 | 4 | 5 | class UserProfile(models.Model): 6 | user = models.OneToOneField( 7 | User, 8 | on_delete=models.CASCADE, 9 | related_name='profile' 10 | ) 11 | cpf = models.CharField(max_length=14, unique=True) 12 | 13 | def __str__(self): 14 | return str(self.user) 15 | -------------------------------------------------------------------------------- /myproject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for myproject 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/2.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', 'myproject.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # custom-admin-cpf 2 | 3 | Django custom admin login with CPF. 4 | 5 | Login com CPF. 6 | 7 | ## Como rodar o projeto? 8 | 9 | * Clone esse repositório. 10 | * Crie um virtualenv com Python 3. 11 | * Ative o virtualenv. 12 | * Instale as dependências. 13 | * Rode as migrações. 14 | 15 | ``` 16 | git clone https://github.com/rg3915/custom-admin-cpf.git 17 | cd custom-admin-cpf 18 | python3 -m venv .venv 19 | source .venv/bin/activate 20 | pip install -r requirements.txt 21 | python contrib/env_gen.py 22 | python manage.py migrate 23 | ``` -------------------------------------------------------------------------------- /myproject/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.auth.views import LoginView, LogoutView 3 | from django.urls import include, path 4 | 5 | from myproject.core.forms import LoginForm 6 | 7 | urlpatterns = [ 8 | path('', include('myproject.core.urls', namespace='core')), 9 | path( 10 | 'login/', 11 | LoginView.as_view( 12 | template_name='core/auth.html', authentication_form=LoginForm 13 | ), 14 | name='authenticate' 15 | ), 16 | path('logout/', LogoutView.as_view(), name='logout'), 17 | path('admin/', admin.site.urls), 18 | ] 19 | -------------------------------------------------------------------------------- /myproject/core/tests/test_auth_backends.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import authenticate, get_user_model 2 | from django.test import TestCase 3 | 4 | from ..models import UserProfile 5 | 6 | User = get_user_model() 7 | 8 | 9 | class TestCpfBackend(TestCase): 10 | 11 | def setUp(self): 12 | self.user = User.objects.create_user( 13 | username='walison', 14 | password='10203040' 15 | ) 16 | UserProfile.objects.create(user=self.user, cpf='25197394013') 17 | 18 | def test_authenticate_with_valid_credentials(self): 19 | self.assertEqual( 20 | authenticate(username='25197394013', password='10203040'), 21 | self.user 22 | ) 23 | -------------------------------------------------------------------------------- /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 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /contrib/env_gen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Django SECRET_KEY generator. 5 | """ 6 | from django.utils.crypto import get_random_string 7 | 8 | chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' 9 | 10 | CONFIG_STRING = """ 11 | DEBUG=True 12 | SECRET_KEY=%s 13 | ALLOWED_HOSTS=127.0.0.1, .localhost 14 | #DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME 15 | #DEFAULT_FROM_EMAIL= 16 | #EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend 17 | #EMAIL_HOST= 18 | #EMAIL_PORT= 19 | #EMAIL_USE_TLS= 20 | #EMAIL_HOST_USER= 21 | #EMAIL_HOST_PASSWORD= 22 | """.strip() % get_random_string(50, chars) 23 | 24 | # Writing our configuration file to '.env' 25 | with open('.env', 'w') as configfile: 26 | configfile.write(CONFIG_STRING) 27 | -------------------------------------------------------------------------------- /myproject/core/auth_backends.py: -------------------------------------------------------------------------------- 1 | from django.contrib import messages 2 | from django.contrib.auth import get_user_model 3 | from django.contrib.auth.backends import ModelBackend 4 | 5 | User = get_user_model() 6 | 7 | 8 | class CpfBackend(ModelBackend): 9 | 10 | def authenticate(self, request, username, password=None, **kwargs): 11 | try: 12 | user = User.objects.get(profile__cpf=username) 13 | except User.DoesNotExist: 14 | User().set_password(password) 15 | messages.error(request, 'CPF não existe.') 16 | else: 17 | if (user.check_password(password) and self.user_can_authenticate(user)): # noqa E501 18 | return user 19 | 20 | messages.error(request, 'Senha inválida.') 21 | -------------------------------------------------------------------------------- /myproject/core/templates/core/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 | 5 | {% for message in messages %} 6 | {% if 'success' in message.tags %} 7 | 8 | {% else %} 9 | 10 | {% endif %} 11 | {% endfor %} 12 | 13 | 14 |
15 |
16 |

Bem-vindo!

17 |

Exemplo de login com CPF.

18 | {% if user.is_authenticated %} 19 |

Seu login é {{ request.user }}

20 | {% endif %} 21 |
22 |
23 | 24 | {% endblock content %} -------------------------------------------------------------------------------- /myproject/core/migrations/0002_auto_20191005_2020.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.5 on 2019-10-05 23:20 2 | 3 | import django.db.models.deletion 4 | from django.conf import settings 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('core', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name='userprofile', 17 | name='cpf', 18 | field=models.CharField(max_length=14, unique=True), 19 | ), 20 | migrations.AlterField( 21 | model_name='userprofile', 22 | name='user', 23 | field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL), 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /myproject/core/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.5 on 2019-09-02 20:29 2 | 3 | import django.db.models.deletion 4 | from django.conf import settings 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='UserProfile', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('cpf', models.CharField(max_length=14)), 22 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users', to=settings.AUTH_USER_MODEL)), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /myproject/core/templates/includes/nav.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /myproject/core/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | {% block title %} Custom Login {% endblock title %} 10 | 11 | 12 | 13 | 14 | 15 | 20 | 21 | {% block css %}{% endblock css %} 22 | 23 | 24 | 25 | 26 | 27 | {% include "includes/nav.html" %} 28 | 29 |
30 | {% block content %}{% endblock content %} 31 |
32 | 33 | 34 | 35 | 36 | 37 | 38 | {% block js %}{% endblock js %} 39 | 40 | 41 | -------------------------------------------------------------------------------- /myproject/core/tests/test_views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import get_user_model 2 | from django.test import TestCase 3 | 4 | from ..models import UserProfile 5 | 6 | User = get_user_model() 7 | 8 | 9 | class TestLoginView(TestCase): 10 | def setUp(self): 11 | self.user = User.objects.create_user( 12 | username='walison', 13 | password='10203040' 14 | ) 15 | UserProfile.objects.create(user=self.user, cpf='25197394013') 16 | 17 | def test_template(self): 18 | response = self.client.get('/login/') 19 | 20 | self.assertTemplateUsed(response, 'core/auth.html') 21 | 22 | def test_contains_expected_fields(self): 23 | response = self.client.get('/login/') 24 | 25 | self.assertContains(response, 'CPF') 26 | self.assertContains(response, 'Senha') 27 | self.assertContains(response, 'Login') 28 | 29 | def test_success_login(self): 30 | valid_credentials = {'username': '25197394013', 'password': '10203040'} 31 | response = self.client.post('/login/', data=valid_credentials, follow=True) 32 | 33 | user = response.context['user'] 34 | 35 | self.assertRedirects(response, '/') 36 | self.assertTrue(user.is_authenticated) 37 | self.assertEqual(user, self.user) 38 | 39 | def test_failed_login(self): 40 | invalid_credentials = {'username': '0000000000', 'password': '10203040'} 41 | response = self.client.post('/login/', data=invalid_credentials, follow=True) 42 | 43 | user = response.context['user'] 44 | 45 | self.assertFalse(user.is_authenticated) 46 | self.assertNotEqual(user, self.user) 47 | -------------------------------------------------------------------------------- /.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 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .vscode/ -------------------------------------------------------------------------------- /myproject/core/templates/core/auth.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% load widget_tweaks %} 4 | 5 | {% block title %}Auth{% endblock title %} 6 | 7 | {% block content %} 8 | 9 | {% for message in messages %} 10 | {% if 'success' in message.tags %} 11 | 12 | {% else %} 13 | 14 | {% endif %} 15 | {% endfor %} 16 | 17 |
18 | {% csrf_token %} 19 | {{ form.non_fields_errors }} 20 |
21 | 24 |
25 | {{ form.username|attr:"class:form-control" }} {{ form.cpf.errors }} 26 |
27 |
28 |
29 | 32 |
33 | {{ form.password|attr:"class:form-control" }} {{ form.password.errors }} 34 |
35 |
36 | 37 |
38 |
39 | 40 |
41 |
42 |
43 | 44 | {% endblock content %} 45 | 46 | {% block js %} 47 | 55 | {% endblock js %} -------------------------------------------------------------------------------- /myproject/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for myproject project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | from decouple import Csv, config 16 | from dj_database_url import parse as dburl 17 | 18 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 19 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 20 | 21 | 22 | # Quick-start development settings - unsuitable for production 23 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 24 | 25 | # SECURITY WARNING: keep the secret key used in production secret! 26 | SECRET_KEY = config('SECRET_KEY') 27 | 28 | # SECURITY WARNING: don't run with debug turned on in production! 29 | DEBUG = config('DEBUG', default=False, cast=bool) 30 | 31 | ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) 32 | 33 | 34 | # Application definition 35 | 36 | INSTALLED_APPS = [ 37 | 'django.contrib.admin', 38 | 'django.contrib.auth', 39 | 'django.contrib.contenttypes', 40 | 'django.contrib.sessions', 41 | 'django.contrib.messages', 42 | 'django.contrib.staticfiles', 43 | 'widget_tweaks', 44 | 'django_extensions', 45 | 'myproject.core', 46 | ] 47 | 48 | MIDDLEWARE = [ 49 | 'django.middleware.security.SecurityMiddleware', 50 | 'django.contrib.sessions.middleware.SessionMiddleware', 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 | ROOT_URLCONF = 'myproject.urls' 59 | 60 | TEMPLATES = [ 61 | { 62 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 63 | 'DIRS': [], 64 | 'APP_DIRS': True, 65 | 'OPTIONS': { 66 | 'context_processors': [ 67 | 'django.template.context_processors.debug', 68 | 'django.template.context_processors.request', 69 | 'django.contrib.auth.context_processors.auth', 70 | 'django.contrib.messages.context_processors.messages', 71 | ], 72 | }, 73 | }, 74 | ] 75 | 76 | WSGI_APPLICATION = 'myproject.wsgi.application' 77 | 78 | 79 | # Database 80 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 81 | 82 | default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') 83 | DATABASES = { 84 | 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'pt-br' 111 | 112 | TIME_ZONE = 'America/Sao_Paulo' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 123 | 124 | STATIC_URL = '/static/' 125 | STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 126 | LOGOUT_REDIRECT_URL = 'core:home' 127 | LOGIN_REDIRECT_URL = 'core:home' 128 | 129 | AUTHENTICATION_BACKENDS = [ 130 | 'myproject.core.auth_backends.CpfBackend', 131 | 'django.contrib.auth.backends.ModelBackend' 132 | ] 133 | --------------------------------------------------------------------------------