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 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
        }))
示例#4
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'])
    })
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)})
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))
示例#8
0
def login(data):
    if not 'email' in data.form:
        return Response.wrong_format({'message': 'email missing'})
    if not 'password' in data.form:
        return Response.wrong_format({'message': 'password missing'})
    user = session.query(Person).filter(
        Person.mail == data.form['email']).first()
    if (argon2.verify(data.form['password'], user.password)):
        sessionid = uuid.uuid4()
        session_end = datetime.datetime.now() + datetime.timedelta(
            seconds=config.getint('Session', 'session_duration'))
        fsession[str(sessionid)] = {
            'user.id': user.id,
            'session_end': session_end
        }
        return Response.ok({'sessionID': sessionid})
    Response.unauthorized()
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))
def generate_password(data: dict):
    if not 'userid' in data:
        return Response.wrong_format({
            'updated': False,
            'message': 'userid missing'
        })

    person = session.query(Person).filter_by(id=data["userid"]).first()
    password = ''.join(
        [choice('abcdefghijklmnopqrstuvwxyz0123456789-') for i in range(15)])
    person.password = argon2.hash(password)
    session.commit()
    return '{ "new_password" : "{}"}'.format(password)
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"})
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 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)
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 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"})
示例#16
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)
    })