def test_init_fails_for_rs_algorithms_when_crypto_not_installed(self):
     with self.assertRaisesRegex(TokenBackendError, 'You must have cryptography installed to use RS256.'):
         TokenBackend('RS256', 'not_secret')
     with self.assertRaisesRegex(TokenBackendError, 'You must have cryptography installed to use RS384.'):
         TokenBackend('RS384', 'not_secret')
     with self.assertRaisesRegex(TokenBackendError, 'You must have cryptography installed to use RS512.'):
         TokenBackend('RS512', 'not_secret')
 def setUp(self):
     self.hmac_token_backend = TokenBackend('HS256', secret_key=SECRET)
     self.hmac_custom_user_key_token_backend = TokenBackend(
         'HS256', get_user_secret_key=lambda a: a)
     self.rsa_token_backend = TokenBackend('RS256',
                                           signing_key=PRIVATE_KEY,
                                           verifying_key=PUBLIC_KEY)
     self.aud_iss_token_backend = TokenBackend('RS256', PRIVATE_KEY,
                                               PUBLIC_KEY, AUDIENCE, ISSUER)
     self.payload = {'foo': 'bar'}
示例#3
0
 def test_init_fails_for_rs_algorithms_when_crypto_not_installed(self):
     for algo in ("RS256", "RS384", "RS512", "ES256"):
         with self.assertRaisesRegex(
                 TokenBackendError,
                 f"You must have cryptography installed to use {algo}.",
         ):
             TokenBackend(algo, "not_secret")
    def test_decode_rsa_aud_iss_jwk_success(self):
        self.payload["exp"] = aware_utcnow() + timedelta(days=1)
        self.payload["foo"] = "baz"
        self.payload["aud"] = AUDIENCE
        self.payload["iss"] = ISSUER

        token = jwt.encode(
            self.payload,
            PRIVATE_KEY_2,
            algorithm="RS256",
            headers={"kid": "230498151c214b788dd97f22b85410a5"},
        )
        # Payload copied
        self.payload["exp"] = datetime_to_epoch(self.payload["exp"])

        mock_jwk_module = mock.MagicMock()
        with patch("rest_framework_simplejwt.backends.PyJWKClient") as mock_jwk_module:
            mock_jwk_client = mock.MagicMock()
            mock_signing_key = mock.MagicMock()

            mock_jwk_module.return_value = mock_jwk_client
            mock_jwk_client.get_signing_key_from_jwt.return_value = mock_signing_key
            type(mock_signing_key).key = mock.PropertyMock(return_value=PUBLIC_KEY_2)

            # Note the PRIV,PUB care is intentially the original pairing
            jwk_token_backend = TokenBackend(
                "RS256", PRIVATE_KEY, PUBLIC_KEY, AUDIENCE, ISSUER, JWK_URL
            )

            self.assertEqual(jwk_token_backend.decode(token), self.payload)
示例#5
0
 def test_custom_JSONEncoder(self):
     backend = TokenBackend("HS256", SECRET, json_encoder=UUIDJSONEncoder)
     unique = uuid.uuid4()
     self.payload["uuid"] = unique
     token = backend.encode(self.payload)
     decoded = backend.decode(token)
     self.assertEqual(decoded["uuid"], str(unique))
示例#6
0
 def post(self, request):
     serializer = PasswordSendResetSerializer(data=request.data)
     if serializer.is_valid():
         if CustomUser.objects.filter(email=serializer.validated_data.get('email')).exists():
             reset = serializer.save()
             # TODO check if token isn't used
             tokenbackend = TokenBackend(algorithm='RS256',
                                         signing_key=getattr(settings, "RS256_PRIVATE_KEY", None),
                                         verifying_key=getattr(settings, "RS256_PUBLIC_KEY", None))
             reset = UserResetToken(email=reset.email,
                                    expire=datetime.utcnow() + timedelta(0,
                                                                                           3600) + timedelta(
                                        0, 3600) + timedelta(0, 3600),
                                    created_on=datetime.utcnow() + timedelta(0,
                                                                                               3600) + timedelta(
                                        0, 3600),
                                    used=False
                                    )
             reset.save()
             token = tokenbackend.encode(
                 {'user_email': reset.email, 'exp': datetime.utcnow() + timedelta(0, 3600)})
             # TODO check if user is active
             mail_subject = 'Reset your password.'
             current_site = get_current_site(request)
             activation_link = "http://{0}/passreset/{1}".format(current_site, token)
             message = "Hello ,\n click the link below to reset your password.\n {0}".format(activation_link)
             email = EmailMessage(mail_subject, message, to=[reset.email])
             email.send()
         return Response(serializer.errors, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#7
0
def get_jwt_payload(request):
    jwt_object = JWTAuthentication()
    header = jwt_object.get_header(request)
    raw_token = jwt_object.get_raw_token(header)
    validated_token = jwt_object.get_validated_token(raw_token)
    token_backend = TokenBackend(algorithm='HS256')
    payload = token_backend.decode(token=str(validated_token), verify=False)
    return payload
示例#8
0
def usuarioAutenticado(request):

    # Decodificando el access token
    tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                settings.SIMPLE_JWT['SIGNING_KEY'],
                                settings.SIMPLE_JWT['VERIFYING_KEY'])
    tokenDecoded = tokenBackend.decode(
        request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)
    # consultando el usuario
    user = models.User.objects.get(pk=tokenDecoded['user_id'])

    return user
    def test_decode_hmac_custom_changed_user(self):
        token_backend = TokenBackend(
            'HS256',
            get_user_secret_key=lambda a: str(a) + str(randint(0, 1000000000)))
        payload = {
            'exp': make_utc(datetime(year=2000, month=1, day=1)),
            'id': '1234'
        }

        token = token_backend.encode(payload)

        with self.assertRaises(TokenBackendError):
            self.hmac_token_backend.decode(token)
示例#10
0
def user_from_token(token):
    """
    Return User model from token by decoded id in token
    """

    try:
        valid_data = TokenBackend(algorithm='HS256').decode(token,
                                                            verify=False)
        user_id = valid_data['user_id']
        user = User.objects.get(pk=user_id)
        return user
    except:
        return None
示例#11
0
 def get(self, request):
     r"""
     This method handles the get request with token assigned to the user and checks if the token is valid. 
     """
     token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
     data = {'token': token}
     try:
         valid_data = TokenBackend(algorithm='HS256').decode(token,
                                                             verify=False)
         user = valid_data['user']
         request.user = user
     except ValidationError as v:
         print("validation error", v)
示例#12
0
 def post(self, request):
     """
     проверяет полноту данных запроса,
     по email находит в БД пользователя user,
     если такой находится выполняет действия action
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = get_object_or_404(User, email=request.data.get('email'))
     token = TokenBackend(
         SIMPLE_JWT['ALGORITHM'],
         signing_key=SIMPLE_JWT['SIGNING_KEY'],
     )
     return self.action(user, token, serializer)
示例#13
0
def decode_token(token):
    """ little function to decode a token """

    tbe = TokenBackend(SIMPLE_JWT['ALGORITHM'])

    try:

        decoded = tbe.decode(token, False)

    except TokenBackendError:

        return 0

    return decoded
示例#14
0
def get_user(token_key, user_id):
    try:
        valid_data = TokenBackend(algorithm='HS256').decode(token_key,
                                                            verify=False)
        print(token_key)
        print(valid_data)
        user = valid_data['user_id']
        print(user, user_id, token_key)
        if user == int(user_id):
            return User.objects.get(id=user)
        else:
            raise
    except Exception as e:
        print(e)
        return AnonymousUser()
示例#15
0
    def __call__(self, request):

        if not (request.path.startswith('/api/token')
                or request.path.startswith('/api/register/')):
            token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
            data = {'token': token}
            try:
                valid_data = TokenBackend(algorithm='HS256').decode(
                    token, verify=False)
                user_id = valid_data['user_id']
                request.user_id = user_id
            except ValidationError as v:
                logger.error("Error occured during decoding" + str(v))

        response = self.get_response(request)
        return response
示例#16
0
 def setUp(self):
     self.hmac_token_backend = TokenBackend("HS256", SECRET)
     self.hmac_leeway_token_backend = TokenBackend("HS256", SECRET, leeway=LEEWAY)
     self.rsa_token_backend = TokenBackend("RS256", PRIVATE_KEY, PUBLIC_KEY)
     self.aud_iss_token_backend = TokenBackend(
         "RS256", PRIVATE_KEY, PUBLIC_KEY, AUDIENCE, ISSUER
     )
     self.payload = {"foo": "bar"}
     self.backends = (
         self.hmac_token_backend,
         self.rsa_token_backend,
         TokenBackend("ES256", ES256_PRIVATE_KEY, ES256_PUBLIC_KEY),
         TokenBackend("ES384", ES256_PRIVATE_KEY, ES256_PUBLIC_KEY),
         TokenBackend("ES512", ES256_PRIVATE_KEY, ES256_PUBLIC_KEY),
     )
示例#17
0
    async def __call__(self, send, receive):
        headers = dict(self.scope['headers'])
        print("Headers", headers)
        if b'sec-websocket-protocol' in headers:

            try:
                token_name, token_key = headers[b'sec-websocket-protocol'].decode().split('%space%')
                if token_name == 'Bearer':
                    valid_data = TokenBackend(algorithm='HS256').decode(token_key, verify=False)
                    print(valid_data['user_id'])
                    # print("Access_token", access_token)
                    # user = CustomMember.objects.get(id=valid_data['user_id'])
                    user = await get_user(valid_data)
                    print("Token key: ", token_key)
                    self.scope['user'] = user
                    print(user)
                    print("Embedded user to header")
            except TokenError:
                self.scope['user'] = AnonymousUser()
        inner = self.inner(self.scope)
        return await inner(receive, send)
示例#18
0
 def post(self, request, **kwargs):
     if True:
         token = kwargs.pop('token')
         tokenbackend = TokenBackend(algorithm='RS256',
                                     signing_key=getattr(settings, "RS256_PRIVATE_KEY", None),
                                     verifying_key=getattr(settings, "RS256_PUBLIC_KEY", None))
         try:
             payload = tokenbackend.decode(token=token, verify=True)
         except TokenBackendError:
             return Response({'error': 'Invalid token'}, status=status.HTTP_403_FORBIDDEN)
         if UserResetToken.expire == (
                 datetime.utcnow() + timedelta(3600) + timedelta(0, 3600)):
             return Response(status=status.HTTP_409_CONFLICT)
         if UserResetToken.used is True:
             return Response(status=status.HTTP_409_CONFLICT)
         email = payload.get('user_email')
         user = CustomUser.objects.get(email=email)
         password = request.data['password']
         user.set_password(password)
         user.save()
         return Response(status=status.HTTP_202_ACCEPTED)
示例#19
0
 def get(self, request, *args, **kwargs):
     token = kwargs.pop('token')
     # TODO check token isnt used
     tokenbackend = TokenBackend(algorithm='RS256',
                                 signing_key=getattr(settings, "RS256_PRIVATE_KEY", None),
                                 verifying_key=getattr(settings, "RS256_PUBLIC_KEY", None))
     try:
         payload = tokenbackend.decode(token=token, verify=True)
     except TokenBackendError:
         return Response({'error': 'Invalid token'}, status=status.HTTP_403_FORBIDDEN)
     if UserActivationToken.expire == (
             datetime.utcnow() + timedelta(3600) + timedelta(0, 3600)):
         return Response(status=status.HTTP_409_CONFLICT)
     if UserActivationToken.used is True:
         return Response(status=status.HTTP_409_CONFLICT)
     user = CustomUser.objects.get(id=payload.get('user_id'))
     # token_id = UserActivationToken.pk
     # UserActivationToken.objects.get(id=payload.get('token_id'))
     user.is_active = True
     user.save()
     return Response(
         {"message": 'User Activated'},
         status=status.HTTP_200_OK
     )
示例#20
0
 def post(self, request, *args, **kwargs, ):
     serializer = CustomUserSerializer(data=request.data)
     if serializer.is_valid():
         # userr = CustomUser.objects.filter(email=serializer.email)
         if CustomUser.objects.filter(email=serializer.validated_data.get('email')).exists():
             return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
         elif CustomUser.objects.filter(username=serializer.validated_data.get('username')).exists():
             return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
         user = serializer.save()
         tokenbackend = TokenBackend(algorithm='RS256',
                                     signing_key=getattr(settings, "RS256_PRIVATE_KEY", None),
                                     verifying_key=getattr(settings, "RS256_PUBLIC_KEY", None))
         activation = UserActivationToken(user=CustomUser.objects.get(id=user.id),
                                          expire=datetime.utcnow() + timedelta(0,3600) + timedelta(0, 3600) + timedelta(0, 3600),
                                          created_on=datetime.utcnow() + timedelta(0,
                                          3600) + timedelta(
                                              0, 3600),
                                          used=False
                                          )
         activation.save()
         token = tokenbackend.encode(
             {'user_id': user.id, 'exp': datetime.utcnow() + timedelta(0, 3600)})
         data = {
             'confirmation_token': token
         }
         user.is_active = False
         user.save()
         mail_subject = 'Activate your account.'
         current_site = get_current_site(request)
         activation_link = "http://{0}/activateaccount/{1}".format(current_site, token)
         message = "Hello {0},\n click the link below to activate your account.\n {1}".format(user.username,
                                                                                              activation_link)
         email = EmailMessage(mail_subject, message, to=[user.email])
         email.send()
         return Response(data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#21
0
def categorizacion(request):

    try:
        barrioUbicacion = request.GET.get('barrioUbicacion')
        barrioSeleccion = request.GET.get('barrioSeleccion')
        year = request.GET.get('year')

        if request.META['HTTP_AUTHORIZATION'] != 'null':

            # Decodificando el access token
            tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                        settings.SIMPLE_JWT['SIGNING_KEY'],
                                        settings.SIMPLE_JWT['VERIFYING_KEY'])
            tokenDecoded = tokenBackend.decode(
                request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

            # consultando el usuario
            user = Usuario.objects.get(pk=tokenDecoded['user_id'])
            edadUsuario = calculoEdad(user.fecha_nacimiento)

        if barrioUbicacion is not None and barrioSeleccion is not None and year is not None:

            conflictividades = Conflictividad.objects.all()
            data = []

            for conf in conflictividades:

                queryIndicadorCiudad = "select SUM(t.cantidad) as count from \
                                        (select * from v1.contextualizaciones \
                                        where (confid = '{0}') \
                                        and (fecha_hecho between '{1}-01-01' and '{1}-12-31')) t;" \
                                        .format(conf.confid, year)

                queryIndicadorUbicacion = "select SUM(t.cantidad) as count from \
                                        (select * from v1.contextualizaciones \
                                        where confid = '{0}' \
                                        and barrioid = '{1}' \
                                        and (fecha_hecho between '{2}-01-01' and '{2}-12-31')) t;" \
                                        .format(conf.confid, barrioUbicacion, year)

                queryIndicadorSeleccion = "select SUM(t.cantidad) as count from \
                                           (select * from v1.contextualizaciones \
                                           where confid = '{0}' \
                                           and barrioid = '{1}' \
                                           and (fecha_hecho between '{2}-01-01' and '{2}-12-31')) t;" \
                                          .format(conf.confid, barrioSeleccion, year)

                if 'user' in locals():
                    queryIndicadorPerfil = "select SUM(t.cantidad) as count from \
                                               (select * from v1.contextualizaciones \
                                               where confid = '{0}' \
                                               and barrioid = {1} \
                                               and generoid = '{2}' \
                                               and nivelid = '{3}' \
                                               and edad = {4} \
                                               and (fecha_hecho between '{5}-01-01' and '{5}-12-31')) t;" \
                                               .format(conf.confid, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario, year)

                with connection.cursor() as cursor:
                    cursor.execute(queryIndicadorCiudad)
                    indicadorCiudad = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    cursor.execute(queryIndicadorUbicacion)
                    indicadorUbicacion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    cursor.execute(queryIndicadorSeleccion)
                    indicadorSeleccion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    if 'user' in locals():
                        cursor.execute(queryIndicadorPerfil)
                        indicadorPerfil = verificacionExistenciaConflictividades(
                            dictfetchall(cursor)[0]['count'])

                    if (indicadorCiudad != 0):
                        indicadorPromedio = indicadorCiudad / bisiesto(
                            int(year))
                    else:
                        indicadorPromedio = 0

                indicadores = {
                    'conflictividad': model_to_dict(conf),
                    'indicadores': {
                        'ciudad': indicadorCiudad,
                        'ubicacion': indicadorUbicacion,
                        'seleccion': indicadorSeleccion,
                        'promedio': indicadorPromedio
                    },
                }

                if 'user' in locals():
                    indicadores['indicadores']['perfil'] = indicadorPerfil

                data.append(indicadores)

                response = {'code': 200, 'data': data, 'status': 'success'}

        else:

            response = {'code': 400, 'status': 'error'}

    except (IndexError):
        response = {'code': 400, 'status': 'error'}

    except TokenBackendError as e:
        response = {'code': 400, 'message': str(e), 'status': 'error'}

    return JsonResponse(response, safe=False, status=response['code'])
示例#22
0
def almacenamientoProyecto(request):

    # Decodificando el access token
    tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY'])
    tokenDecoded = tokenBackend.decode(request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

    proyNombre = request.POST.get('proynombre')
    proyDescripcion = request.POST.get('proydescripcion')
    tipoProyecto = request.POST.get('tiproid')
    proyIdExterno = 12345
    proyFechaCreacion = datetime.today()
    proyfechainicio = request.POST.get('proyfechainicio')
    proyFechaCierre = request.POST.get('proyfechacierre')
    proyEstado = 1
    decisiones = request.POST.get('decisiones')
    contextos = request.POST.get('contextos')
    equipos = request.POST.get('plantillas')
    propietario = tokenDecoded['user_id']
    delimitacionGeograficas = request.POST.get('delimitacionesGeograficas')

    proyecto = models.Proyecto(proynombre = proyNombre, proydescripcion = proyDescripcion, proyidexterno = proyIdExterno, \
                               proyfechacreacion = proyFechaCreacion, proyfechainicio = proyfechainicio, proyfechacierre = proyFechaCierre, \
                               proyestado = proyEstado, proypropietario = propietario, tiproid=tipoProyecto)

    try:
        proyecto.full_clean()

        if delimitacionGeograficas is None:
            raise ValidationError({'delitacionesGeograficas': 'Requerido'})

        proyecto.save()

        if decisiones is not None:
            decisiones = json.loads(decisiones)
            almacenarDecisionProyecto(proyecto, decisiones)

        if contextos is not None:
            contextos = json.loads(contextos)
            almacenarContextosProyecto(proyecto, contextos)


        almacenarDelimitacionesGeograficas(proyecto, delimitacionGeograficas)

        if equipos is not None:
            equipos = json.loads(equipos)
            asignarEquipos(proyecto, equipos)

        data = serializers.serialize('python', [proyecto])[0]

        data = {
            'code': 201,
            'proyecto': data,
            'status': 'success'
        }

    except ValidationError as e:

        try:
            errors = dict(e)
        except ValueError:
            errors = list(e)[0]

        data = {
            'code': 400,
            'errors': errors,
            'status': 'error'
        }

    except IntegrityError as e:

        data = {
            'code': 500,
            'message': str(e),
            'status': 'success'
        }

    except ObjectDoesNotExist as e:
        data = {
            'code': 404,
            'message': str(e),
            'status': 'error'
        }

    return JsonResponse(data, safe = False, status = data['code'])
    def test_init(self):
        # Should reject unknown algorithms
        with self.assertRaises(TokenBackendError):
            TokenBackend('oienarst oieanrsto i', 'not_secret')

        TokenBackend('HS256', 'not_secret')
示例#24
0
def todo(request):

    try:

        barrioUbicacion = request.GET.get('barrioUbicacion')
        barrioSeleccion = request.GET.get('barrioSeleccion')

        if request.META['HTTP_AUTHORIZATION'] != 'null':

            # Decodificando el access token
            tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                        settings.SIMPLE_JWT['SIGNING_KEY'],
                                        settings.SIMPLE_JWT['VERIFYING_KEY'])
            tokenDecoded = tokenBackend.decode(
                request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

            # consultando el usuario
            user = Usuario.objects.get(pk=tokenDecoded['user_id'])
            edadUsuario = calculoEdad(user.fecha_nacimiento)

        if barrioUbicacion is not None and barrioSeleccion is not None:

            anioInicial = 2010
            anioFinal = 2019
            anios = []

            count = anioInicial

            conflictividadesCiudad = []
            conflictividadesUbicacion = []
            conflictividadesSeleccion = []
            conflictividadesPerfil = []

            while count <= anioFinal:

                anios.append(count)

                queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \
                        "SELECT * FROM v1.contextualizaciones " \
                        "WHERE fecha_hecho between '{0}-01-01' and '{0}-12-31') t" \
                        .format(count)

                queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \
                        "SELECT * FROM v1.contextualizaciones " \
                        "WHERE barrioid = {1} and " \
                        "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                        .format(count, barrioUbicacion)

                queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE barrioid = {1} and " \
                                          "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                          .format(count, barrioSeleccion)

                if 'user' in locals():
                    queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \
                                           "SELECT * FROM v1.contextualizaciones " \
                                           "WHERE barrioid = {1} " \
                                           "and generoid = '{2}' " \
                                           "and nivelid = '{3}' " \
                                           "and edad = {4} " \
                                           "and (fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                           .format(count, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario)

                with connection.cursor() as cursor:

                    # Indicador Ciudad
                    cursor.execute(queryIndicadorCiudad)
                    indicadorCiudad = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesCiudad.append(indicadorCiudad)

                    # Indicador Ubicación
                    cursor.execute(queryIndicadorUbicacion)
                    indicadorUbicacion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesUbicacion.append(indicadorUbicacion)

                    # Indicador Selección
                    cursor.execute(queryIndicadorSeleccion)
                    indicadorSeleccion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesSeleccion.append(indicadorSeleccion)

                    if 'user' in locals():
                        # Indicador Perfil
                        cursor.execute(queryIndicadorPerfil)
                        indicadorPerfil = verificacionExistenciaConflictividades(
                            dictfetchall(cursor)[0]['count'])

                        conflictividadesPerfil.append(indicadorPerfil)

                count += 1

            data = {
                'labels':
                anios,
                'datasets': [{
                    'label': 'ciudad',
                    'fill': False,
                    'borderColor': 'orange',
                    'data': conflictividadesCiudad
                }, {
                    'label': 'Ubicación',
                    'fill': False,
                    'borderColor': 'blue',
                    'data': conflictividadesUbicacion
                }, {
                    'label': 'Selección',
                    'fill': False,
                    'borderColor': 'green',
                    'data': conflictividadesSeleccion
                }]
            }

            if 'user' in locals():

                totalConflictividadesPerfil = 0

                for cp in conflictividadesPerfil:
                    totalConflictividadesPerfil = totalConflictividadesPerfil + cp

                data['datasets'].append({
                    'label':
                    'Perfil',
                    'fill':
                    False,
                    'borderColor':
                    'red',
                    'data':
                    conflictividadesPerfil,
                    'promedio':
                    totalConflictividadesPerfil / len(conflictividadesPerfil)
                })

            response = {'code': 200, 'data': data, 'status': 'success'}

        else:
            response = {'code': 400, 'status': 'error'}

    except (IndexError):

        response = {'code': 400, 'status': 'error'}

    except TokenBackendError as e:

        response = {'code': 400, 'message': str(e), 'status': 'error'}

    return JsonResponse(response, safe=False, status=response['code'])
示例#25
0
def almacenamientoProyecto(request):
    user = usuarioAutenticado(request)
    person = models.Person.objects.get(user__userid=user.userid)
    # Decodificando el access token
    tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                settings.SIMPLE_JWT['SIGNING_KEY'],
                                settings.SIMPLE_JWT['VERIFYING_KEY'])
    tokenDecoded = tokenBackend.decode(
        request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)
    delimintacionBarrio = request.POST.get('dimensionesPre')
    decisiones = request.POST.get('decisiones')
    contextos = request.POST.get('contextos')
    equipos = request.POST.get('plantillas')
    delimitacionGeograficas = request.POST.get('delimitacionesGeograficas')
    tipoP = models.ProjectType.objects.get(
        projtype_id__exact=request.POST.get('tiproid'))

    try:
        with transaction.atomic():
            if ((delimitacionGeograficas != "[]") and (decisiones != "[]")
                    and (contextos != "[]") and (equipos != "[]")):
                proyecto = models.Project(
                    proj_name=request.POST.get('proynombre'),
                    proj_description=request.POST.get('proydescripcion'),
                    proj_external_id=12345,
                    proj_close_date=request.POST.get('proyfechacierre'),
                    proj_start_date=request.POST.get('proyfechainicio'),
                    proj_completness=0,
                    project_type=tipoP,
                    proj_owner=person)
                proyecto.full_clean()
                proyecto.save()

                delimintacionBarrio = json.loads(delimintacionBarrio)
                almacenarDelimitacionesPrecarga(proyecto, delimintacionBarrio)

                delimitacionGeograficas = json.loads(delimitacionGeograficas)
                almacenarDelimitacionesGeograficas(proyecto,
                                                   delimitacionGeograficas)

                decisiones = json.loads(decisiones)
                almacenarDecisionProyecto(proyecto, decisiones)

                contextos = json.loads(contextos)
                almacenarContextosProyecto(proyecto, contextos)

                equipos = json.loads(equipos)
                asignarEquipos(proyecto, equipos)

                data = serializers.serialize('python', [proyecto])[0]

                data = {'code': 201, 'proyecto': data, 'status': 'success'}
            else:
                raise ValidationError({'Información incompleta'})

    except ValidationError as e:
        try:
            errors = dict(e)
        except ValueError:
            errors = list(e)[0]

        data = {
            'code': 400,
            'errors': errors,
            'message': str(e),
            'status': 'error'
        }

    except IntegrityError as e:

        data = {'code': 500, 'message': str(e), 'status': 'success'}

    except ObjectDoesNotExist as e:
        data = {'code': 404, 'message': str(e), 'status': 'error'}

    return JsonResponse(data, safe=False, status=data['code'])
示例#26
0
def dia(request):

    try:

        barrioUbicacion = request.GET.get('barrioUbicacion')
        barrioSeleccion = request.GET.get('barrioSeleccion')
        year = request.GET.get('year')

        if request.META['HTTP_AUTHORIZATION'] != 'null':
            # Decodificando el access token
            tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                        settings.SIMPLE_JWT['SIGNING_KEY'],
                                        settings.SIMPLE_JWT['VERIFYING_KEY'])
            tokenDecoded = tokenBackend.decode(
                request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

            # consultando el usuario
            user = Usuario.objects.get(pk=tokenDecoded['user_id'])
            edadUsuario = calculoEdad(user.fecha_nacimiento)

        if barrioUbicacion is not None and barrioSeleccion is not None and year is not None:

            conflictividadesCiudad = []
            conflictividadesUbicacion = []
            conflictividadesSeleccion = []
            conflictividadesPerfil = []

            diasSemana = {
                'Sunday': 1,
                'Monday': 2,
                'Tuesday': 3,
                'Wednesday': 4,
                'Thursday': 5,
                'Friday': 6,
                'Saturday': 7
            }
            diaSemana = diasSemana.get(date.today().strftime("%A"))
            hora = 0
            horas = []

            while hora <= 23:

                horas.append(str(hora) + 'h')

                if hora < 10:
                    horaInicio = "0{}:00:00".format(str(hora))
                    horaFin = "0{}:59:59".format(str(hora))

                else:
                    horaInicio = "{}:00:00".format(str(hora))
                    horaFin = "{}:59:59".format(str(hora))

                queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \
                                       "SELECT * FROM v1.contextualizaciones " \
                                       "WHERE dia = {1} and " \
                                       "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \
                                       "(hora_hecho between '{2}' and '{3}')) t" \
                                       .format(year, diaSemana, horaInicio, horaFin)


                queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE dia = {1} and " \
                                          "barrioid = {4} and " \
                                          "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \
                                          "(hora_hecho between '{2}' and '{3}')) t" \
                                          .format(year, diaSemana, horaInicio, horaFin, barrioUbicacion)

                queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE dia = {1} and " \
                                          "barrioid = {4} and " \
                                          "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \
                                          "(hora_hecho between '{2}' and '{3}')) t" \
                                          .format(year, diaSemana, horaInicio, horaFin, barrioSeleccion)

                if 'user' in locals():
                    queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \
                                           "SELECT * FROM v1.contextualizaciones " \
                                           "WHERE dia = {1} " \
                                           "and barrioid = {4}" \
                                           "and generoid = '{5}' " \
                                           "and nivelid = '{6}' " \
                                           "and edad = {7} " \
                                           "and (fecha_hecho between '{0}-01-01' and '{0}-12-31') " \
                                           "and (hora_hecho between '{2}' and '{3}')) t" \
                                           .format(year, diaSemana, horaInicio, horaFin, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario)

                with connection.cursor() as cursor:

                    # Indicador Ciudad
                    cursor.execute(queryIndicadorCiudad)
                    indicadorCiudad = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesCiudad.append(indicadorCiudad)

                    # Indicador Ubicación
                    cursor.execute(queryIndicadorUbicacion)
                    indicadorUbicacion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesUbicacion.append(indicadorUbicacion)

                    # Indicador Selección
                    cursor.execute(queryIndicadorSeleccion)
                    indicadorSeleccion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesSeleccion.append(indicadorSeleccion)

                    if 'user' in locals():
                        # Indicador Perfil
                        cursor.execute(queryIndicadorPerfil)
                        indicadorPerfil = verificacionExistenciaConflictividades(
                            dictfetchall(cursor)[0]['count'])

                        conflictividadesPerfil.append(indicadorPerfil)

                hora += 1

            data = {
                'labels':
                horas,
                'datasets': [{
                    'label': 'ciudad',
                    'fill': False,
                    'borderColor': 'orange',
                    'data': conflictividadesCiudad
                }, {
                    'label': 'Ubicación',
                    'fill': False,
                    'borderColor': 'blue',
                    'data': conflictividadesUbicacion
                }, {
                    'label': 'Selección',
                    'fill': False,
                    'borderColor': 'green',
                    'data': conflictividadesSeleccion
                }]
            }

            if 'user' in locals():
                data['datasets'].append({
                    'label': 'Perfil',
                    'fill': False,
                    'borderColor': 'red',
                    'data': conflictividadesPerfil
                })

            response = {'code': 200, 'data': data, 'status': 'success'}

        else:
            response = {'code': 400, 'status': 'error'}

    except (IndexError):

        response = {'code': 400, 'status': 'error'}

    except TokenBackendError as e:

        response = {'code': 400, 'message': str(e), 'status': 'error'}

    return JsonResponse(response, safe=False, status=response['code'])
示例#27
0
def semanal(request):

    try:

        barrioUbicacion = request.GET.get('barrioUbicacion')
        barrioSeleccion = request.GET.get('barrioSeleccion')
        year = request.GET.get('year')

        if request.META['HTTP_AUTHORIZATION'] != 'null':
            # Decodificando el access token
            tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                        settings.SIMPLE_JWT['SIGNING_KEY'],
                                        settings.SIMPLE_JWT['VERIFYING_KEY'])
            tokenDecoded = tokenBackend.decode(
                request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

            # consultando el usuario
            user = Usuario.objects.get(pk=tokenDecoded['user_id'])
            edadUsuario = calculoEdad(user.fecha_nacimiento)

        if barrioUbicacion is not None and barrioSeleccion is not None and year is not None:

            semana = [{
                'label': 'Domingo',
                'value': 1
            }, {
                'label': 'Lunes',
                'value': 2
            }, {
                'label': 'Martes',
                'value': 3
            }, {
                'label': 'Miercoles',
                'value': 4
            }, {
                'label': 'Jueves',
                'value': 5
            }, {
                'label': 'Viernes',
                'value': 6
            }, {
                'label': 'Sabado',
                'value': 7
            }]

            conflictividadesCiudad = []
            conflictividadesUbicacion = []
            conflictividadesSeleccion = []
            conflictividadesPerfil = []

            for sem in semana:

                queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \
                                       "SELECT * FROM v1.contextualizaciones " \
                                       "WHERE dia = {1} and " \
                                       "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                       .format(year, sem['value'])

                queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE dia = {1} and " \
                                          "barrioid = {2} and " \
                                          "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                          .format(year, sem['value'], barrioUbicacion)

                queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE dia = {1} and " \
                                          "barrioid = {2} and " \
                                          "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                          .format(year, sem['value'], barrioSeleccion)

                if 'user' in locals():
                    queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \
                                           "SELECT * FROM v1.contextualizaciones " \
                                           "WHERE dia = {1} " \
                                           "and barrioid = {2}" \
                                           "and generoid = '{3}' " \
                                           "and nivelid = '{4}' " \
                                           "and edad = {5} " \
                                           "and (fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \
                                           .format(year, sem['value'], user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario)

                with connection.cursor() as cursor:

                    #Indicador Ciudad
                    cursor.execute(queryIndicadorCiudad)
                    indicadorCiudad = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesCiudad.append(indicadorCiudad)

                    #Indicador Ubicación
                    cursor.execute(queryIndicadorUbicacion)
                    indicadorUbicacion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesUbicacion.append(indicadorUbicacion)

                    #Indicador Selección
                    cursor.execute(queryIndicadorSeleccion)
                    indicadorSeleccion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesSeleccion.append(indicadorSeleccion)

                    if 'user' in locals():
                        #Indicador Perfil
                        cursor.execute(queryIndicadorPerfil)
                        indicadorPerfil = verificacionExistenciaConflictividades(
                            dictfetchall(cursor)[0]['count'])

                        conflictividadesPerfil.append(indicadorPerfil)

            data = {
                'labels': [d['label'] for d in semana],
                'datasets': [{
                    'label': 'ciudad',
                    'fill': False,
                    'borderColor': 'orange',
                    'data': conflictividadesCiudad
                }, {
                    'label': 'Ubicación',
                    'fill': False,
                    'borderColor': 'blue',
                    'data': conflictividadesUbicacion
                }, {
                    'indicador': 'Selección',
                    'fill': False,
                    'borderColor': 'green',
                    'data': conflictividadesSeleccion
                }]
            }

            if 'user' in locals():
                data['datasets'].append({
                    'label': 'Perfil',
                    'fill': False,
                    'borderColor': 'red',
                    'data': conflictividadesPerfil
                })

            response = {'code': 200, 'data': data, 'status': 'success'}

        else:
            response = {'code': 400, 'status': 'error'}

    except (IndexError):

        response = {'code': 400, 'status': 'error'}

    except TokenBackendError as e:

        response = {'code': 400, 'message': str(e), 'status': 'error'}

    return JsonResponse(response, safe=False, status=response['code'])
示例#28
0
def mensual(request):

    try:

        barrioUbicacion = request.GET.get('barrioUbicacion')
        barrioSeleccion = request.GET.get('barrioSeleccion')
        year = request.GET.get('year')

        if request.META['HTTP_AUTHORIZATION'] != 'null':

            # Decodificando el access token
            tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'],
                                        settings.SIMPLE_JWT['SIGNING_KEY'],
                                        settings.SIMPLE_JWT['VERIFYING_KEY'])
            tokenDecoded = tokenBackend.decode(
                request.META['HTTP_AUTHORIZATION'].split()[1], verify=True)

            # consultando el usuario
            user = Usuario.objects.get(pk=tokenDecoded['user_id'])
            edadUsuario = calculoEdad(user.fecha_nacimiento)

        if barrioUbicacion is not None and barrioSeleccion is not None and year is not None:

            meses = [{
                'label': 'Enero',
                'value': '01',
                'lastDay': '31'
            }, {
                'label': 'Febrero',
                'value': '02',
                'lastDay': bisiesto(int(year), anio=False, mes=True)
            }, {
                'label': 'Marzo',
                'value': '03',
                'lastDay': '31'
            }, {
                'label': 'Abril',
                'value': '04',
                'lastDay': '30'
            }, {
                'label': 'Mayo',
                'value': '05',
                'lastDay': '31'
            }, {
                'label': 'Junio',
                'value': '06',
                'lastDay': '30'
            }, {
                'label': 'Julio',
                'value': '07',
                'lastDay': '31'
            }, {
                'label': 'Agosto',
                'value': '08',
                'lastDay': '31'
            }, {
                'label': 'Septiembre',
                'value': '09',
                'lastDay': '30'
            }, {
                'label': 'Octubre',
                'value': '10',
                'lastDay': '31'
            }, {
                'label': 'Noviembre',
                'value': '11',
                'lastDay': '30'
            }, {
                'label': 'Diciembre',
                'value': '12',
                'lastDay': '31'
            }]

            conflictividadesCiudad = []
            conflictividadesUbicacion = []
            conflictividadesSeleccion = []
            conflictividadesPerfil = []

            for mes in meses:

                queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \
                                       "SELECT * FROM v1.contextualizaciones " \
                                       "WHERE fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}') t" \
                                        .format(year, mes['value'], mes['lastDay'])

                queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE barrioid = {3} and " \
                                          "(fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \
                                          .format(year, mes['value'], mes['lastDay'], barrioUbicacion)

                queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \
                                          "SELECT * FROM v1.contextualizaciones " \
                                          "WHERE barrioid = {3} and " \
                                          "(fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \
                                          .format(year, mes['value'], mes['lastDay'], barrioSeleccion)

                if 'user' in locals():

                    queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \
                                           "SELECT * FROM v1.contextualizaciones " \
                                           "WHERE barrioid = {3} " \
                                           "and generoid = '{4}' " \
                                           "and nivelid = '{5}' " \
                                           "and edad = {6} " \
                                           "and (fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \
                                           .format(year, mes['value'], mes['lastDay'], user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario)

                with connection.cursor() as cursor:

                    #Indicador Ciudad
                    cursor.execute(queryIndicadorCiudad)
                    indicadorCiudad = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesCiudad.append(indicadorCiudad)

                    #Indicador Ubicación
                    cursor.execute(queryIndicadorUbicacion)
                    indicadorUbicacion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesUbicacion.append(indicadorUbicacion)

                    #Indicador Selección
                    cursor.execute(queryIndicadorSeleccion)
                    indicadorSeleccion = verificacionExistenciaConflictividades(
                        dictfetchall(cursor)[0]['count'])

                    conflictividadesSeleccion.append(indicadorSeleccion)

                    if 'user' in locals():
                        #Indicador Perfil
                        cursor.execute(queryIndicadorPerfil)
                        indicadorPerfil = verificacionExistenciaConflictividades(
                            dictfetchall(cursor)[0]['count'])

                        conflictividadesPerfil.append(indicadorPerfil)

            data = {
                'labels': [m['label'] for m in meses],
                'datasets': [{
                    'label': 'ciudad',
                    'fill': False,
                    'borderColor': 'orange',
                    'data': conflictividadesCiudad
                }, {
                    'label': 'Ubicación',
                    'fill': False,
                    'borderColor': 'blue',
                    'data': conflictividadesUbicacion
                }, {
                    'label': 'Selección',
                    'fill': False,
                    'borderColor': 'green',
                    'data': conflictividadesSeleccion
                }]
            }

            if 'user' in locals():

                data['datasets'].append({
                    'label': 'Perfil',
                    'fill': False,
                    'borderColor': 'red',
                    'data': conflictividadesPerfil
                })

            response = {'code': 200, 'data': data, 'status': 'success'}

        else:
            response = {'code': 400, 'status': 'error'}

    except (IndexError):

        response = {'code': 400, 'status': 'error'}

    except TokenBackendError as e:

        response = {'code': 400, 'message': str(e), 'status': 'error'}

    return JsonResponse(response, safe=False, status=response['code'])
示例#29
0
from django.shortcuts import render
from django.contrib.auth.models import User

from card.models import Pokemon
from card.serializers import PokemonSerializer
from rest_framework import generics, authentication, permissions

from rest_framework_simplejwt.backends import TokenBackend

tb = TokenBackend('HS256')


class PokemonList(generics.ListAPIView):
    serializer_class = PokemonSerializer
    authentication_classes = []  # [myAuth]
    permission_classes = [permissions.AllowAny]

    def get_queryset(self):
        username = self.request.COOKIES.get('username')
        print(username)
        print(self.request.COOKIES)
        user = User.objects.get(username=username)

        return Pokemon.objects.filter(user=user)


class PokemonCreate(generics.CreateAPIView):
    serializer_class = PokemonSerializer
    authentication_classes = []  # Remove parent auth
    permission_classes = [permissions.AllowAny
                          ]  # because I dont have enough time
 def setUp(self):
     self.hmac_token_backend = TokenBackend('HS256', SECRET)
     self.rsa_token_backend = TokenBackend('RS256', PRIVATE_KEY, PUBLIC_KEY)
     self.payload = {'foo': 'bar'}