58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
![]() |
|
||
|
from django.views.decorators.csrf import csrf_exempt
|
||
|
from django.http import HttpResponse
|
||
|
from django.http import JsonResponse
|
||
|
|
||
|
from rest_framework.decorators import action, api_view, schema
|
||
|
|
||
|
from .. import models, schemas
|
||
|
from decouple import config
|
||
|
import json
|
||
|
import jwt
|
||
|
from datetime import datetime, timedelta
|
||
|
import logging
|
||
|
|
||
|
private_key = config('SECRET_JWT')
|
||
|
|
||
|
# Views jwt
|
||
|
@csrf_exempt
|
||
|
@action(detail=False, methods=['post','get'])
|
||
|
@api_view(['GET','POST'])
|
||
|
@schema(schemas.AuthSchema())
|
||
|
def jwt_login(request):
|
||
|
if request.method == 'POST':
|
||
|
count = models.Usuario.objects.filter(vigente = True).count()
|
||
|
logging.error(f'count usuario vigente = {count}')
|
||
|
|
||
|
# validar username y password
|
||
|
input = json.loads(request.body)
|
||
|
username = input['username']
|
||
|
password = input['password']
|
||
|
usuario = None
|
||
|
|
||
|
if count > 0:
|
||
|
usuario = models.Usuario.objects.filter(login = username, vigente = True).values().first()
|
||
|
elif username == '0' and password == '0':
|
||
|
usuario = { 'login': '0', 'clave': '0' }
|
||
|
|
||
|
if not usuario:
|
||
|
return HttpResponse('Acceso no valido', status=400)
|
||
|
|
||
|
if username != '0':
|
||
|
clave = models.UsuarioClave.objects.filter(login = username).first()
|
||
|
if not clave or clave.clave != password:
|
||
|
return HttpResponse('Acceso no valido', status=400)
|
||
|
|
||
|
ahora = datetime.utcnow()
|
||
|
manana = ahora + timedelta(days=1)
|
||
|
manana = manana.replace(hour=0, minute=0, second=0, microsecond=0)
|
||
|
|
||
|
payload = {
|
||
|
'iat': ahora,
|
||
|
'exp': manana, # ahora + 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)
|