예제 #1
0
    def store_votes(self, v):
        voters = list(Census.objects.filter(voting_id=v.id))
        voter = voters.pop()

        clear = {}

        data = {'voting': v.id, 'voter': voter.voter_id, 'votes': []}
        for pty in v.parties.all():
            for p in pty.president_candidates.all():
                clear[p.number] = 0
                # for i in range(random.randint(0, 5)):
                for i in range(1):
                    a, b = self.encrypt_msg(p.number, v)
                    data['votes'].append({'a': a, 'b': b})
                    clear[p.number] += 1
            for c in pty.congress_candidates.all():
                clear[c.number] = 0
                # for i in range(random.randint(0, 5)):
                for i in range(1):
                    a, b = self.encrypt_msg(c.number, v)
                    data['votes'].append({'a': a, 'b': b})
                    clear[c.number] += 1
            user = self.get_or_create_user(voter.voter_id)
            self.login(user=user.username)
            voter = voters.pop()
            mods.post('store', json=data)

        return clear
예제 #2
0
파일: tests.py 프로젝트: edubotdom/decide
    def test_create_voting_from_api(self):
        data = {'name': 'Example'}
        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 401)

        # login with user no admin
        self.login(user='******')
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 403)

        # login with user admin
        self.login()
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 400)

        data = {
            'name': 'Example',
            'desc': 'Description example',
            'question': 'I want a ',
            'question_opt': ['cat', 'dog', 'horse'],
            'question_ord': []
        }

        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 201)
예제 #3
0
    def test_create_voting_prefer_from_api(self):
        data = {'name': 'Example'}
        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 401)

        # login with user no admin
        self.login(user='******')
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 403)

        # login with user admin
        self.login()
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 400)

        data = {
            'name': 'Example',
            'desc': 'Description example',
            'question': 'I want a ',
            'escanios': 20,
            'question_opt': [],
            'question_pref': ['CAT', 'DOG', 'HORSE']
        }

        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 201)
예제 #4
0
    def test_create_voting_from_api(self):
        data = {'name': 'Example'}
        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 401)

        # login with user no admin
        self.login(user='******')
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 403)

        # login with user admin
        self.login()
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 400)

        data = {
            'name': 'Example',
            'desc': 'Description example',
            'questions': ['I want a '],
            'question_opts': [['cat', 'dog', 'horse']],
            'postproc_type': PostProcType.IDENTITY,
        }

        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 201)
예제 #5
0
    def tally_votes(self, token=''):
        '''
        The tally is a shuffle and then a decrypt
        '''

        votes = self.get_votes(token)

        auth = self.auths.first()
        shuffle_url = "/shuffle/{}/".format(self.id)
        decrypt_url = "/decrypt/{}/".format(self.id)

        # first, we do the shuffle
        data = { "msgs": votes }
        response = mods.post('mixnet', entry_point=shuffle_url, baseurl=auth.url, json=data,
                response=True)
        if response.status_code != 200:
            # TODO: manage error
            pass

        # then, we can decrypt that
        data = {"msgs": response.json()}
        response = mods.post('mixnet', entry_point=decrypt_url, baseurl=auth.url, json=data,
                response=True)

        if response.status_code != 200:
            # TODO: manage error
            pass

        self.tally = response.json()
        self.save()

        self.do_postproc()
예제 #6
0
    def testVotingWithManyCandidateFromApi(self):
        data = {'name': 'Example'}
        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 401)

        # login with user no admin
        self.login(user='******')
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 403)

        # login with user admin
        self.login()
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 400)

        data = {
            'name':
            'Example',
            'desc':
            'Description example',
            'escanios':
            20,
            'question':
            'I want a ',
            'question_opt': ['cat', 'dog', 'horse'],
            'candidates': [{
                'name': 'pepe',
                'sex': 'H',
                'auto_community': 'H',
                'age': 21,
                'political_party': {
                    'abreviatura': 'PACMA',
                    'nombre': 'Partido Animalista'
                }
            }, {
                'name': 'pepe2',
                'sex': 'H',
                'auto_community': 'BA',
                'age': 21,
                'political_party': {
                    'abreviatura': 'VOX',
                    'nombre': 'VOX'
                }
            }, {
                'name': 'pepe3',
                'sex': 'M',
                'auto_community': 'AN',
                'age': 30,
                'political_party': {
                    'abreviatura': 'UP',
                    'nombre': 'Unidas Podemos'
                }
            }]
        }

        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 201)
예제 #7
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        token = self.request.session.get('user_token')
        if token:
            mods.post('authentication',
                      entry_point='/logout/',
                      json={'token': token})
            del self.request.session['user_token']
            del self.request.session['voter_id']
            del self.request.session['username']

        return context
예제 #8
0
 def test_create_voting_from_api(self):
     data = {'name': 'Example'}
     response = self.client.post('/voting/', data, format='json')
     self.assertEqual(response.status_code, 401)
     # login with user no admin
     self.login(user='******')
     response = mods.post('voting', params=data, response=True)
     self.assertEqual(response.status_code, 403)
     # login with user admin
     self.login()
     response = mods.post('voting', params=data, response=True)
     self.assertEqual(response.status_code, 400)
예제 #9
0
    def tally_votes_masc(self, token=''):
        '''
        The tally is a shuffle and then a decrypt
        '''
        votos = self.get_votes_masc(token)

        votes = []
        for i in votos:
            if i['sex'] == 'M':
                aa = i['a'].split(',')
                bb = i['b'].split(',')
                for j in range(len(aa)):
                    #[[int(i['a']), int(i['b'])] for i in votes if i['sex']=='F']
                    votes.append([int(aa[j]), int(bb[j]), j, i['question_id']])

        auth = self.auths.first()
        shuffle_url = "/shuffle/{}/".format(self.id)
        decrypt_url = "/decrypt/{}/".format(self.id)
        auths = [{"name": a.name, "url": a.url} for a in self.auths.all()]

        # first, we do the shuffle
        data = {"msgs": votes}
        response = mods.post('mixnet',
                             entry_point=shuffle_url,
                             baseurl=auth.url,
                             json=data,
                             response=True)
        if response.status_code != 200:
            # TODO: manage error
            pass

        # then, we can decrypt that
        data = {"msgs": response.json()}
        response = mods.post('mixnet',
                             entry_point=decrypt_url,
                             baseurl=auth.url,
                             json=data,
                             response=True)

        if response.status_code != 200:
            # TODO: manage error
            pass

        self.tallyM = response.json()
        self.save()

        tallyM = self.tallyM

        self.tally_votes_fem(token)
        return tallyM
예제 #10
0
def logout(request):
    response = redirect('index')
    response.delete_cookie('decide')

    token = request.session.get('user_token')

    if token:
        mods.post('authentication', entry_point='/logout/', json={'token': token})

        del request.session['user_token']
        del request.session['voter_id']
        del request.session['username']
        request.session.modified = True

    return response
예제 #11
0
 def has_permission(self, request, view):
     if not request.auth:
         return False
     response = mods.post(
         'authentication/getuser', json={'token': request.auth.key},
             response=True)
     return response.json().get('is_staff', False)
예제 #12
0
def autenticacion(request, username, password):
    token = mods.post('authentication',
                      entry_point='/login/',
                      json={
                          'username': username,
                          'password': password
                      })
    request.session['user_token'] = token
    voter = mods.post('authentication', entry_point='/getuser/', json=token)
    voter_id = voter.get('id', None)
    request.session['voter_id'] = voter_id

    if voter_id == None:
        return False, voter_id

    return True, voter_id
예제 #13
0
    def do_postproc(self):
        tally = self.tally
        options = self.question.options.all()

        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes
            })
        msn = "Votación: " + self.name + "\n\n"
        for opt in opts:
            msn = str(msn) + str(opt.get('option')) + ": " + (str(
                opt.get('votes'))) + " votos.\n"
        data = {'type': 'IDENTITY', 'options': opts}
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()
        self.enviarTelegram(msn)
예제 #14
0
    def do_postproc(self):
        tally = self.tally
        options = self.question.options.all()
        dhont = self.dhont
        numero_dhont = self.numero_dhont

        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes
            })

        data = {
            'type': 'IDENTITY',
            'options': opts,
            'dhont': dhont,
            'numero_dhont': numero_dhont
        }
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()
예제 #15
0
    def post(self, request):
        # validating token
        token = request.auth.key
        user = mods.post('authentication',
                         entry_point='/getuser/',
                         json={'token': token})
        user_id = user.get('id', None)

        if not user_id:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        my_votings = Census.objects.filter(voter_id=user_id).values_list(
            'voting_id', flat=True).distinct()
        pending_votings = []
        past_votings = []
        for vid in my_votings:
            try:
                voting = Voting.objects.get(id=vid)
                votes = Vote.objects.filter(voter_id=user_id,
                                            voting_id=vid).count()

                if votes == 0 and voting.start_date != None and voting.end_date == None:
                    pending_votings.append(voting)
                elif voting.tally != None:
                    past_votings.append(voting)
            except:
                pass

        return Response({
            'pending_votings':
            MinimalVotingSerializer(pending_votings, many=True).data,
            'past_votings':
            MinimalVotingSerializer(past_votings, many=True).data
        })
    def do_postproc(self):
        tally = self.tally
        options = self.question.options.all()

        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes,
            })

        data = {
            'type': self.tipo,
            'options': opts,
            'numEscanos': self.numEscanos
        }
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()
예제 #17
0
    def do_postproc(self):
        tally = self.tally
        for q in self.questions.all():
            options = q.options.all()

            opts = []
            for opt in options:
                if isinstance(tally, list):
                    votes = tally.count(opt.number)
                else:
                    votes = 0
                opts.append({
                    'option': opt.option,
                    'number': opt.number,
                    'votes': votes
                })

            # we have two types of tally the wheighted one or the traditional
            if not self.isWeighted:
                data = {'type': 'IDENTITY', 'options': opts}
            else:
                data = {'type': 'WEIGHT', 'options': opts}

            postp = mods.post('postproc', json=data)

            self.postproc = postp
            self.save()
예제 #18
0
 def login(self, user='******', password='******'):
     data = {'username': user, 'password': password}
     response = mods.post('authentication/login', json=data, response=True)
     self.assertEqual(response.status_code, 200)
     self.token = response.json().get('token')
     self.assertTrue(self.token)
     self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
예제 #19
0
    def do_postproc(self):
        tally = self.tally
        options = self.question.options.all()
        escanios = self.escanios
        postproc_mode = self.postproc_mode
        print(options)
        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes
            })

        if postproc_mode == 'IDENTITY':
            data = { 'type': postproc_mode, 'options': opts}
        else :
            data = { 'type': postproc_mode, 'options': opts,'escanio':escanios}
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()
예제 #20
0
    def do_postproc(self, census):
        tally = self.tally
        options = []
        for q in self.question.all():
            options.extend(q.options.all())

        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes
            })

        data = {'type': self.tally_type, 'options': opts, 'census': census}
        print(data)
        directory = "voting/tallies/"
        if not os.path.exists(directory):
            os.makedirs(directory)
        file_name = 'tally_voting'+str(self.id)
        with open(directory+file_name+'.json', 'w') as outfile:
            json.dump(data, outfile)

        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()

        return directory+file_name+'.json'
예제 #21
0
    def do_postproc(self):
        tally = self.tally
        questions = self.questions.all()

        qsts = []
        for qst in questions:
            opts = []
            for opt in qst.options.all():
                if isinstance(tally, list):
                    votes = tally.count(opt.number)
                else:
                    votes = 0
                opts.append({
                    'option': opt.option,
                    'number': opt.number,
                    'votes': votes,
                    'gender': opt.gender,
                    'team': opt.team,
                    'weight': opt.weight,
                })
            qsts.append({'number': qst.number, 'options': opts, 'seats': qst.seats})

        data = { 'type': self.postproc_type, 'questions': qsts }
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()
예제 #22
0
 def store_votes(self, v):
     voters = list(Census.objects.filter(voting_id=v.id))
     voter = voters.pop()
     clear = {}
     for opt in v.question.options.all():
         clear[opt.number] = 0
         for i in range(random.randint(0, 5)):
             a, b = self.encrypt_msg(opt.number, v)
             data = {
                 'voting': v.id,
                 'voter': voter.voter_id,
                 'vote': { 'a': a, 'b': b },
             }
             clear[opt.number] += 1
             voter = voters.pop()
             mods.post('store', json=data)
     return clear
예제 #23
0
    def store_votes(self, v, q1, q2):
        voters = list(Census.objects.filter(voting_id=v.id))
        voter = voters.pop()

        clear1 = {}
        clear2 = {}

        options1 = QuestionOption.objects.filter(question=q1)
        for opt in options1:
            clear1[opt.number] = 0
            for i in range(random.randint(0, 5)):
                a, b = self.encrypt_msg(opt.number, v)
                data = {
                    'voting': v.id,
                    'voter': voter.voter_id,
                    'votes': [{
                        "a": a,
                        "b": b
                    }],
                }
                clear1[opt.number] += 1
                user = self.get_or_create_user(voter.voter_id)
                self.login(user=user.email)
                voter = voters.pop()
                mods.post('store', json=data)

        options2 = QuestionOption.objects.filter(question=q2)
        for opt in options2:
            clear2[opt.number] = 0
            for i in range(random.randint(0, 5)):
                a, b = self.encrypt_msg(opt.number, v)
                data = {
                    'voting': v.id,
                    'voter': voter.voter_id,
                    'votes': [{
                        "a": a,
                        "b": b
                    }],
                }
                clear2[opt.number] += 1
                user = self.get_or_create_user(voter.voter_id)
                self.login(user=user.email)
                voter = voters.pop()
                mods.post('store', json=data)

        return clear1, clear2, options1, options2
예제 #24
0
    def tally_votes(self, token=''):
        '''
        The tally is a shuffle and then a decrypt
        '''

        votes = self.get_votes(token)

        auth = self.auths.first()
        shuffle_url = "/shuffle/{}/".format(self.id)
        decrypt_url = "/decrypt/{}/".format(self.id)
        auths = [{"name": a.name, "url": a.url} for a in self.auths.all()]

        # first, we do the shuffle
        data = {"msgs": votes}

        response = mods.post('mixnet',
                             entry_point=shuffle_url,
                             baseurl=auth.url,
                             json=data,
                             response=True)

        if response.status_code != 200 and len(votes) > 0:

            # TODO: manage error necesitamos unir las api, para ver que se haga bien cuando no hay votaciones
            error_response = "error: Shuffle fails"
            return error_response
            pass

        # then, we can decrypt that
        data = {"msgs": response.json()}
        response = mods.post('mixnet',
                             entry_point=decrypt_url,
                             baseurl=auth.url,
                             json=data,
                             response=True)

        if response.status_code != 200 and len(votes) > 0:
            # TODO: manage error, necesitamos unir las api, para ver que se haga bien cuando no hay votaciones
            error_response = "error: Decrypt fails"
            return error_response
            pass

        self.tally = response.json()
        self.save()
        self.do_postproc()
        return 'Voting tallied'
예제 #25
0
파일: views.py 프로젝트: jualinfer/locaste
    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({})
예제 #26
0
    def post(self, request):
        # Extracts data from form
        form = LoginForm(request.POST)
        data = {
            "username": form.data["username"],
            "password": form.data["password"],
        }

        # Logs in
        token = mods.post('authentication/login',
                          baseurl=settings.APIS.get('authentication',
                                                    settings.BASEURL),
                          json=data)

        # Tries to get user data
        try:
            user = mods.post('authentication/getuser',
                             baseurl=settings.APIS.get('authentication',
                                                       settings.BASEURL),
                             json={"token": token["token"]})
            # If it's not an admin
            if (not user["is_staff"]):
                return render(
                    request, 'populate_login.html', {
                        'form': form,
                        "error": "Only administrator can populate the database"
                    })
            # If it's an admin
            else:
                return render(request, "mixnet_populate.html",
                              self.get_context_data())
        except KeyError as k:
            # If incorrect user/pass
            return render(request, 'populate_login.html', {
                'form': form,
                "error": "Incorrect username or password"
            })
        except Exception as e:
            # If unknown error
            print(e)
            return HttpResponse("Unexpected server error")
        return HttpResponse("Unexpected server error")
예제 #27
0
    def tally_votes(self, token=''):
        '''
        The tally is a shuffle and then a decrypt
        '''

        votes = self.get_votes(token)

        auth = self.auths.first()
        shuffle_url = "/shuffle/{}/".format(self.id)
        decrypt_url = "/decrypt/{}/".format(self.id)
        auths = [{"name": a.name, "url": a.url} for a in self.auths.all()]

        # first, we do the shuffle
        data = { "msgs": votes }
        response = mods.post('mixnet', entry_point=shuffle_url, baseurl=auth.url, json=data,
                response=True)
        if response.status_code != 200:
            # TODO: manage error
            pass

        # then, we can decrypt that
        data = {"msgs": response.json()}
        response = mods.post('mixnet', entry_point=decrypt_url, baseurl=auth.url, json=data,
                response=True)

        if response.status_code != 200:
            # TODO: manage error
            pass

        self.tally = response.json()
        self.save()
        #Aqui hacemos el guardado del Tally
        _datetime = datetime.now()
        datetime_str = _datetime.strftime("%Y-%m-%d-%H")
        with open ('archivosGuardados/tally','w') as f:
             for tallys in json.dumps(self.tally):
                 json.dump(tallys,f)
        self.do_postproc()
        #Aqui comprimo
        with zipfile.ZipFile('archivosGuardados/'+datetime_str+'.zip', 'w') as zf:
            zf.write('archivosGuardados/tally')
            zf.write('archivosGuardados/postproc')
예제 #28
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)
예제 #29
0
    def testVotingCandidateFromApi(self):
        data = {'name': 'Example'}
        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 401)

        # login with user no admin
        self.login(user='******')
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 403)

        # login with user admin
        self.login()
        response = mods.post('voting', params=data, response=True)
        self.assertEqual(response.status_code, 400)

        data = {
            'name': 'Example',
            'desc': 'Description example',
            'escanios': 20,
            'question': 'I want a ',
            'question_opt': ['cat', 'dog', 'horse'],
            'candidates': {
                'name': 'pepe',
                'sex': 'H',
                'auto_community': 'H',
                'age': 21,
                'political_party': {
                    'abreviatura': 'PC',
                    'nombre': 'Partido Cuestista',
                    'program': {
                        'title': 'programa de PC',
                        'overview': 'el programa politico del PC',
                        'plank': ['promesa1', 'promesa2', 'promesa3'],
                    }
                }
            }
        }

        response = self.client.post('/voting/', data, format='json')
        self.assertEqual(response.status_code, 201)
예제 #30
0
def login(request):
    response = redirect('index')
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        
        token = mods.post('authentication', entry_point='/login/',json={'username': username, 'password': password})
        user = mods.post('authentication', entry_point='/getuser/', json=token)

        user_id = user.get('id', None)
        if user_id == None:
            response['Location'] += '?failedlogin'
            return response

        request.session['user_token'] = token
        request.session['voter_id'] = user_id
        request.session['username'] = user.get('username', '')
        request.session.modified = True
        
        response.set_cookie('decide', token.get('token', ''), path='/', max_age=1800)

    return response