├── 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 |
{{ message }}
8 | {% else %} 9 |{{ message }}
10 | {% endif %} 11 | {% endfor %} 12 | 13 | 14 |Exemplo de login com CPF.
18 | {% if user.is_authenticated %} 19 |Seu login é {{ request.user }}
20 | {% endif %} 21 |