def updatePicture(choiceid: int, data: dict) -> str:
    if not 'picture' in data:
        return Response.wrong_format({
            'updated': False,
            'message': 'picture missing'
        })
    if not data['picture'].endswith('=='):
        return Response.wrong_format({
            'updated': False,
            'message': 'not a base64 string'
        })
    try:
        choice = session.query(Choice).get(choiceid)
    except:
        return Response.database_error()
    if not choice:
        return Response.ressource_not_found({
            'id': choiceid,
            'message': 'choiceid not found!'
        })
    choice.picture = data['picture']
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok({'id': choiceid, 'updated': True})
def update_votes(choiceId: int, data: dict) -> str:
    if not 'votes' in data:
        return Response.wrong_format({
            'updated': False,
            'message': 'votes missing'
        })

    if not type(data['votes']) == int:
        return Response.wrong_format({
            'id': 'error',
            'message': 'Not a number'
        })
    try:
        choice = session.query(Choice).get(choiceId)
    except:
        return Response.database_error()
    if choice:
        choice.counter += int(data['votes'] or 0)
        try:
            session.commit()
        except:
            return Response.database_error()
        return Response.ok({'id': choiceId, 'success': True})
    else:
        return Response.ressource_not_found({
            'id': choiceId,
            'message': 'choice not found'
        })
def get_result_of_election_round(electionroundid: int):
    '''Returns the result of an election round.'''
    try:
        electionround = session.query(ElectionRound).filter(
            ElectionRound.id == electionroundid).first()
        choices_list = session.query(Choice).filter(
            Choice.election_round_id == electionround.id).all()
    except:
        return Response.database_error()

    result_choices = []
    for choice in choices_list:
        tmp = {}
        tmp['id'] = choice.id
        tmp['description'] = choice.description
        tmp['picture'] = choice.picture
        tmp['counter'] = choice.counter
        result_choices.append(tmp)
    try:
        session.commit()
    except:
        return Response.database_error()
    result = {}
    result["electionroundid"] = electionroundid
    result['choices'] = result_choices
    return Response.ok(json.dumps(result))
Ejemplo n.º 4
0
def get_all_persons_who_have_not_voted(elec_round_id: int) -> dict:
    '''Get all persons who have not voted
    
    Warning: This is only accurate at the time of the election round, since 
    people can leave (altering the is_present) after the election round.
    '''
    try:
        elec_round = _get_electionround_by_id(elec_round_id)
        if not elec_round:
            return Response.ressource_not_found(
                {"message": "No election round for this id."})
    except:
        return Response.database_error()
    persons_voted = elec_round.persons_voted

    # Get present people
    try:
        persons_present = session.query(Person).filter(
            Person.is_present == True).all()
        session.commit()
    except:
        return Response.database_error()
    # Get all persons who didn't vote but are present
    persons_not_voted = []
    for person in persons_present:
        if person not in persons_voted:
            persons_not_voted.append(person)

    # Create response
    ret = []
    for person in persons_not_voted:
        ret.append({"id": person.id, "name": person.name})
    return Response.ok(json.dumps(ret))
def get_all_persons():
    try:
        persons = session.query(Person).all()
        session.commit()
    except:
        Response.database_error()
    response = []
    for person in persons:
        response.append(model_as_dict(person))
    json_response = json.dumps(response)
    return Response.ok(json_response)
def get_all_open_elections():
    '''Returns all active elections'''
    try:
        elec_round_list = session.query(ElectionRound).filter(
            ElectionRound.running == "running").all()
        session.commit()
    except:
        Response.database_error()
    response = []
    for round in elec_round_list:
        response.append(model_as_dict(round))

    return Response.ok(json.dumps(response))
def check_out(userid: int):
    if not userid:
        return Response.wrong_format({
            'updated': False,
            'message': 'userid missing'
        })

    person = session.query(Person).filter(Person.id == userid).first()
    person.is_present = False
    try:
        session.commit()
    except:
        Response.database_error()
    return Response.ok({"userid": userid, "message": "checked out"})
def read_choices(electionid: int) -> str:
    try:
        choices = session.query(Choice).filter_by(election_round_id=electionid)
    except:
        Response.database_error()
    liste = []
    for choice in choices:
        liste.append({
            'id': choice.id,
            'picture': choice.picture,
            'description': choice.description,
            'counter': choice.counter
        })
    return Response.ok(json.dumps(liste))
Ejemplo n.º 9
0
def place_vote(data: dict):
    if not 'choice_id' in data:
        return Response.wrong_format(
            {'message': 'choiceid is required for voting'})
    if not 'election_round_id' in data:
        return Response.wrong_format(
            {'message': 'election_round_id required for voting'})
    if not 'person_id' in data:
        return Response.wrong_format(
            {'message': 'person_id required for voting'})
    try:
        election_round_id = int(data['election_round_id'])
        person_id = int(data['person_id'])
        choice_id = int(data['choice_id'])
    except:
        return Response.wrong_format(
            {"message": "ids have to be an int base 10"})
    elec_round = _get_electionround_by_id(election_round_id)
    if not elec_round:
        return Response.ressource_not_found(
            {"message": "No electionround for this id."})
    person = get_person_by_id(person_id)
    if person in elec_round.persons_voted:
        return Response.server_error({"message": "Person already voted"})
    try:
        choice = session.query(Choice).filter_by(id=choice_id).first()
        session.commit()
        if choice is None:
            return Response.ressource_not_found(
                {"message": "No Choice with this id."})
    except:
        print("no choice")
        return Response.database_error()

    if choice not in elec_round.choices:
        return Response.server_error(
            {"message": "Electionround has no Choice with that ID"})
    try:
        choice.counter = choice.counter + 1
        session.commit()
    except:
        return Response.database_error()
    try:
        elec_round.persons_voted.append(person)
        session.commit()
    except:
        return Response.database_error()

    return Response.ok(model_as_dict(choice))
def close_open_election_round(electionroundid: int):
    '''Closes an election round.'''

    try:
        electionround = session.query(ElectionRound).filter(
            ElectionRound.id == electionroundid).first()
    except:
        return Response.database_error()
    if electionround.running != "finished":
        electionround.running = "finished"
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(model_as_dict(electionround))
Ejemplo n.º 11
0
def update_choice_proxy(data: dict) -> bool:
    '''Updates an choice proxy'''
    if not 'senderid' in data:
        return Response.wrong_format({'message': 'senderid missing'})
    if not type(data['senderid']) == int:
        return Response.wrong_format({'message': 'senderid: not a number'})

    if not 'receiverid' in data:
        return Response.wrong_format({'message': 'receiverid missing'})
    if not type(data['receiverid']) == int:
        return Response.wrong_format({'message': 'receiverid: not a number'})

    if data['receiverid'] == data['senderid']:
        return Response.wrong_format({'message': 'receiverid equals senderid'})

    try:
        receiver = session.query(Person).filter(
            Person.id == data['receiverid']).first()
        sender = session.query(Person).filter(
            Person.id == data['senderid']).first()
        delete_choice_proxy(data['senderid'])
        receiver.received_proxy_vote.append(sender)
        session.commit()
    except:
        return Response.database_error()
    return Response.ok({
        "success":
        True,
        'message':
        'senderid {} gave vote to receiverid {}'.format(
            sender.id, receiver.id)
    })
def add_choice_to_election_round(data: dict):
    '''Adds an choice to an election round.'''
    if not 'choiceid' in data:
        return Response.wrong_format({'message': 'choiceid missing'})
    if not type(data['choiceid']) == int:
        return Response.wrong_format({'message': 'choiceid: not a number'})

    if not 'electionroundid' in data:
        return Response.wrong_format({'message': 'electionroundid missing'})
    if not type(data['electionroundid']) == int:
        return Response.wrong_format(
            {'message': 'electionroundid: not a number'})

    try:
        choice = session.query(Choice).filter(
            Choice.id == data['choiceid']).first()
        electionround = session.query(ElectionRound).filter(
            ElectionRound.id == data['electionroundid']).first()
        choice.election_round = electionround
        session.commit()
    except:
        return Response.database_error()
    return Response.ok({
        'message':
        'added choiceid {} to electionroundid {}'.format(
            data['choiceid'], data['electionroundid'])
    })
Ejemplo n.º 13
0
def delete_choice_proxy(id: int) -> bool:
    '''Deletes an choice proxy.'''
    #choice = session.query(Person).join(
    #   has_choice_proxy_table).join(Person).filter(
    #   has_choice_proxy_table.sender_id == id).first()
    try:
        choice = session.query(has_choice_proxy_table).filter(
            has_choice_proxy_table.c.sender_id == id).first()
        if not choice:
            return Response.ressource_not_found(
                {'message': 'senderid not found'})
        receiver = session.query(Person).filter(
            Person.id == choice.receiver_id).first()
        sender = session.query(Person).filter(
            Person.id == choice.sender_id).first()
        receiver.received_proxy_vote.remove(sender)
        session.commit()
    except:
        return Response.database_error()
    return Response.ok({
        "success":
        True,
        'message':
        'senderid {} deleted vote from receiverid {}'.format(
            sender.id, receiver.id)
    })
def delete_choice(choiceid: int) -> str:
    try:
        choice = session.query(Choice).get(choiceid)
    except:
        return Response.database_error()
    if not choice:
        return Response.ressource_not_found({
            'id': choiceid,
            'message': 'choiceid not found!'
        })
    session.delete(choice)
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(json.dumps({'id': choiceid, 'deleted': True}))
def create_choice(data: dict) -> str:
    if not 'description' in data:
        return Response.wrong_format(
            json.dumps({'message': 'description missing'}))
    if not 'election_round_id' in data:

        return Response.wrong_format(
            json.dumps({'message': 'electionid missing'}))

    if 'picture' in data:
        if data['picture'].endswith('=='):
            picture = data['picture']
        else:
            return Response.wrong_format({"message": "picture is not Base64"})
    else:
        picture = ''

    choice = Choice(description=data['description'],
                    counter=0,
                    picture=picture,
                    election_round_id=data['election_round_id'])
    session.add(choice)
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(
        json.dumps({
            'id': choice.id,
            'description': choice.description
        }))
def create_person(data: dict):
    if 'name' not in data or not data['name']:
        return Response.wrong_format({"message": "Name missing!"})
    p1 = Person()
    p1.name = data['name']
    # TODO: Encpyt Passwords
    p1.password = ""
    p1.mail = data['email']
    p1.is_present = False
    p1.role = "0"
    session.add(p1)
    try:
        session.commit()
    except:
        Response.database_error()
    response = model_as_dict(p1)
    return Response.ok(response)
Ejemplo n.º 17
0
def get_person_by_id(personid: int) -> Person:
    try:
        person = session.query(Person).filter_by(id=personid).first()
        session.commit()
    except:
        return Response.database_error()
    if person is None:
        return Response.ressource_not_found(
            {"message": "No persion for this id."})
    return person
def delete_person(userid: int):
    print(type(userid))
    if not userid:
        return Response.wrong_format({
            'updated': False,
            'message': 'userid missing'
        })

    try:
        person = session.query(Person).filter_by(id=userid).first()
    except:
        return Response.database_error()

    if not person:
        return Response.ressource_not_found({"message": "userid not found!"})
    session.delete(person)
    try:
        session.commit()
    except:
        Response.database_error()
    return Response.ok({"userid": userid, "message": "deleted"})
def get_all_election_rounds():
    '''Returns all election rounds.'''
    try:
        elec_round_list = session.query(ElectionRound).all()
        session.commit()
    except:
        return Response.database_error()
    response = []
    for round in elec_round_list:
        response.append(model_as_dict(round))

    return Response.ok(json.dumps(response))
def get_all_persons_checked_out():
    try:
        persons = session.query(Person).filter(
            Person.is_present == False).all()
        session.commit()
    except:
        return Response.database_error()
    response = []
    for person in persons:
        response.append(model_as_dict(person))
    json_respose = json.dumps(response)
    return Response.ok(json.dumps(response))
Ejemplo n.º 21
0
def set_vote(data: dict):
    '''Add a person to the as has voted to the election_round'''
    if not 'elec_round_id' in data:
        return Response.wrong_format({'message': 'elec_round_id required'})
    if not 'person_id' in data:
        return Response.wrong_format({'message': 'person_id required'})

    try:
        elec_round_id = int(data['elec_round_id'])
        person_id = int(data['person_id'])
    except ValueError:
        return Response.wrong_format(
            {"message": "ids have to be an int (base 10)."})

    # Get election_round
    try:
        elec_round = _get_electionround_by_id(elec_round_id)
        if not elec_round:
            return Response.ressource_not_found(
                {"message": "No electionround for this id."})
    except:
        return Response.database_error()

    # Get person
    try:
        person = session.query(Person).filter_by(id=person_id).first()
        session.commit()
        if person is None:
            return Response.ressource_not_found(
                {"message": "No persion for this id."})

        # Add person to election_round
        elec_round.persons_voted.append(person)
        session.commit()

    except:
        return Response.database_error()
    return Response.ok({"message": "OK"})
Ejemplo n.º 22
0
def upload_csv(file):
    first_name = 'fn'
    surname = 'sn'
    mail = 'mail'
    if not file:
        return Response.wrong_format({'message': 'no file'})

    try:
        csv_file_pandas = read_csv(file, usecols=[first_name, surname, mail])
    except ValueError:
        return Response.wrong_format({
            'message':
            '.csv columns missing. Must contain {}, {}'.format(
                first_name, surname, mail)
        })
    except:
        return Response.server_error({'message': 'error processing .csv-file'})

    pw_list = []

    for index, row in csv_file_pandas.iterrows():
        person = Person()
        person.name = '{} {}'.format(row[first_name], row[surname])
        password = ''.join([
            choice('abcdefghijklmnopqrstuvwxyz0123456789-') for i in range(15)
        ])
        person.password = argon2.hash(password)
        person.mail = row[mail]
        person.is_present = False
        person.role = '0'
        pw_list.append({
            'mail': person.mail,
            'password': password,
            'name': person.name
        })
        session.add(person)

    duplicates = []
    try:
        session.commit()
    except IntegrityError as e:
        print(e)
        duplicates.append(e)
    except:
        return Response.database_error()

    send_email(pw_list)

    return Response.ok({'message': 'ok', "duplicates": str(duplicates)})
Ejemplo n.º 23
0
def create_choice_proxy(data: dict) -> bool:
    '''Create an proxy for an voter.'''
    if not 'senderid' in data:
        return Response.wrong_format({'message': 'senderid missing'})
    if not type(data['senderid']) == int:
        return Response.wrong_format({'message': 'senderid: not a number'})

    if not 'receiverid' in data:
        return Response.wrong_format({'message': 'receiverid missing'})
    if not type(data['receiverid']) == int:
        return Response.wrong_format({'message': 'receiverid: not a number'})

    if data['receiverid'] == data['senderid']:
        return Response.wrong_format({'message': 'receiverid equals senderid'})

    try:
        choice = session.query(has_choice_proxy_table).filter(
            has_choice_proxy_table.c.sender_id == data["senderid"]).first()
        if choice:
            return Response.wrong_format({
                'message':
                'senderid {} already gave their vote'.format(data['senderid'])
            })
        receiver = session.query(Person).filter(
            Person.id == data['receiverid']).first()
        if not receiver:
            return Response.ressource_not_found(
                {'message': 'receiverid: not found'})
        sender = session.query(Person).filter(
            Person.id == data['senderid']).first()
        if not sender:
            return Response.ressource_not_found(
                {'message': 'senderid: not found'})
        print('line 40')
        receiver.received_proxy_vote.append(sender)
        session.commit()
    except Exception as e:
        print(e)
        return Response.database_error()
    return Response.ok({
        "success":
        True,
        'message':
        'senderid {} gave vote to receiverid {}'.format(
            sender.id, receiver.id)
    })
Ejemplo n.º 24
0
def get_all_persons_who_voted(elec_round_id: int):
    '''Return all persons as dict who have already participated in
    an election round.'''

    try:
        elec_round = _get_electionround_by_id(elec_round_id)
        if not elec_round:
            return Response.ressource_not_found(
                {"message": "No election round for this id."})
    except:
        return Response.database_error()

    # Build and return dict
    ret = []
    for person in elec_round.persons_voted:
        ret.append({"id": person.id, "name": person.name})
    return Response.ok(json.dumps(ret))
Ejemplo n.º 25
0
def _get_electionround_by_id(elec_round_id: int) -> ElectionRound:
    '''get election round by id and handle errors'''
    # Elec_round_id should be int
    try:
        elec_round_id = int(elec_round_id)
    except ValueError:
        return Response.wrong_format(
            {"message": "elec_round_id has to be an int (base 10)."})

    # Get ElectionRound object from the DB.
    try:
        elec_round = session.query(ElectionRound).filter_by(
            id=elec_round_id).first()
        session.commit()
    except:
        return Response.database_error()
    # Handle invalid election round
    if elec_round is None:
        return Response.ressource_not_found(
            {"message": "No electionround for this id."})
    return elec_round
def create_election_round(data: dict):
    '''Creates an election round'''
    if not 'title' in data or not data['title']:
        return Response.wrong_format({"message": "Title is missing"})
    if not 'max_choices_per_person' in data:
        return Response.wrong_format(
            {"message": "max_choices_per_person is missing"})
    if not type(data['max_choices_per_person']) == int:
        return Response.wrong_format(
            {'message': 'max_choices_per_person: not a number'})

    elec_round = ElectionRound()
    elec_round.title = data['title']
    elec_round.running = 'not_started'
    elec_round.max_choices_per_person = data['max_choices_per_person']
    session.add(elec_round)
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(model_as_dict(elec_round))