├── api ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── tests.py ├── apps.py ├── admin.py ├── urls.py ├── serializers.py ├── models.py └── views.py ├── login_rest ├── __init__.py ├── wsgi.py ├── urls.py └── settings.py ├── templates └── login.html ├── README.rst ├── requirements.txt ├── manage.py └── .gitignore /api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /login_rest/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | name = 'api' 6 | -------------------------------------------------------------------------------- /api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Persona 3 | 4 | admin.site.register(Persona) 5 | -------------------------------------------------------------------------------- /templates/login.html: -------------------------------------------------------------------------------- 1 |
6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | #