├── .gitignore ├── README.rst ├── api ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── serializers.py ├── tests.py ├── urls.py └── views.py ├── login_rest ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── requirements.txt └── templates └── login.html /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/django 3 | # Edit at https://www.gitignore.io/?templates=django 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | db.sqlite3 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 | pip-wheel-metadata/ 41 | share/python-wheels/ 42 | *.egg-info/ 43 | .installed.cfg 44 | *.egg 45 | MANIFEST 46 | 47 | # PyInstaller 48 | # Usually these files are written by a python script from a template 49 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 50 | *.manifest 51 | *.spec 52 | 53 | # Installer logs 54 | pip-log.txt 55 | pip-delete-this-directory.txt 56 | 57 | # Unit test / coverage reports 58 | htmlcov/ 59 | .tox/ 60 | .nox/ 61 | .coverage 62 | .coverage.* 63 | .cache 64 | nosetests.xml 65 | coverage.xml 66 | *.cover 67 | .hypothesis/ 68 | .pytest_cache/ 69 | 70 | # Translations 71 | *.mo 72 | 73 | # Django stuff: 74 | 75 | # Flask stuff: 76 | instance/ 77 | .webassets-cache 78 | 79 | # Scrapy stuff: 80 | .scrapy 81 | 82 | # Sphinx documentation 83 | docs/_build/ 84 | 85 | # PyBuilder 86 | target/ 87 | 88 | # Jupyter Notebook 89 | .ipynb_checkpoints 90 | 91 | # IPython 92 | profile_default/ 93 | ipython_config.py 94 | 95 | # pyenv 96 | .python-version 97 | 98 | # pipenv 99 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 100 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 101 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 102 | # install all needed dependencies. 103 | #Pipfile.lock 104 | 105 | # celery beat schedule file 106 | celerybeat-schedule 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # End of https://www.gitignore.io/api/django 139 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Autenticación vía Token con Django Rest Framework 3 | ===== 4 | 5 | Proyecto con implementación de Login y Logout utilizando el método 6 | Token para la Autenticación. 7 | -------------------------------------------------------------------------------- /api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerpe/authentication_token_django_rest/3e060b294849d0e27ae25b455dced22d042ac9cb/api/__init__.py -------------------------------------------------------------------------------- /api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Persona 3 | 4 | admin.site.register(Persona) 5 | -------------------------------------------------------------------------------- /api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | name = 'api' 6 | -------------------------------------------------------------------------------- /api/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2019-08-12 22:34 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Persona', 16 | fields=[ 17 | ('id', models.AutoField(primary_key=True, serialize=False)), 18 | ('nombre', models.CharField(max_length=100, verbose_name='Nombre')), 19 | ('apellido', models.CharField(max_length=200, verbose_name='Apellido')), 20 | ], 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerpe/authentication_token_django_rest/3e060b294849d0e27ae25b455dced22d042ac9cb/api/migrations/__init__.py -------------------------------------------------------------------------------- /api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | class Persona(models.Model): 4 | id = models.AutoField(primary_key = True) 5 | nombre = models.CharField('Nombre', max_length = 100) 6 | apellido = models.CharField('Apellido', max_length = 200) 7 | 8 | def __str__(self): 9 | return '{0},{1}'.format(self.apellido,self.nombre) 10 | -------------------------------------------------------------------------------- /api/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from .models import Persona 3 | 4 | class PersonaSerializer(serializers.ModelSerializer): 5 | class Meta: 6 | model = Persona 7 | fields = ( 8 | 'id', 9 | 'nombre', 10 | 'apellido', 11 | ) 12 | -------------------------------------------------------------------------------- /api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import PersonaList 3 | 4 | urlpatterns = [ 5 | path('persona/',PersonaList.as_view(), name = 'persona_list'), 6 | ] 7 | -------------------------------------------------------------------------------- /api/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render,redirect 2 | from rest_framework import generics 3 | from django.urls import reverse_lazy 4 | from django.utils.decorators import method_decorator 5 | from django.views.decorators.cache import never_cache 6 | from django.views.decorators.csrf import csrf_protect 7 | from django.views.generic.edit import FormView 8 | from django.contrib.auth import login,logout,authenticate 9 | from django.http import HttpResponseRedirect 10 | from django.contrib.auth.forms import AuthenticationForm 11 | from rest_framework.authtoken.models import Token 12 | from rest_framework.permissions import IsAuthenticated 13 | from rest_framework.authentication import TokenAuthentication 14 | from rest_framework.views import APIView 15 | from rest_framework import status 16 | from rest_framework.response import Response 17 | from .models import Persona 18 | from .serializers import PersonaSerializer 19 | 20 | 21 | class PersonaList(generics.ListCreateAPIView): 22 | queryset = Persona.objects.all() 23 | serializer_class = PersonaSerializer 24 | permission_classes = (IsAuthenticated,) 25 | authentication_class = (TokenAuthentication,) 26 | 27 | 28 | class Login(FormView): 29 | template_name = "login.html" 30 | form_class = AuthenticationForm 31 | success_url = reverse_lazy('api:persona_list') 32 | 33 | @method_decorator(csrf_protect) 34 | @method_decorator(never_cache) 35 | def dispatch(self,request,*args,**kwargs): 36 | if request.user.is_authenticated: 37 | return HttpResponseRedirect(self.get_success_url()) 38 | else: 39 | return super(Login,self).dispatch(request,*args,*kwargs) 40 | 41 | def form_valid(self,form): 42 | user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password']) 43 | token,_ = Token.objects.get_or_create(user = user) 44 | if token: 45 | login(self.request, form.get_user()) 46 | return super(Login,self).form_valid(form) 47 | 48 | class Logout(APIView): 49 | def get(self,request, format = None): 50 | request.user.auth_token.delete() 51 | logout(request) 52 | return Response(status = status.HTTP_200_OK) 53 | -------------------------------------------------------------------------------- /login_rest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerpe/authentication_token_django_rest/3e060b294849d0e27ae25b455dced22d042ac9cb/login_rest/__init__.py -------------------------------------------------------------------------------- /login_rest/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for login_rest project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.1. 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 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'pf*l+g9_rbjl5-)^1clzxgy1_g+)a(y7bo7exu4m7azt^m@8h%' 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 | 'rest_framework', 41 | 'rest_framework.authtoken', 42 | 'api', 43 | ] 44 | 45 | 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | 'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'login_rest.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': ['templates'], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | }, 72 | }, 73 | ] 74 | 75 | WSGI_APPLICATION = 'login_rest.wsgi.application' 76 | 77 | 78 | # Database 79 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 80 | 81 | DATABASES = { 82 | 'default': { 83 | 'ENGINE': 'django.db.backends.sqlite3', 84 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 85 | } 86 | } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'es-pe' 112 | 113 | TIME_ZONE = 'America/Lima' 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | 122 | # Static files (CSS, JavaScript, Images) 123 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 124 | 125 | STATIC_URL = '/static/' 126 | -------------------------------------------------------------------------------- /login_rest/urls.py: -------------------------------------------------------------------------------- 1 | """login_rest URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/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 | from rest_framework.authtoken import views 19 | from api.views import Login,Logout 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('api/1.0/',include(('api.urls','api'))), 24 | path('api_generate_token/', views.obtain_auth_token), 25 | path('login/',Login.as_view(), name = 'login'), 26 | path('logout/', Logout.as_view()), 27 | ] 28 | -------------------------------------------------------------------------------- /login_rest/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for login_rest 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', 'login_rest.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 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'login_rest.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 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2019.6.16 2 | chardet==3.0.4 3 | Django==2.2.4 4 | djangorestframework==3.10.2 5 | httpie==1.0.2 6 | idna==2.8 7 | pkg-resources==0.0.0 8 | Pygments==2.4.2 9 | pytz==2019.2 10 | requests==2.22.0 11 | sqlparse==0.3.0 12 | urllib3==1.25.3 13 | -------------------------------------------------------------------------------- /templates/login.html: -------------------------------------------------------------------------------- 1 |
2 | {% csrf_token %} 3 | {{ form }} 4 | 5 |
6 | --------------------------------------------------------------------------------