74 lines
2.4 KiB
Python
74 lines
2.4 KiB
Python
from rest_framework import viewsets
|
|
from rest_framework.decorators import action, api_view, schema
|
|
from rest_framework.schemas import AutoSchema
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from django.http import HttpResponse
|
|
from django.http import JsonResponse
|
|
from .models import Usuario, Persona
|
|
from .models import Aplicacion
|
|
from .serializers import UsuarioSerializer, PersonaSerializer
|
|
from .serializers import AplicacionSerializer, AuthSerializer
|
|
import json
|
|
import jwt
|
|
import datetime
|
|
import coreapi
|
|
from decouple import config
|
|
|
|
private_key = config('SECRET_JWT')
|
|
|
|
# Create your views here.
|
|
class AplicacionViewSet(viewsets.ModelViewSet):
|
|
queryset = Aplicacion.objects.all()
|
|
serializer_class = AplicacionSerializer
|
|
ordering_fields = '__all__'
|
|
|
|
class PersonaViewSet(viewsets.ModelViewSet):
|
|
queryset = Persona.objects.all()
|
|
serializer_class = PersonaSerializer
|
|
|
|
class UsuarioViewSet(viewsets.ModelViewSet):
|
|
queryset = Usuario.objects.all()
|
|
serializer_class = UsuarioSerializer
|
|
|
|
|
|
class CustomAuthSchema(AutoSchema):
|
|
manual_fields = []
|
|
|
|
def get_manual_fields(self, path, method):
|
|
custom_fields = []
|
|
if method.lower() == 'post':
|
|
custom_fields = [
|
|
coreapi.Field('username', required=True, location='form', description='Usuario'),
|
|
coreapi.Field('password', required=True, location='form', description='Contraseña'),
|
|
]
|
|
return self._manual_fields + custom_fields
|
|
|
|
# Views jwt
|
|
@csrf_exempt
|
|
@action(detail=False, methods=['post','get'])
|
|
@api_view(['GET','POST'])
|
|
@schema(CustomAuthSchema())
|
|
def jwt_login(request):
|
|
if request.method == 'POST':
|
|
# validar username y password
|
|
json_data = json.loads(request.body)
|
|
username = json_data['username']
|
|
password = json_data['password']
|
|
|
|
usuario = Usuario.objects.filter(login = username, vigente = True).values().first()
|
|
if not usuario:
|
|
return HttpResponse('Acceso no valido', status = 400)
|
|
|
|
if usuario['clave'] != password:
|
|
return HttpResponse('Acceso no valido', status = 400)
|
|
|
|
now = datetime.datetime.utcnow()
|
|
payload = {
|
|
'exp': now + datetime.timedelta(minutes=60),
|
|
'login': usuario['login']
|
|
}
|
|
token = jwt.encode(payload, private_key, algorithm="HS256")
|
|
return JsonResponse({ 'token': token })
|
|
elif request.method == 'GET':
|
|
return JsonResponse(request.jwt_info)
|
|
|