Пример #1
0
def registerVote(plainText, username, password):
	"""Register plainText as the vote of user with given username and password"""
	if GlobalVariables.objects.filter(varname='electionState')[0].value != 'election':
		return False
	userlist = Users.objects.filter(username=username)
	#print len(userlist)
	if (len(userlist) == 0):
		return False
	assert(len(userlist) == 1)
	decryptedPrivateKey = cryptography.symmetricDecrypt(userlist[0].encryptedPrivateKey,password)

	certificate = cryptography.asymmetricSign(plainText,decryptedPrivateKey)
	key = RSA.importKey(decryptedPrivateKey)
	key = key.publickey().exportKey()
	assert(len(PublicKeys.objects.filter(publicKey=key)) == 1)
	publicKey = PublicKeys.objects.filter(publicKey=key)[0]

	challenobj = ChallengeStrings.objects.all()
	lenofcha = len(challenobj)
	rannum = lenofcha/2
	'''get a random number'''
	p1 = Votes(plainText=plainText, certificate=certificate, publicKey=publicKey, challengeStr = challenobj[rannum])
	p1.save()

	return True
Пример #2
0
def registerVote(plainText, username, password):
	"""Register plainText as the vote of user with given username and password"""
	if GlobalVariables.objects.filter(varname='electionState')[0].value != 'election':
		return False
	userlist = Users.objects.filter(username=username)
	#print len(userlist)
	if (len(userlist) == 0):
		return False
	assert(len(userlist) == 1)
	decryptedPrivateKey = cryptography.symmetricDecrypt(userlist[0].encryptedPrivateKey,password)

	certificate = cryptography.asymmetricSign(plainText,decryptedPrivateKey)
	key = RSA.importKey(decryptedPrivateKey)
	key = key.publickey().exportKey()
	assert(len(PublicKeys.objects.filter(publicKey=key)) == 1)
	publicKey = PublicKeys.objects.filter(publicKey=key)[0]

	challenobj = ChallengeStrings.objects.all()
	lenofcha = len(challenobj)
	rannum = lenofcha/2
	'''get a random number'''
	p1 = Votes(plainText=plainText, certificate=certificate, publicKey=publicKey, challengeStr = challenobj[rannum])
	p1.save()

	return True
Пример #3
0
async def get_ranks(after='1y', sort='top', limit=None):
    if sort == 'hot':
        after = '1y'
    epoch = get_epoch(after)
    ranks = []
    db = DB(DB_FILE)
    await db.connect()
    data = await db.get_ranks(epoch, sort, limit)
    num = 1

    async for row in data:
        bot, link_karma, comment_karma, good_bots, bad_bots, top_score, hot_score, controversial_score = row
        rank = Bot()
        rank.name = bot
        rank.score = top_score
        votes = Votes()
        votes.good = good_bots
        votes.bad = bad_bots
        rank.votes = votes
        karma = Karma()
        karma.link = link_karma
        karma.comment = comment_karma
        rank.karma = karma
        ranks.append(rank)
    await db.close()
    for bot in sorted(ranks, key=lambda x: x.score, reverse=True):
        bot.rank = num
        num += 1
    return ranks
Пример #4
0
def test_add_one_vote_and_return_100():

    add = Votes()
    add['result'] = 1
    add.save()

    get = report()
    _sum = get['p1']+get['p2']
    assert _sum == 100, _sum
Пример #5
0
def test_add_three_vote_and_return_100():

    for a in [1,2,1]:
        add = Votes()
        add['result'] = a
        add.save()

    get = report()
    _sum = get['p1']+get['p2']
    assert _sum == 100, _sum
Пример #6
0
def add_vote(request, poll_id):
	poll = Poll.objects.get(id=poll_id)
	choice = Choice.objects.filter(poll=poll_id).order_by('id')
	if request.method == 'POST':
		vote = request.POST.get('choice')
		if vote:
			vote = Choice.objects.get(id=vote)
			# saves the poll id, user id, and choice to the votes table
			v = Votes(poll=poll, choiceVote = vote)
			v.save()
			# redirects the user to the results page after they submit their vote
			return HttpResponseRedirect('../.')
		return render_to_response('votes.html', {'choice': choice, 'poll': poll, 'vcount': vcount,}, context_instance=RequestContext(request))
Пример #7
0
def vote_up(request, answer_id):
    if request.user.is_authenticated():
        answer = Answer.objects.get(id = answer_id)
        votos = Votes.objects.filter(author = request.user, answer = answer)
        question_id = answer.question.id       
        if len(votos) == 0:
            voto = Votes(answer = answer, author = request.user, vote = 'Up')
            voto.save()
        else:
            pass #TODO mandar un mensaje de que ya voto.
            #request.session['message'] = 'Usted ya ha votado por esta repuesta.' 
        return HttpResponseRedirect('/soporte/pregunta/' + str(question_id))
    else:
        return HttpResponseRedirect('/cuentas/login')
Пример #8
0
def handle_vote(vote):
    vote_count_up = vote_count('up')
    vote_count_down = vote_count('down')
    p_up = percent_up()
    if not 'vote' in request.cookies:  # if the user has not voted, add their vote
        if market_closed(
                datetime.utcnow()):  # market is closed and its a weekday
            v = Votes(vote)
            db.session.add(v)
            db.session.commit()
            response = make_response(
                render_template('poll.html',
                                percent_up=percent_up(),
                                vote_count_up=vote_count('up'),
                                vote_count_down=vote_count('down'),
                                vote=vote))
            response.set_cookie('vote', vote)
            return response
        else:  # user has not voted, but the window is closed
            return render_template("home.html",
                                   percent_up=p_up,
                                   vote_count_up=vote_count_up,
                                   vote_count_down=vote_count_down)

    else:  # if the user has voted, then display the poll html without adding to db
        response = make_response(
            render_template('poll.html',
                            percent_up=p_up,
                            vote_count_up=vote_count_up,
                            vote_count_down=vote_count_down,
                            vote=vote))
        return response
Пример #9
0
def report():
    p_1 = Votes.query().filter(result='1').count()
    p_2 = Votes.query().filter(result='2').count()

    p1 = 0
    if p_1 != 0:
        p1 = int((p_1*100.00)/(p_1+p_2))
    p2 = 0
    if p_2 != 0:
        p2 = int((p_2*100.00)/(p_1+p_2))

    if p1 == 0 and p2 == 0:
        p1 = 50
        p2 = 50

    return {'p1': p1, 'p2': p2}
Пример #10
0
async def get_subs(after='1y', limit=None):
    epoch = get_epoch(after)
    db = DB(DB_FILE)
    subs = []
    await db.connect()
    data = await db.get_subs(epoch, limit)
    async for row in data:
        sub = Sub()
        sub.name = row[0]
        votes = Votes()
        votes.good = row[1]
        votes.bad = row[2]
        sub.votes = votes
        subs.append(sub)
    await db.close()
    return subs
Пример #11
0
def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly set
        for key, value in poll.items():
            if not value:
                return jsonify(
                    {'message': 'value for {} is empty'.format(key)})

        title = poll['title']
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))

        options = [
            Votes(option=Options(
                name=option)) if options_query(option).count() == 0 else Votes(
                    option=options_query(option).first())
            for option in poll['options']
        ]
        eta = datetime.utcfromtimestamp(poll['close_date'])
        new_poll = Polls(title=title,
                         options=options,
                         close_date=eta,
                         voting_method=0)

        db.session.add(new_poll)
        db.session.commit()

        # run the task
        from tasks import close_poll

        close_poll.apply_async((new_poll.id, SQLALCHEMY_DATABASE_URI), eta=eta)

        return jsonify({'message': 'Poll was created succesfully'})

    else:
        # it's a GET request, return dict representations of the API
        polls = Polls.query.filter_by(status=True).join(Votes).order_by(
            Polls.id.desc()).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Пример #12
0
def api_poll_vote():
    poll = request.get_json()

    poll_title, option_name = (poll['poll_title'], poll['option'])

    join_tables = Votes.query.join(Polls).join(Options)

    # Get votes, poll, username, and option from the database
    poll = Polls.query.filter_by(title=poll_title, status=True).first()
    user = Users.query.filter_by(username=session['user']).first()
    option = Options.query.filter_by(name=option_name).first()

    # if poll was closed in the background before user voted
    if not poll:
        return jsonify({'message': 'Sorry! this poll has been closed'})

    # filter option names
    option_name = join_tables.filter(
        Polls.title.like(poll_title),
        Polls.status == True).filter(Options.name.like(option_name)).first()

    if option_name:
        # check if the user has voted on this poll
        poll_count = UserPolls.query.filter_by(poll_id=poll.id).filter_by(
            user_id=user.id).filter_by(option_id=option.id).count()
        if poll_count > 0:
            return jsonify(
                {'message': 'Sorry! multiple votes are not allowed'})

        # record userpoll and vote
        user_poll = UserPolls(poll_id=poll.id,
                              user_id=user.id,
                              option_id=option.id)
        user_vote = Votes(poll_id=poll.id,
                          user_id=user.id,
                          option_id=option.id,
                          vote_count=0)

        db.session.add(user_poll)
        db.session.add(user_vote)

        # increment vote_count by 1 if the option was found
        option_name.vote_count += 1

        db.session.commit()

        return jsonify({'message': 'Thank you for voting'})

    return jsonify(
        {'message': 'Option or poll was not found please try again'})
Пример #13
0
def save_vote():
    # Get the team and time the vote was cast.
    team = request.form["team"]
    time_cast = datetime.datetime.utcnow()

    if team != "TABS" and team != "SPACES":
        return Response(response="Invalid team specified.", status=400)

    try:
        with session_scope() as session:
            session.add(Votes(time_cast=time_cast, candidate=team))
    except Exception as e:
        return Response(
            status=500,
            response="Unable to successfully cast vote!",
        )
    return Response(
        status=200,
        response="Vote successfully cast for '{}'".format(team),
    )
Пример #14
0
def addVotes(plainText, certificate):
    p1 = Votes(plainText=plainText, certificate=certificate)
    p1.save()
Пример #15
0
def addVotes(plainText,certificate):
	p1 = Votes(plainText=plainText, certificate=certificate)
	p1.save()
Пример #16
0
async def get_graph(after='1y'):
    epoch = get_epoch(after)
    db = DB(DB_FILE)
    await db.connect()

    results = {}
    if 'd' in after:
        for i in range(24):
            results[str(i)] = {'good_votes': 0, 'bad_votes': 0}
        data = await db.get_timeline_data(epoch, '%H')
        async for row in data:
            key, good_votes, bad_votes = row
            results[str(int(key))] = {
                'good_votes': good_votes,
                'bad_votes': bad_votes
            }

    elif 'w' in after:
        days_of_week = [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
            'Saturday'
        ]
        for day in days_of_week:
            results[day] = {'good_votes': 0, 'bad_votes': 0}
        data = await db.get_timeline_data(epoch, '%w')
        async for row in data:
            key, good_votes, bad_votes = row
            results[days_of_week[int(key)]] = {
                'good_votes': good_votes,
                'bad_votes': bad_votes
            }

    elif 'M' in after:
        for i in range(31):
            results[str(i)] = {'good_votes': 0, 'bad_votes': 0}
        data = await db.get_timeline_data(epoch, '%d')
        async for row in data:
            key, good_votes, bad_votes = row
            results[str(int(key))] = {
                'good_votes': good_votes,
                'bad_votes': bad_votes
            }

    else:
        months_of_year = [
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'
        ]
        for month in months_of_year:
            results[month] = {'good_votes': 0, 'bad_votes': 0}
        data = await db.get_timeline_data(epoch, '%m')
        async for row in data:
            key, good_votes, bad_votes = row
            results[months_of_year[int(key) - 1]] = {
                'good_votes': good_votes,
                'bad_votes': bad_votes
            }

    graph = Graph()
    graph.labels = []
    graph.votes = []
    for key in results:
        good_votes = results[key]['good_votes']
        bad_votes = results[key]['bad_votes']
        graph.labels.append(key)
        votes = Votes()
        votes.good = good_votes
        votes.bad = bad_votes
        graph.votes.append(votes)

    await db.close()
    return graph