Esempio n. 1
0
 def api_create(self, **data):
     fillable = Validator.validate(data, self.__class__.fields,
                                   self.__class__.defaults)
     if self.find({"login": fillable["login"]}) is not None:
         Validator.fail('Der Benutzername ist bereits vergeben.')
     resource = self.create(fillable)
     return resource
Esempio n. 2
0
 def PUT(self, race_id, vehicle_id, station, **data):
     race_id = Validator.require_int(race_id)
     vehicle_id = Validator.require_int(vehicle_id)
     station = Validator.require_int(station)
     resource = self.find({
         "race_id": race_id,
         "vehicle_id": vehicle_id,
         "station": station
     })
     if resource is None:
         resource = {
             "race_id": race_id,
             "vehicle_id": vehicle_id,
             "station": station
         }
         data = Validator.validate(data,
                                   self.__class__.fields,
                                   self.__class__.defaults,
                                   require_all=True)
         self.resources.append(resource)
     else:
         data = Validator.validate(data,
                                   self.__class__.fields,
                                   self.__class__.defaults,
                                   require_all=False)
     for field in data:
         resource[field] = data[field]
     self.save()
     return self.response(resource)
def login_user():
    """User verification and Login"""

    input_data = request.get_json(force=True)

    # validation check for required values
    if 'email' not in input_data.keys() or 'password' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'email' and 'password' data")
    email = input_data['email'].strip()
    if len(email) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide an email address")
    password = input_data['password']
    if len(password.strip()) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide a password")

    # get all users and check if email and password match
    all_users = User.read_all(db.cur)
    if all_users is not None:
        for user in all_users:
            if email.strip().lower() == user.email.strip().lower() and sha256.verify(password, user.password):
                user_dict = user.obj_to_dict()
                # create token
                access_token = create_access_token(
                    identity=user.id, expires_delta=False)
                user_dict['access_token'] = access_token
                user_dict['msg'] = 'Login Successful!'
                return jsonify(user_dict), 200  # return user with access token
        # if the iterations do not find any matching user, return message:
        return Validator.custom_response(403, 'Forbidden', 'Invalid Login Credentials')
    else:
        return Validator.custom_response(200, "OK", "Request Successful BUT There are no users in store")
def api_add_answer(question_id):
    """Add an answer to a specific question"""

    # get id of user currently logged in (from authentication token)
    current_user_id = get_jwt_identity()
    input_data = request.get_json(force=True)
    if 'answer' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'answer' data")
    answer = input_data['answer'].strip()
    if len(answer) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide a value for answer")
    all_answers = Answer.read_all(db.cur, question_id)

    # make sure the question for which the answer is to be posted is present
    question = Question.read_one(db.cur, question_id)
    if question is not None:
        for ans in all_answers:
            if ans.answer.strip().lower() == answer.strip().lower():  # check if value already exists
                return Validator.custom_response(409, 'Conflict', "Duplicate Value. Answer already exists")
        accepted = 'false'
        date_posted = datetime.datetime.now()
        new_id = Answer(0, question_id, current_user_id, answer,
                        0, accepted, date_posted).create(db.cur)
        return jsonify(Answer(new_id, question_id, current_user_id, answer, 0, accepted, date_posted).obj_to_dict()), 201
    else:
        return Validator.custom_response(404, 'Not Found', 'Question with id:' + str(question_id) + ' does not exist')
Esempio n. 5
0
 def PUT(self, username, password, **data):
     for user in self.list:
         if user["username"] == username:
             if user["password"] != password:
                 Validator.fail("The username or password is wrong!")
             return json.dumps(user)
     Validator.fail("The username or password is wrong!")
Esempio n. 6
0
 def POST(self, **data):
     Validator.require(data, "login", "password")
     user = self.application.user.find({
         "login": data["login"],
         "password": data["password"]
     })
     if user is not None:
         return self.application.user.response(user)
     Validator.fail("The username or password is wrong!")
Esempio n. 7
0
 def GET(self, *files):
     minified = ""
     for file in files:
         file = path.join(self.js_dir, file + ".js")
         if not path.isfile(file):
             Validator.fail_found()
         with open(file) as js_file:
             minified += jsmin(js_file.read(), quote_chars="'\"`") + "\n"
     return minified
Esempio n. 8
0
    def DELETE(self, race_id, vehicle_id, **data):
        race_id = Validator.require_int(race_id)
        vehicle_id = Validator.require_int(vehicle_id)
        filter = {"race_id": race_id, "vehicle_id": vehicle_id}
        resource = self.find(filter)
        if resource is not None:
            response = deepcopy(resource)
            self.remove(filter)
            return self.response(response)

        Validator.fail_found()
Esempio n. 9
0
    def DELETE(self, race_id, vehicle_id, **data):
        race_id = Validator.require_int(race_id)
        vehicle_id = Validator.require_int(vehicle_id)
        filter = {"race_id": race_id, "vehicle_id": vehicle_id}
        resource = self.find(filter)
        if resource is not None:
            response = deepcopy(resource)
            self.remove(filter)
            return self.response(response)

        Validator.fail_found()
Esempio n. 10
0
    def GET(self, race_id=None, vehicle_id=None, **data):
        if vehicle_id is None:
            if race_id is None:
                return self.response(self.sort(self.findall(data)))
            race_id = Validator.require_int(race_id)
            data["race_id"] = race_id
            return self.response(self.sort(self.findall(data)))
        vehicle_id = Validator.require_int(vehicle_id)

        resource = self.find({"race_id": race_id, "vehicle_id": vehicle_id})

        return self.response(resource)
Esempio n. 11
0
    def GET(self, race_id=None, vehicle_id=None, **data):
        if vehicle_id is None:
            if race_id is None:
                return self.response(self.sort(self.findall(data)))
            race_id = Validator.require_int(race_id)
            data["race_id"] = race_id
            return self.response(self.sort(self.findall(data)))
        vehicle_id = Validator.require_int(vehicle_id)

        resource = self.find({"race_id": race_id, "vehicle_id": vehicle_id})

        return self.response(resource)
Esempio n. 12
0
def api_update_answer(question_id, answer_id):
    """Update an answer to a specific question"""

    # get new answer values
    input_data = request.get_json(force=True)

    all_answers = Answer.read_all(db.cur, question_id)
    if all_answers is not None:
        for ans in all_answers:
            if ans.id == answer_id:  # check if answer exists
                # replace old values with new ones if available
                answer_edited = False
                if 'accepted' in input_data.keys():
                    new_accepted_value = input_data['accepted']  # boolean
                    # validate accepted value (must be a valid boolean value for postgres)
                    if isinstance(new_accepted_value, bool):
                        # make sure it's the user who posted the question accepting the answer
                        qn = Question.read_one(db.cur, question_id)
                        if qn.user_id != get_jwt_identity():
                            return Validator.custom_response(403, 'Forbidden',
                                                             "You do not have permission to accept this answer")
                        ans.accepted = new_accepted_value
                        answer_edited = True
                    else:
                        return Validator.custom_response(400, 'Bad Request',
                                                         "Provide 'accepted' data as a boolean (true OR false)")
                if 'answer' in input_data.keys():
                    new_answer_value = input_data['answer'].strip()
                    if len(new_answer_value) == 0:
                        return Validator.custom_response(400, 'Bad Request', "Provide a value for 'answer'")
                    if ans.user_id != get_jwt_identity():  # only the answer owner can edit it
                        return Validator.custom_response(403, 'Forbidden',
                                                         "You do not have permission to edit this answer")
                    ans.answer = new_answer_value
                    answer_edited = True

                if 'vote' in input_data.keys():
                    new_vote_value = input_data['vote']  # boolean
                    if isinstance(new_vote_value, bool):
                        if new_vote_value:
                            ans.votes += 1  # add a vote
                        else:
                            ans.votes -= 1  # remove a vote
                        answer_edited = True
                    else:
                        return Validator.custom_response(400, 'Bad Request',
                                                         "Provide 'vote' data as a boolean (true OR false)")

                if answer_edited:
                    ans.update(db.cur)
                    return jsonify(ans.obj_to_dict()), 202  # HTTP_202_ACCEPTED
                else:
                    return Validator.custom_response(400,
                                                     'Bad Request',
                                                     """Provide 'answer' data to edit answer, OR 'accepted' data (as a boolean) to edit accepted status OR 'vote' data (as a boolean) to up-vote or down-vote""")

        # Answer does not exist
        return Validator.custom_response(404, 'Not Found', 'No Answer found with id, ' + str(answer_id))
    else:  # Question does not exist
        return Validator.custom_response(404, 'Not Found', 'No answers for the question')
Esempio n. 13
0
 def PUT(self, race_id, vehicle_id, **data):
     race_id = Validator.require_int(race_id)
     vehicle_id = Validator.require_int(vehicle_id)
     resource = self.find({"race_id": race_id, "vehicle_id": vehicle_id})
     if resource is None:
         resource = {"race_id": race_id, "vehicle_id": vehicle_id}
         data = Validator.validate(data, self.__class__.fields, self.__class__.defaults, require_all=True)
         self.resources.append(resource)
     else:
         data = Validator.validate(data, self.__class__.fields, self.__class__.defaults, require_all=False)
     for field in data:
         resource[field] = data[field]
     self.save()
     return self.response(resource)
class RequestHandler():
    def __init__(self, form_data):
        self.validator = Validator()
        self.form_data = html.unescape(form_data)

    def extract_user_data(self):
        data_list = self.form_data.split(' ')
        user_email = data_list[0]
        product_url = data_list[1]
        return user_email, product_url

    def handle_request(self):
        user_email, product_url = self.extract_user_data()
        input_valid, error_message = self.validator.validate_user_input(
            user_email, product_url)
        if input_valid == False:
            return False, error_message

        # if input is valid i.e: input_valid == True
        entry_handler = EntryHandler()
        entry_added = entry_handler.add_entry(user_email, product_url)
        if entry_added == False:
            error_message = '* This exact user email and product url have been registered before'
            return False, error_message

        # if input is valid and teh entry was successfully added to the db
        message = "* We will email you when the product's price fall"
        return True, message
Esempio n. 15
0
 def login():
     db = DatabaseConnection()
     user_input = request.get_json(force=True)
     username = user_input.get("user_name")
     password = user_input.get("user_password")
     validate = Validator.validate_user_login_credentials(
         username, password)
     if validate:
         return validate
     user = db.get_user(username)
     if user:
         verify_password = User_Controller.verify_hash(password, user[4])
         if verify_password:
             select = db.login_user(username, verify_password)
             if select:
                 expiry = datetime.timedelta(days=1)
                 user_data = {
                     "username": username,
                     "id": user[0],
                     "role": user[5]
                 }
                 access_token = create_access_token(identity=user_data,
                                                    expires_delta=expiry)
                 return jsonify({
                     'success':
                     f"You have successfully been logged in as {username}",
                     'access_token': access_token
                 }), 200
         return jsonify({'message': 'Incorrect user name or password'}), 400
     return jsonify({'message': f"{username} does not exist"}), 400
Esempio n. 16
0
class TestValidator(unittest.TestCase):
    def setUp(self):
        self.validator = Validator()
        self.test_records = [
            Record(**x).record for x in [test_record, test_record]
        ]

    def test_parse_empty(self):
        results = self.validator.validate()
        self.assertEqual(results['no_errors'], True)
        self.assertEqual(results['results'], {})

    def test_parse_one(self):
        with app.app.test_request_context('/'):
            results = self.validator.validate(
                records=self.test_records)
        self.assertEqual(results['no_errors'], True)
Esempio n. 17
0
 def is_admin(self, **data):
     if "user_id" not in data or data is None:
         return False
     user_id = Validator.require_int(data["user_id"])
     if 0 <= user_id < len(self.list):
         user = self.list[user_id]
         if user["role"] == "ADMIN":
             return True
     return False
Esempio n. 18
0
def api_delete_question(question_id):
    """Delete a specific question based on id"""

    # get object from database
    all_questions = Question.read_all(db.cur)
    if all_questions is not None:
        for qn in all_questions:
            if qn.id == question_id:
                # only the owner of the question can delete it
                if qn.user_id != get_jwt_identity():
                    return Validator.custom_response(403, 'Forbidden',
                                                     "You do not have permission to delete this question")
                qn.delete(db.cur)
                return Validator.custom_response(202, 'Accepted',
                                                 'Question with id, ' + str(question_id) + ' was deleted')
        return Validator.custom_response(404, 'Not Found', 'No question in store matching the id')
    else:
        return Validator.custom_response(200, 'OK', 'Request Successful BUT There are no Questions in store')
Esempio n. 19
0
def api_add_question():
    """Post / Add a new question"""

    # get id of user currently logged in (from authentication token) and save it alongside the question
    current_user_id = get_jwt_identity()
    input_data = request.get_json(force=True)
    if 'question' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'question' data")
    question = input_data['question'].strip()
    if len(question) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide a value for question")
    all_questions = Question.read_all(db.cur)
    if all_questions is not None:
        for qn in all_questions:
            if qn.question.strip().lower() == question.strip().lower():  # check if question already exists
                return Validator.custom_response(409, 'Conflict', "Duplicate Value. Question already exists")
    date_posted = datetime.datetime.now()
    new_id = Question(0, current_user_id, question, date_posted).create(db.cur)
    # 201 = created
    return jsonify(Question(new_id, current_user_id, question, date_posted).obj_to_dict()), 201
Esempio n. 20
0
 def is_module_admin(self, module_id=None, **data):
     if "user_id" not in data or data is None:
         return False
     user_id = Validator.require_int(data["user_id"])
     if 0 <= user_id < len(self.list):
         user = self.list[user_id]
         if user["role"] != "ADMIN" and module_id is not None:
             for u_module_id in user["module"]:
                 if u_module_id == module_id:
                     return True
             return False
         return True
     return False
Esempio n. 21
0
def api_get_one_question(question_id):
    """Get a specific question using its id. Also fetch all answers for the question"""

    questions_with_answers = dict()
    question_obj = Question.read_one(db.cur, question_id)
    if question_obj is None:
        return Validator.custom_response(404, 'Not Found', 'Question with id:' + str(question_id) + ' does not exist')

    # get all answers for the question
    questions_with_answers['question'] = question_obj.obj_to_dict()
    answers_list = Answer.read_all(db.cur, question_id)
    if answers_list is not None:
        list_of_answer_dicts = [answer_obj.obj_to_dict()
                                for answer_obj in answers_list]
        if len(list_of_answer_dicts) > 0:
            questions_with_answers['answers'] = list_of_answer_dicts

    return jsonify(questions_with_answers), 200
 def change_parcel_destination(parcel_id):
     """Change the destination of a parcel delivery order"""
     current_user = get_jwt_identity()
     user_input = request.get_json(force=True) 
     parcel = db.get_a_parcel(parcel_id)
     if parcel:
         if current_user.get('id') == parcel[2]:
             destination = user_input.get('destination')
             price = user_input.get('total_price')
             validated_destination = Validator.validate_str_to_change(destination)
             if validated_destination:
                 return validated_destination   
             if parcel[10] == 'cancelled' or parcel[10] == 'delivered':  
                 return jsonify({"message":f"Destination of parcel {parcel_id} can not be changed because it was cancelled or delivered"}), 400
             destination_change = db.change_destination(parcel_id, destination, price)
             if destination_change:
                 return jsonify({"message":f"Destination of parcel {parcel_id} changed to {destination}"}), 200  
         return jsonify({'message':f"Invalid request! You do not have rights to change the destination of a parcel"}), 401 
     return jsonify({'message':f"There is no parcel with ID {parcel_id}"}), 404
 def change_present_location(parcel_id):
     """Change the present location of a parcel delivery order"""
     current_user = get_jwt_identity()
     user_input = request.get_json(force=True) 
     parcel = db.get_a_parcel(parcel_id)
     if parcel:
         if current_user.get('role') == True:
             present_location = user_input.get('present_location')
             validated_location = Validator.validate_str_to_change(present_location)
             if validated_location:
                 return validated_location
             if parcel[10] == 'cancelled' or parcel[10] == 'delivered':  
                 return jsonify({"message":f"Present location of parcel {parcel_id} can not be changed because it was cancelled or delivered"}), 400 
             location_change = db.change_location(parcel_id, present_location)
             if location_change:
                 if present_location != parcel[7]:
                     db.change_status(parcel_id, 'intransit')
                 elif present_location == parcel[7]:
                     db.change_status(parcel_id, 'delivered')
                 return jsonify({"message":f"Present location of parcel {parcel_id} changed to {present_location}"}), 200
         return jsonify({'message':'Invalid request! You do not have rights to change the present location of a parcel'}), 401
     return jsonify({'message':f"There is no parcel with ID {parcel_id}"}), 404
Esempio n. 24
0
    def sign_up():
        """Register a user"""
        # db = DatabaseConnection()
        user_input = request.get_json(force=True)
        user_name = user_input.get("user_name")
        user_email = user_input.get("user_email")
        user_mobile = user_input.get("user_mobile")
        user_password = user_input.get("user_password")
        users = db.get_users()
        for user in users:
            if user_name == user[1]:
                return jsonify({'message':
                                f"User {user_name} already exists"}), 400
            if user_email == user[2]:
                return jsonify({'message':
                                "Email belongs to another account"}), 400

        validate_credentials = Validator.validate_user_credentials(
            user_name, user_email, user_password, user_mobile)
        if validate_credentials is not None:
            return validate_credentials
        if len(str(user_password)) < 9:
            return jsonify(
                {'message':
                 'Password must be more than 8 characters long'}), 400
        mail = ['@', '.com']
        for m in mail:
            if not m in user_email:
                return jsonify({'message': 'Please enter a valid email'}), 400

        user_password = User_Controller.generate_hash(user_password)
        new_user = User(user_name, user_email, user_mobile, user_password)
        db.insert_user(new_user.user_name, new_user.user_email,
                       new_user.user_mobile, new_user.user_password)
        return jsonify({"message":
                        f"User {user_name} successfully created"}), 201
    def create_parcel():
        """Create a parcel delivery order"""
        user_input = request.get_json(force=True)
        current_user = get_jwt_identity()
        # descriptions = ["Electronics", "Perishable goods", "Furniture", "Home appliances",
        #                 "Clothing", "Bags and shoes", "Toys"]  
        user_id = current_user.get('id')
        user_name = current_user.get('username')
        recipient_name = user_input.get("recipient_name")
        recipient_mobile = user_input.get("recipient_mobile")
        pickup_location = user_input.get("pickup_location")
        destination = user_input.get("destination")
        weight = user_input.get("weight")
        total_price = Parcel.get_delivery_price(weight)
        description = user_input.get("description")
        # if not description in descriptions:
        #     return jsonify({"message": f"Description can only be {descriptions}"}), 400

        parcel_dict = {
            "description": description,
            "recipient_name": recipient_name,
            "recipient_mobile": recipient_mobile,
            "pickup_location" : pickup_location,
            "destination": destination,
            "weight": weight,
            "total_price": total_price
        }
        validate_parcel = Validator.validate_parcel(parcel_dict)
        # if validate_parcel:
        #     return validate_parcel
        msgs_list = validate_parcel['message']
        if len(msgs_list) > 0:
            return jsonify(validate_parcel), 400
        parcel = Parcel(user_id, user_name, parcel_dict)
        db.add_parcel(parcel.description, parcel.user_id, parcel.user_name, parcel.recipient_name, parcel.recipient_mobile, pickup_location, parcel.destination, parcel.weight, parcel.total_price)
        return jsonify({"message":"Parcel delivery order successfully made"}), 201
 def __init__(self, form_data):
     self.validator = Validator()
     self.form_data = html.unescape(form_data)
Esempio n. 27
0
 def setUp(self):
     self.validator = Validator()
     self.test_records = [
         Record(**x).record for x in [test_record, test_record]
     ]
Esempio n. 28
0
def gemeente_stemlokalen_dashboard():
    # Select a gemeente if none is currently selected
    if not 'selected_gemeente_code' in session:
        return redirect(url_for('gemeente_selectie'))

    gemeente = Gemeente.query.filter_by(
        gemeente_code=session['selected_gemeente_code']).first()
    elections = gemeente.elections.all()

    # Pick the first election. In the case of multiple elections we only
    # retrieve the stembureaus of the first election as the records for
    # both elections are the same (at least the GR2018 + referendum
    # elections on March 21st 2018).
    verkiezing = elections[0].verkiezing

    all_publish_records = ckan.get_records(
        ckan.elections[verkiezing]['publish_resource'])
    all_draft_records = ckan.get_records(
        ckan.elections[verkiezing]['draft_resource'])

    gemeente_publish_records = [
        record for record in all_publish_records['records']
        if record['CBS gemeentecode'] == gemeente.gemeente_code
    ]
    gemeente_draft_records = [
        record for record in all_draft_records['records']
        if record['CBS gemeentecode'] == gemeente.gemeente_code
    ]

    _remove_id(gemeente_publish_records)
    _remove_id(gemeente_draft_records)

    toon_stembureaus_pagina = False
    if gemeente_publish_records:
        toon_stembureaus_pagina = True

    show_publish_note = False
    if gemeente_draft_records != gemeente_publish_records:
        show_publish_note = True

    vooringevuld = ''
    vooringevuld_fn = (
        'files/deels_vooringevuld/waarismijnstemlokaal.nl_invulformulier_%s_'
        'deels_vooringevuld.xlsx' % (gemeente.gemeente_naam))
    if os.path.exists(vooringevuld_fn):
        vooringevuld = vooringevuld_fn

    form = FileUploadForm()

    # Save, parse and validate an uploaded spreadsheet and save the
    # stembureaus
    if form.validate_on_submit():
        f = form.data_file.data
        filename = secure_filename(f.filename)
        filename = '%s__%s' % (gemeente.gemeente_code, filename)
        file_path = os.path.join(
            os.path.abspath(os.path.join(app.instance_path, '../upload')),
            filename)
        f.save(file_path)
        parser = UploadFileParser()
        app.logger.info('Processing uploaded file for %s' %
                        (gemeente.gemeente_naam))
        try:
            records = parser.parse(file_path)
        except ValueError as e:
            app.logger.warning('Upload failed: %s' % e)
            flash(
                Markup(
                    '<span class="text-red">Uploaden mislukt</span>. Het '
                    'lijkt er op dat u geen gebruik maakt van (de meest '
                    'recente versie van) de stembureau-spreadsheet. Download '
                    'een <a href="/files/waarismijnstemlokaal.nl_'
                    'invulformulier.xlsx"><b>leeg</b></a> of <a href="%s"><b>'
                    'deels vooringevuld</b></a> stembureau-spreadsheet en vul '
                    'de gegevens volgens de instructies in de spreadsheet in '
                    'om deze vervolgens op deze pagina te '
                    'uploaden.' % (vooringevuld)))
            return render_template(
                'gemeente-stemlokalen-dashboard.html',
                verkiezing_string=_format_verkiezingen_string(elections),
                gemeente=gemeente,
                total_publish_records=len(gemeente_publish_records),
                total_draft_records=len(gemeente_draft_records),
                form=form,
                show_publish_note=show_publish_note,
                vooringevuld=vooringevuld,
                toon_stembureaus_pagina=toon_stembureaus_pagina,
                upload_deadline_passed=check_deadline_passed())

        validator = Validator()
        results = validator.validate(records)

        # If the spreadsheet did not validate then return the errors as
        # flash messages
        if not results['no_errors']:
            flash(
                Markup(
                    '<span class="text-red">Uploaden mislukt</span>. Los de '
                    'hieronder getoonde foutmeldingen op en upload de '
                    'spreadsheet opnieuw.'
                    '<br><br>'))
            for column_number, col_result in sorted(
                    results['results'].items()):
                if col_result['errors']:
                    error_flash = (
                        '<b>Foutmelding(en) in <span class="text-red">'
                        'invulveld %s (oftewel kolom "%s")</span></b>:' %
                        (column_number - 5, _colnum2string(column_number)))
                    error_flash += '<ul>'
                    for column_name, error in col_result['errors'].items():
                        error_flash += '<li>%s: %s</li>' % (column_name,
                                                            error[0])
                    error_flash += '</ul><br>'
                    flash(Markup(error_flash))
        # If there not a single value in the results then state that we
        # could not find any stembureaus
        elif not results['found_any_record_with_values']:
            flash(
                Markup(
                    '<span class="text-red">Uploaden mislukt</span>. Er zijn geen '
                    'stembureaus gevonden in de spreadsheet.'))
        # If the spreadsheet did validate then first delete all current
        # stembureaus from the draft_resource and then save the newly
        # uploaded stembureaus to the draft_resources of each election
        # and finally redirect to the overzicht
        else:
            # Delete all stembureaus of current gemeente
            if gemeente_draft_records:
                for election in [x.verkiezing for x in elections]:
                    ckan.delete_records(
                        ckan.elections[election]['draft_resource'],
                        {'CBS gemeentecode': gemeente.gemeente_code})

            # Create and save records
            for election in [x.verkiezing for x in elections]:
                records = []
                for _, result in results['results'].items():
                    if result['form']:
                        records.append(
                            _create_record(result['form'], result['uuid'],
                                           gemeente, election))
                ckan.save_records(ckan.elections[election]['draft_resource'],
                                  records=records)

            flash(
                'Het uploaden van stembureaus is gelukt! Controleer in het '
                'overzicht hieronder of alles klopt en voer eventuele '
                'wijzigingen door. Klik vervolgens op de "Publiceer"-knop als '
                'alles klopt.')
            return redirect(url_for('gemeente_stemlokalen_overzicht'))

    return render_template(
        'gemeente-stemlokalen-dashboard.html',
        verkiezing_string=_format_verkiezingen_string(elections),
        gemeente=gemeente,
        total_publish_records=len(gemeente_publish_records),
        total_draft_records=len(gemeente_draft_records),
        form=form,
        show_publish_note=show_publish_note,
        vooringevuld=vooringevuld,
        toon_stembureaus_pagina=toon_stembureaus_pagina,
        upload_deadline_passed=check_deadline_passed())
Esempio n. 29
0
def api_get_answers(question_id):
    """Get all answers to a specific question"""
    return Validator.check_for_content(Answer.read_all(db.cur, question_id), 'There are no Answers for this question')
Esempio n. 30
0
 def POST(self, **data):
     Validator.require(data, "login", "password")
     user = self.application.user.find({"login": data["login"], "password": data["password"]})
     if user is not None:
         return self.application.user.response(user)
     Validator.fail("The username or password is wrong!")
Esempio n. 31
0
def api_get_all_answers():
    """Get all answers"""
    return Validator.check_for_content(Answer.read_all_answers(db.cur), 'There are no Answers')
Esempio n. 32
0
def register_user():
    """Post / Add a new user"""

    # validate presence of appropriate data
    input_data = request.get_json(force=True)
    if 'full_name' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'full_name' data")
    if 'email' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'email' data")
    if 'password' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'password' data")
    if 'retype_password' not in input_data.keys():
        return Validator.custom_response(400, 'Bad Request', "Request must contain 'retype_password' data")

    password = input_data['password']
    if len(str(password)) < 6:
        return Validator.custom_response(400, 'Bad Request', "Password must be at least 6 characters long")
    full_name = input_data['full_name']
    if len(str(full_name).strip()) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide a name")
    email = input_data['email']
    if len(str(email).strip()) == 0:
        return Validator.custom_response(400, 'Bad Request', "Provide an email address")
    # email validator
    if not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]+$", email):
        return Validator.custom_response(400, 'Bad Request', "Invalid email format")
    retype_password = input_data['retype_password']
    if len(str(retype_password)) == 0:
        return Validator.custom_response(400, 'Bad Request', "Retype password")

    # check if user already exists (compare emails)
    all_users = User.read_all(db.cur)
    if all_users is not None:
        for user in all_users:
            if user.email.strip().lower() == email.strip().lower():
                return Validator.custom_response(409, 'Conflict', "Duplicate Value. Email Address is already taken")

    # check if passwords match
    if password != retype_password:
        return Validator.custom_response(400, 'Bad Request', "Password mismatch")

    # if all is well; Add to database and return new id
    new_id = User(0, full_name, email, password).create(db.cur)
    user_dict = User(new_id, full_name, email,
                     sha256.hash(password)).obj_to_dict()

    # create token
    access_token = create_access_token(identity=new_id, expires_delta=False)
    user_dict['access_token'] = access_token
    user_dict['msg'] = 'User Registration Successful!'
    return jsonify(user_dict), 201
Esempio n. 33
0
def api_get_all_questions():
    """Get all questions"""
    return Validator.check_for_content(Question.read_all(db.cur), 'There are no Questions in store')
Esempio n. 34
0
def page_not_found(e):  # Page not found
    return Validator.custom_response(404, 'Resource Not Found',
                                     'You are trying to access a resource that does not exist')
Esempio n. 35
0
def bad_request(e):  # Bad request e.g. missing JSON post request data
    return Validator.custom_response(400, 'Bad request', 'Provide POST request data as valid JSON')
Esempio n. 36
0
 def api_create(self, **data):
     fillable = Validator.validate(data, self.__class__.fields, self.__class__.defaults)
     if self.find({"login": fillable["login"]}) is not None:
         Validator.fail('Der Benutzername ist bereits vergeben.');
     resource = self.create(fillable)
     return resource
Esempio n. 37
0
def upload_stembureau_spreadsheet(gemeente_code, file_path):
    """
    Uploads a stembureau spreadheet, specify full absolute file_path
    """
    current_gemeente = _get_gemeente(gemeente_code)

    elections = current_gemeente.elections.all()
    # Pick the first election. In the case of multiple elections we only
    # retrieve the stembureaus of the first election as the records for
    # both elections are the same (at least the GR2018 + referendum
    # elections on March 21st 2018).
    verkiezing = elections[0].verkiezing
    all_draft_records = ckan.get_records(
        ckan.elections[verkiezing]['draft_resource']
    )
    gemeente_draft_records = [
        record for record in all_draft_records['records']
        if record['CBS gemeentecode'] == current_gemeente.gemeente_code
    ]
    _remove_id(gemeente_draft_records)

    parser = UploadFileParser()
    app.logger.info(
        'Manually (CLI) uploading file for '
        '%s' % (current_gemeente.gemeente_naam)
    )
    try:
        records = parser.parse(file_path)
    except ValueError as e:
        app.logger.warning('Manual upload failed: %s' % e)
        return

    validator = Validator()
    results = validator.validate(records)

    # If the spreadsheet did not validate then return the errors
    if not results['no_errors']:
        print(
            'Upload failed. Fix the errors shown below and try again.\n\n'
        )
        for column_number, col_result in sorted(
                results['results'].items()):
            if col_result['errors']:
                print(
                    'Error(s) in '
                    'invulveld %s:' % (
                        column_number - 5
                    )
                )
                for column_name, error in col_result['errors'].items():
                    print(
                        '%s: %s\n' % (
                            column_name, error[0]
                        )
                    )
    # If there is not a single value in the results then state that we
    # could not find any stembureaus
    elif not results['found_any_record_with_values']:
        print(
            'Upload failed. No stembureaus have been found in this '
            'spreadsheet.'
        )
    # If the spreadsheet did validate then first delete all current
    # stembureaus from the draft_resource and then save the newly
    # uploaded stembureaus to the draft_resources of each election
    else:
        # Delete all stembureaus of current gemeente
        if gemeente_draft_records:
            for election in [x.verkiezing for x in elections]:
                ckan.delete_records(
                    ckan.elections[election]['draft_resource'],
                    {
                        'CBS gemeentecode': current_gemeente.gemeente_code
                    }
                )

        # Create and save records
        for election in [x.verkiezing for x in elections]:
            records = []
            for _, result in results['results'].items():
                if result['form']:
                    records.append(
                        _create_record(
                            result['form'],
                            result['uuid'],
                            current_gemeente,
                            election
                        )
                    )
            ckan.save_records(
                ckan.elections[election]['draft_resource'],
                records=records
            )
        print('Upload succesful!')
    print('\n\n')