Exemple #1
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)
        custom_url = ''
        if 'custom_url' in kwargs:
            custom_url = kwargs.get('custom_url', 1)

        try:
            r = mods.get('voting', params={'id': vid})
            if r[0]['custom_url'] != '' and custom_url != '':
                r = mods.get('voting',
                             params={
                                 'id': vid,
                                 'custom_url': custom_url
                             })
                if r[0]['custom_url'] != custom_url:
                    raise Http404
            elif (r[0]['custom_url'] == ''
                  and custom_url != '') or (r[0]['custom_url'] != ''
                                            and custom_url == ''):
                raise Http404
            context['voting'] = r[0]
        except:
            raise Http404

        return context
Exemple #2
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)
        custom_url = ''
        if 'custom_url' in kwargs:
            custom_url = kwargs.get('custom_url', 1)

        try:
            r = mods.get('voting', params={'id': vid})
            if r[0]['custom_url'] != '' and custom_url != '':
                r = mods.get('voting',
                             params={
                                 'id': vid,
                                 'custom_url': custom_url
                             })
                if r[0]['custom_url'] != custom_url:
                    raise Http404
            elif (r[0]['custom_url'] == ''
                  and custom_url != '') or (r[0]['custom_url'] != ''
                                            and custom_url == ''):
                raise Http404
            context['voting'] = r[0]
        except:
            raise Http404

        context['store_url'] = settings.APIS.get('store', settings.BASEURL)
        context['auth_url'] = settings.APIS.get('authentication',
                                                settings.BASEURL)
        context['KEYBITS'] = settings.KEYBITS

        return context
Exemple #3
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)
        custom_url = ''
        url_not_found = ''

        if 'custom_url' in kwargs:
            custom_url = kwargs.get('custom_url', 1)

        try:
            r = mods.get('voting', params={'id': vid})
            if r[0]['custom_url'] != '' and custom_url != '':
                r = mods.get('voting',
                             params={
                                 'id': vid,
                                 'custom_url': custom_url
                             })
                if r[0]['custom_url'] != custom_url:
                    url_not_found = 'true'
            elif (r[0]['custom_url'] == ''
                  and custom_url != '') or (r[0]['custom_url'] != ''
                                            and custom_url == ''):
                url_not_found = 'true'
            context['voting'] = r[0]
            context['url_not_found'] = url_not_found
        except:
            url_not_found = 'true'
            context['url_not_found'] = url_not_found

        return context
Exemple #4
0
    def post(self, request):
        """
         * voting: id
         * voter: id
         * vote: { "a": int, "b": int }
        """

        vid = request.data.get('voting')
        voting = mods.get('voting', params={'id': vid})
        if not voting or not isinstance(voting, list):
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)
        start_date = voting[0].get('start_date', None)
        end_date = voting[0].get('end_date', None)
        not_started = not start_date or timezone.now() < parse_datetime(
            start_date)
        is_closed = end_date and parse_datetime(end_date) < timezone.now()
        if not_started or is_closed:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        uid = request.data.get('voter')
        vote = request.data.get('vote')
        if not vid or not uid or not vote:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
        # validating voter
        token = None
        if request.auth:
            token = request.auth.key
        voter = mods.post('authentication',
                          entry_point='/getuser/',
                          json={'token': token})
        voter_id = voter.get('id', None)
        if voter_id == None:
            voter = request.user
            voter_id = voter.id
        if not voter_id or voter_id != uid:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        # the user is in the census
        perms = mods.get('census/{}'.format(vid),
                         params={'voter_id': uid},
                         response=True)
        if perms.status_code == 401:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        a = vote.get("a")
        b = vote.get("b")

        defs = {"a": a, "b": b}
        v, _ = Vote.objects.get_or_create(voting_id=vid,
                                          voter_id=uid,
                                          defaults=defs)
        v.a = a
        v.b = b

        v.save()

        return Response({})
    def post(self, request):

        vid = request.data.get('voting')
        voting = mods.get('voting', params={'id': vid})
        if not voting or not isinstance(voting, list):
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)
        start_date = voting[0].get('start_date', None)
        end_date = voting[0].get('end_date', None)
        not_started = not start_date or timezone.now() < parse_datetime(
            start_date)
        is_closed = end_date and parse_datetime(end_date) < timezone.now()
        if not_started or is_closed:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        uid = request.data.get('voter')
        vote = request.data.get('vote')
        if not vid or not uid or not vote:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

        # validating voter
        token = request.data.get('token')
        voter = mods.post('authentication',
                          entry_point='/getuser/',
                          json={'token': token})
        voter_id = voter.get('id', None)
        if not voter_id or voter_id != uid:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        # the user is in the census
        perms = mods.get('census/{}'.format(vid),
                         params={'voter_id': uid},
                         response=True)
        if perms.status_code == 401:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        #################################################################
        ########################## New encrypt ##########################
        #################################################################

        v = Vote.objects.filter(voting_id=vid, voter_id=uid)

        if len(v) == 0:
            v1 = Vote.objects.create(voting_id=vid, voter_id=uid, data=vote)
        else:
            v1 = v[0]
            v1.data = vote
        v1.save()

        return Response({})
Exemple #6
0
 def get_todos_votos(votings):
     listaVotos = []
     for voting in votings:
         votos = mods.get('store',params={'voting_id':voting.id})
         cuenta = [v['voting_id'] for v in votos]
         listaVotos.append(len(cuenta))
     return listaVotos
Exemple #7
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})

            # Casting numbers to string to manage in javascript with BigInt
            # and avoid problems with js and big number conversion
            for k, v in r[0]['pub_key'].items():
                r[0]['pub_key'][k] = str(v)

            context['voting'] = json.dumps(r[0])
        except:
            raise Http404

        context['KEYBITS'] = settings.KEYBITS

        #The voter json is supposed to come from the authentication module
        voter_json = '{"username": "******", "postal_code": "11368"}'
        voter = json.loads(voter_json)

        nomi = pgeocode.Nominatim('es')

        context['province'] = nomi.query_postal_code(
            voter['postal_code'])['county_name']

        return context
Exemple #8
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        voting_id = kwargs.get('voting_id', 0)
        context['voting_id'] = voting_id
        question_id = kwargs.get('question_id', 0)
        context['question_id'] = question_id

        context['token'], context['voter'], voter_id = get_user(self)
        context['KEYBITS'] = settings.KEYBITS

        try:
            r = mods.get('voting', params={'id': voting_id})
            # Casting numbers to string to manage in javascript with BigInt
            # and avoid problems with js and big number conversion
            for k, v in r[0]['pub_key'].items():
                r[0]['pub_key'][k] = str(v)

            number_of_questions = len(r[0]['question'])
            current_question_position = question_position_by_id(
                r[0]['question'], question_id)

            check_next_question(context, current_question_position,
                                number_of_questions, r)

            store_voting_and_question(context, current_question_position, r)

            check_user_has_voted_question(context, voting_id, question_id,
                                          voter_id)

        except:
            raise Http404("This voting does not exist")

        return context
Exemple #9
0
def view(request, voting_id):
    #Asignacion de votacion con id voting_id, tomado de la url
    voting = mods.get('voting', id=voting_id)

    #Renderizacion de la vista con template 'visualizer/visualizer.html
    #y variable voting
    return render(request, 'visualizer/visualizer.html', {'voting': voting[0]})
Exemple #10
0
 def get_votes_fem(self, token=''):
     # gettings votes from store
     votes = mods.get('store',
                      params={'voting_id': self.id},
                      HTTP_AUTHORIZATION='Token ' + token)
     # anon votes
     return votes
    def get_votes(self, token=''):
	# gettings votes from store
        votes = mods.get('store', params={'voting_id': self.id},
        HTTP_AUTHORIZATION='Token ' + token)

	# anon votes
        return [[i['a'], i['b']] for i in votes]
Exemple #12
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)
        admin_id = User.objects.filter(is_staff='t').first().id
        try:
            tk = Token.objects.filter(user_id=admin_id)[0].key
            r = mods.get('voting', params={'id': vid})
            c = mods.get('census',
                         params={'voting_id': vid},
                         HTTP_AUTHORIZATION='Token ' + tk)
            #Investigar otra forma de pasar Token
            context['voting'] = r[0]
            context['census'] = c
        except:
            raise Http404

        return context
Exemple #13
0
def get_numero_votos(vid):
    #census = mods.get('admin', entry_point= '/census/census', params={'voting_id': vid})
    #print('asd')
    numero_votos = 0
    voters = mods.get('store', params={'voting_id': vid})
    voters_id = [v['voting_id'] for v in voters]
    numero_votos = len(voters_id)

    return numero_votos
Exemple #14
0
 def post(self, request):
     vid = request.data.get('voting', '')
     try:
         r = mods.get('voting', params={'id': vid})
         for k, v in r[0]['pub_key'].items():
             r[0]['pub_key'][k] = str(v)
         return Response(r[0], status=HTTP_200_OK)
     except:
         return Response({}, status=HTTP_404_NOT_FOUND)
Exemple #15
0
 def get_votes(self, token=''):
     # gettings votes from store
     votes = mods.get('store', params={'voting_id': self.id}, HTTP_AUTHORIZATION='Token ' + token)
     # anon votes
     print(votes)
     res = []
     for vote in votes:
         for cipher in vote["ciphers"]:
             res.append([cipher["a"], cipher["b"]])
     return res
Exemple #16
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = r[0]
        except:
            raise Http404

        return context
Exemple #17
0
    def test_nuevo_usuario_fail_data(self):
        data = {'email': 'new2.mail.com', 'firs_name': 'new', 'last_name': 'new', 'birthday':'01/01/2000', 'password1': 'practica', 'password2': 'practica', 'city': 'Sevilla'}
        
        response = mods.get('authentication/signup', json=data, response=True) #getting the html
        self.assertEqual(response.status_code, 200)   #get html    
        response = mods.post('authentication/signup', json=data, response=True) 
        self.assertEqual(response.status_code, 200) 

        form = UserCreateForm(data)
        self.assertTrue(form)
        self.assertTrue(form.is_valid()==False)
Exemple #18
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)
        
        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = json.dumps(r[0])
            if r[0]['start_date'] is None:
                print('Votación no comenzada')
            elif r[0]['end_date'] is None:
                
                context['options'] = json.dumps(r[0]['question']['options']) # Datos para gráfica en tiempo real. (gabgutpri, visualización)
                opciones = r[0]['question']['options']
                numOp=[]
                
                for i in range(len(opciones)):
                    numOp.append(opciones[i]['number'])
                
                votos = mods.get('store',params={'voting_id':vid})
                print('buenas a todos')
                votosPorOpcion = []
                for op in numOp:
                    cuenta = 0
                    for v in votos:
                        if(op==v['b']):
                            cuenta = cuenta + 1
                    votosPorOpcion.append(cuenta)
                
                context['votosOpcion'] = votosPorOpcion                         # Fin de datos para gráfica

                
                numero_votos= len(votos)
                context['numero_votos'] = numero_votos
                
        except:
            raise Http404

        return context
    def test_nuevo_usuario_ok(self):
        os.environ['NORECAPTCHA_TESTING'] = 'True'

        data = {'email': '*****@*****.**', 'first_name': 'new', 'last_name': 'new', 'birthday':'01/01/2000', 'password1': 'practica', 'password2': 'practica', 'city': 'Sevilla', 'g-recaptcha-response': 'PASSED'}# this user must not exits in db
        response = mods.get('authentication/signup', json=data, response=True) #getting the html
        self.assertEqual(response.status_code, 200)  
        response = mods.post('authentication/signup', json=data, response=True) 
        self.assertEqual(response.status_code, 200)  
        
        form = UserCreateForm(data)
        self.assertTrue(form)
        self.assertTrue(form.is_valid())
        user1=form.save()
        self.assertTrue(user1.id>0)#user exits
Exemple #20
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = r[0]
        except:
            raise Http404

        context['store_url'] = settings.APIS.get('store', settings.BASEURL)
        context['auth_url'] = settings.APIS.get('authentication',
                                                settings.BASEURL)
        context['KEYBITS'] = settings.KEYBITS

        return context
Exemple #21
0
    def post(self, request):
        # Obtenemos el id del usuario que ha iniciado sesión
        idUser = request.user.id
        # Obtenemos del módulo Census los ids de las votaciones en las que se le permite votar al usuario
        votacionesCensus = Census.objects.filter(voter_id=idUser)
        idsVotaciones = []
        for v in votacionesCensus:
            idsVotaciones.append(v.voting_id)

        votaciones = []
        for idVoting in idsVotaciones:
            # Obtenemos cada votación gracias al id
            votacion = mods.get('voting', params={'id': idVoting})
            votaciones.append(votacion)

        # Mandamos las votaciones a nuestra página
        return Response(votaciones)
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            # Casting numbers to string to manage in javascript with BigInt
            # and avoid problems with js and big number conversion
            for k, v in r[0]['pub_key'].items():
                r[0]['pub_key'][k] = str(v)
            context['voting'] = json.dumps(r[0])
        except:
            raise Http404

        context['KEYBITS'] = settings.KEYBITS

        return context
Exemple #23
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = r[0]
            voters = Census.objects.filter(voting_id=vid).values_list(
                'voter_id', flat=True)
            voters_list = []
            for voter in voters:
                voters_list.append(User.objects.filter(id=voter)[0])
            context['voters'] = voters_list
        except Exception as e:
            print(e)
            raise Http404

        return context
Exemple #24
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        context_grafica_votos = VisualizerView.grafica_votos(self, vid)

        try:
            r = mods.get('voting', params={'id': vid})
            #context['voting'] = json.dumps(r[0])
            voting = r[0]
            #context principal
            context = {'voting': voting}
            #hacer un update del context con los contexts de las funciones de las graficas
            context.update(context_grafica_votos)

        except:
            raise Http404

        return context
    def get(self, request, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            voting = r[0]

            # Identificamos el estado de la votación
            if r[0]['start_date'] is None:

                return HttpResponseBadRequest()

            elif r[0]['end_date'] is None:

                # Votación en proceso
                voting_status = "ongoing"

                #Obtenemos las estadísticas de la votación
                stats = get_statistics(vid)
                stats['voting'] = voting

                return Render.render_xml(voting_status, stats)

            elif r[0]['start_date'] is not None and r[0][
                    'end_date'] is not None:

                # Impedir la obtención de resultados de votaciones que no han pasado
                # por tally

                if voting['postproc'] is None:
                    return HttpResponseBadRequest()

                #Votación terminada
                voting_status = 'ended'

                return Render.render_xml(voting_status, {'voting': voting})

        except Exception as e:
            print(str(e))
            raise Http404

        return context
    def test_nuevo_usuario_exits(self):
        data = {'email': '*****@*****.**', 'firs_name': 'new', 'last_name': 'new', 'birthday':'01/01/2000', 'password1': 'practica', 'password2': 'practica', 'city': 'Sevilla'}# this user is saved previously
        response = self.client.post('/authentication/login/', data, format='json') 
        self.assertTrue(response.status_code, 200) #exits
        response = mods.get('authentication/signup', json=data, response=True) #getting the html
        self.assertEqual(response.status_code, 200)   #get html    
        response = mods.post('authentication/signup', json=data, response=True) 
        self.assertEqual(response.status_code, 200) 

        form = UserCreateForm(data)
        self.assertTrue(form)
        self.assertTrue(form.is_valid()==False)

    


        
   
        
Exemple #27
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = json.dumps(r[0])
            if r[0]['start_date'] is None:
                print('asd')
            elif r[0]['end_date'] is None:
                #print('asd')
                numero_votos = get_numero_votos(vid)

                context['numero_votos'] = numero_votos
                print(context)
        except:
            raise Http404

        return context
Exemple #28
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        queryset = Voting.objects.all()
        def get_todos_votos(votings):
            listaVotos = []
            for voting in votings:
                votos = mods.get('store',params={'voting_id':voting.id})
                cuenta = [v['voting_id'] for v in votos]
                listaVotos.append(len(cuenta))
            return listaVotos

        # Parte de la gráfica --- gabgutpri (visualizacion)
        votaciones = mods.get('voting', params={}) # Todas las votaciones
        context['votaciones']= json.dumps(votaciones) # Transformación para que no de problemas en el script JS
        votos = get_todos_votos(queryset) # Traer todos los votos de cada votación
        context['votos'] = votos
        # ------------

        context.update({'votings': queryset})
        return context
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            context['voting'] = r[0]

            # Elegimos la plantilla a renderizar en base al estado
            # de la votación
            if r[0]['start_date'] is None:

                # Votación no comenzada
                self.template_name = "visualizer/not_started.html"

            elif r[0]['end_date'] is None:

                # Votación en proceso
                self.template_name = "visualizer/ongoing.html"

                stats = get_statistics(vid)

                #Añadimos las estadísticas al contexto
                for e, v in stats.items():
                    context['stats_' + str(e)] = v

            elif r[0]['postproc'] is None and r[0]['end_date'] is not None:

                #Recuento no realizado
                self.template_name = "visualizer/not_tally.html"

            else:

                #Votación terminada
                self.template_name = "visualizer/ended.html"

        except Exception as e:
            print(str(e))
            raise Http404

        return context
Exemple #30
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        vid = kwargs.get('voting_id', 0)

        try:
            r = mods.get('voting', params={'id': vid})
            voting = r[0]

            # Se verifica que el usuario es un superuser o pertenece al algún censo de la votación. 
            if self.request.user.is_superuser is False: 
                try:
                    census = Census.objects.filter(voting_id=vid, voter_id=self.request.user.id)
                
                except:
                    raise PermissionDenied

            # Solo se mostrarán las gráficas de aquellas votaciones finalizadas y postprocesadas.
            if voting['end_date'] != None and voting['postproc'][0] != None:
                postproc = voting['postproc'][0]

                if postproc['type'] == 'IDENTITY' or postproc['type'] == 'BORDA':
                    self.statistics_identity(context, voting)

                elif postproc['type'] == 'EQUALITY':
                    self.statistics_equality(context, voting)

                else:
                    self.statistics_points(context, voting)
            
                context['postproc_type'] = voting['postproc'][0]['type']

            context['voting'] = voting

        except PermissionDenied:
            raise HttpResponseForbidden

        except:
            raise Http404

        return context