Ejemplo n.º 1
0
    def get(self, election_id):
        # get current user
        user = self.current_user

        # get election
        election = elections_alchemy.query_election(election_id=election_id)
        if election == list():
            raise exceptions.NotFound404Exception('election with specified ID not found')
        election = election[0]

        # check if results should not be sent
        is_admin = user is not None and (admin_permission in user.roles or elections_permission in user.roles)
        if not is_admin and (election.show_results is None or datetime.now() < election.show_results):
            raise exceptions.Forbidden403Exception('results are not available for this election')

        # count votes for each position
        position_totals = list()
        for position in elections_alchemy.query_position(election_type=election.election_type, active=True):
            # add each position to the totals
            position_summary = {
                'position': position.id,
                'votes': elections_alchemy.count_votes(election_id, position.id)
            }
            position_totals.append(position_summary)

        # response
        self.set_status(200)
        self.write({'positions': [position for position in position_totals]})
Ejemplo n.º 2
0
def validate_ballot(parameters):
    """
    Validate a ballot's parameters based on constraints.
    :param parameters: The ballot's parameters.
    :return: None
    """
    # check if election exists
    specified_election = elections_alchemy.query_election(election_id=parameters['election'])
    if specified_election == list():
        raise exceptions.NotFound404Exception('election with specified ID not found')

    # check if position exists and is active
    specified_position = elections_alchemy.query_position(position_id=parameters['position'])
    if specified_position == list() or specified_position[0].active is False:
        raise exceptions.Forbidden403Exception('position with specified ID not found')

    # check if position is the right election type
    if specified_position[0].election_type != specified_election[0].election_type:
        raise exceptions.Forbidden403Exception('you are creating a vote for a position in a different election type')

    # check for valid candidate username
    if mask_alchemy.query_by_username(parameters['vote']) is None:
        raise exceptions.Forbidden403Exception('you cannot create a vote for this candidate')

    # check for duplicate votes
    if elections_alchemy.query_vote(election_id=specified_election[0].id,
                                    position_id=specified_position[0].id,
                                    vote=parameters['vote'],
                                    username=parameters['username']) != list():
        raise exceptions.Forbidden403Exception('this candidate has already been voted for by this user')
Ejemplo n.º 3
0
    def get(self, position_id):
        # get position
        position = elections_alchemy.query_position(position_id=str(position_id))
        if position == list():
            raise exceptions.NotFound404Exception('position with specified ID not found')

        # response
        self.set_status(200)
        self.write(position[0].serialize())
Ejemplo n.º 4
0
    def get(self):
        # build query parameter dict
        search_criteria = build_query_params(self.request.arguments)

        # get positions
        positions = elections_alchemy.query_position(position=search_criteria.get('position', None),
                                                     election_type=search_criteria.get('election_type', None),
                                                     active=search_criteria.get('active', None))

        # response
        self.set_status(200)
        self.write({'positions': [p.serialize() for p in positions]})
Ejemplo n.º 5
0
    def post(self, election_id):
        # get current user
        user = self.current_user

        # load request body
        body = self.request.body.decode('utf-8')
        body_json = json.loads(body)

        # validate parameters
        required_parameters = ('election', 'position', 'student_id', 'vote')
        elections_validator.validate_parameters(body_json, required_parameters)

        # get student username from student ID
        voter = mask_alchemy.query_by_wwuid(mask_model.User, body_json['student_id'])
        if voter == list():
            raise exceptions.NotFound404Exception('user with specified student ID not found')
        voter = voter[0]

        # build proper vote from ballot data and validate it
        body_json['election'] = str(election_id)
        body_json['username'] = str(voter.username)
        body_json['manual_entry'] = str(user.username)
        elections_validator.validate_ballot(body_json)

        # check for too many votes
        specified_election = elections_alchemy.query_election(election_id=body_json['election'])
        specified_position = elections_alchemy.query_position(position_id=body_json['position'])
        if len(elections_alchemy.query_vote(election_id=specified_election[0].id,
                                            position_id=specified_position[0].id,
                                            username=str(voter.username))) >= specified_election[0].max_votes:
            raise exceptions.Forbidden403Exception(
                'this user has already cast {} vote/s'.format(str(specified_election[0].max_votes))
            )

        # create new vote
        vote = elections_model.Vote()
        for parameter in required_parameters:
            if parameter != 'student_id':
                setattr(vote, parameter, body_json[parameter])
        setattr(vote, 'username', str(voter.username))
        setattr(vote, 'manual_entry', str(user.username))
        elections_alchemy.add_or_update(vote)

        # response
        self.set_status(201)
        self.write(vote.serialize_ballot())
Ejemplo n.º 6
0
    def post(self):
        # get current user
        user = self.current_user

        # load request body
        body = self.request.body.decode('utf-8')
        body_json = json.loads(body)

        # validate parameters
        required_parameters = ('election', 'position', 'vote')
        elections_validator.validate_parameters(body_json, required_parameters)
        body_json['username'] = str(user.username)
        elections_validator.validate_vote(body_json)

        # check for too many votes
        specified_election = elections_alchemy.query_election(election_id=body_json['election'])
        specified_position = elections_alchemy.query_position(position_id=body_json['position'])

        if len(elections_alchemy.query_vote(election_id=specified_election[0].id,
                                            position_id=specified_position[0].id,
                                            username=str(user.username))) > specified_election[0].max_votes:
            raise exceptions.Forbidden403Exception(
                'you may only cast {} vote/s'.format(str(specified_election[0].max_votes))
            )

        if specified_election[0].election_type == 'senate':
            votes = elections_alchemy.query_vote(election_id=specified_election[0].id, 
                                                username=str(user.username))
            for vote in votes:
                if vote.position != body_json['position']:
                    elections_alchemy.delete(vote)

        # create new vote
        vote = elections_model.Vote()
        for parameter in required_parameters:
            setattr(vote, parameter, body_json[parameter])
        setattr(vote, 'username', str(user.username))
        elections_alchemy.add_or_update(vote)

        # response
        self.set_status(201)
        self.write(vote.serialize())
Ejemplo n.º 7
0
def validate_vote(parameters, existing_vote=None):
    """
    Validate a vote's parameters based on constraints.
    :param parameters: The vote's parameters.
    :param existing_vote: An existing vote being updated used to check for duplicate votes.
    :return: None
    """
    # check if election exists
    specified_election = elections_alchemy.query_election(election_id=parameters['election'])
    if specified_election == list():
        raise exceptions.NotFound404Exception('election with specified ID not found')

    # check if not current election
    current_election = elections_alchemy.query_current()
    if specified_election[0] != current_election:
        raise exceptions.Forbidden403Exception('this election is not available for voting')

    # check if position exists and is active
    specified_position = elections_alchemy.query_position(position_id=parameters['position'])
    if specified_position == list() or specified_position[0].active is False:
        raise exceptions.Forbidden403Exception('position with specified ID not found')

    # check if position is the right election type
    if specified_position[0].election_type != current_election.election_type:
        raise exceptions.Forbidden403Exception('you are voting for a position in a different election type')

    # check for valid candidate username
    if mask_alchemy.query_by_username(parameters['vote']) is None:
        raise exceptions.Forbidden403Exception('you cannot vote for this person')

    # check for duplicate votes
    if parameters['vote'] != getattr(existing_vote, 'vote', None) and \
            elections_alchemy.query_vote(election_id=specified_election[0].id,
                                         position_id=specified_position[0].id,
                                         vote=parameters['vote'],
                                         username=parameters['username']) != list():
        raise exceptions.Forbidden403Exception('you have already voted for this person')
Ejemplo n.º 8
0
def validate_candidate(parameters):
    """
    Validate a candidate's parameters based on constraints.
    :param parameters: The candidate's parameters.
    :return: None
    """
    # check to make sure there is an election to push candidates to
    election = elections_alchemy.query_election(election_id=parameters['election'])
    if election == list():
        raise exceptions.NotFound404Exception('election with specified ID not found')
    election = election[0]

    # check to make sure election is either current or up and coming
    if election != elections_alchemy.query_current() and \
            election not in elections_alchemy.query_election(start_after=datetime.now()):
        raise exceptions.Forbidden403Exception('candidate not in current election')

    # check to makes sure position exists
    if not elections_alchemy.query_position(position_id=str(parameters["position"])):
        raise exceptions.NotFound404Exception('position with specified ID not found')

    # check to make sure election exists
    if not elections_alchemy.query_election(election_id=parameters['election']):
        raise exceptions.NotFound404Exception('election with specified ID not found')
Ejemplo n.º 9
0
    def put(self, position_id):
        # load request body
        body = self.request.body.decode('utf-8')
        body_json = json.loads(body)

        # validate parameters
        required_parameters = ('id', 'position', 'election_type', 'active', 'order')
        elections_validator.validate_parameters(body_json, required_parameters)
        elections_validator.validate_position(body_json)

        # get position
        position = elections_alchemy.query_position(position_id=str(position_id))
        if position == list():
            raise exceptions.NotFound404Exception('position with specified ID not found')
        position = position[0]

        # update position
        for parameter in required_parameters:
            setattr(position, parameter, body_json[parameter])
        elections_alchemy.add_or_update(position)

        # response
        self.set_status(200)
        self.write(position.serialize())