def delete_party(_id): """delete the selected party Returns: 1. json : response message o details in json format """ # check if party to delete exists party_to_delete_query = Party.get_party_by_id(_id) party_to_delete = db().get_single_row(*party_to_delete_query) if party_to_delete: # delete found party query, value = Party.delete_party(_id) db().commit_changes(query, value) return jsonify({ "status": 200, "data": [{ "message": "Political Party deleted successfully." }] }), 200 else: # response message when delete fails. return jsonify({ "status": 404, "data": [{ "message": "Political Party to delete not found." }] }), 404
def save_changes(_id, data): """commit application details to the database Args: _id (integer): id of user making the application data (object): application instance """ query, values = Application.add_application(data, user_id=_id) db().commit_changes(query, values)
def save_changes(_id, data): """commit the candidate details to the database Args: _id (integer): office id from the endpoint url data ([object]): candidate instance """ query, values = Candidate.add_candidate(data, office_id=_id) db().commit_changes(query, values)
def save_changes(_id, data): """commit the vote details to the database Args: _id (integer): user id data ([object]): vote instance """ query, values = Vote.add_vote(data, user=_id) db().commit_changes(query, values)
def save_token(token): """ Method to save a token to the blacklist table when user logouts """ blacklist_token = BlacklistToken(token) # insert the token to blacklist table query, values = BlacklistToken.add_blacklist_token(blacklist_token) db().commit_changes(query, values) response_object = jsonify({ "status": 200, "message": "Successfully logged out." }) return response_object, 200
def office_result(office): """get the result set from the database Args: office (integer): the office to get results for """ # verify the token provided by user is valid response, status = get_logged_in_user(request) if status == 200: # sql query to get a user results results_query = get_office_result(office) office_result = db().get_all_rows_of_value(*results_query) if office_result: # serialize office results serialize_results = results_schema.dump(office_result) # json results response response_object = jsonify({ "status": 200, "data": serialize_results }) return response_object, 200 # when no result is returned response_object = jsonify({ "status": 404, "message": "Results requested not found." }) return response_object, 404 # if user could not be verified return response, status
def save_new_office(json_data): """ Method to save new office to list """ # Deserialize the data input against the office schema # check for validation errors try: data = office_schema.load(json_data) except ValidationError as e: return jsonify({"status": 400, "error": e.messages}), 400 office_name = data["office_name"] office_type = data["office_type"] is_occupied = data["is_occupied"] # create office object new_office = Office(office_name=office_name, office_type=office_type, is_occupied=is_occupied) return_id = save_changes(new_office) # 1. serialize the input for response # 2. return serialized and proper format json to api endpoint saved_office_query = Office.get_office_by_id(return_id) saved_office = db().get_single_row(*saved_office_query) response = office_schema.dump(saved_office) response_object = jsonify({"status": 201, "data": [response]}) return response_object, 201
def get_party_id(party_name): """gets id of the passed party name from the database Args: party_name (string): party name to query id for """ party_name_query = Party.get_party_by_name(party_name) party = db().get_single_row(*party_name_query) if party: return party['id']
def save_new_party(json_data): """saves a new party in the database Args: json_data (json) : party details Returns: json : api endpoint response """ # Deserialize the data input against the party schema # check if input values throw validation errors try: data = party_schema.load(json_data) except ValidationError as e: return jsonify({"status": 400, "error": e.messages}), 400 party_name = data['party_name'] hq_address = data['hq_address'] logo_url = data['logo_url'] # Query database for party by name party_by_name = Party.get_party_by_name(party_name) party = db().get_single_row(*party_by_name) if party is None: # if name is not taken new_party = Party(party_name=party_name, hq_address=hq_address, logo_url=logo_url) save_changes(new_party) # 1. serialize the input for response # 2. return serialized and proper format json to api endpoint party_saved = db().get_single_row(*party_by_name) response = party_schema.dump(party_saved) response_object = jsonify({"status": 201, "data": [response]}) return response_object, 201 # default response When name is taken return jsonify({ "status": 409, "error": "Try a different Party name, Provided name is taken." }), 409
def save_changes(data): """commit the petition details to the database Args: data (object): petition details """ query, values = Petition.add_petition(data) petition_id = db().commit_changes_returning_id(query, values) return petition_id
def get_office_id(office_name): """gets id of the passed office name from the database Args: office_name (string): office name oto query id for """ office_name_query = Office.get_office_by_name(office_name) office = db().get_single_row(*office_name_query) if office: return office['id']
def edit_party(_id, json_data): """ Method to apply new changes to party details """ try: data = party_schema.load(json_data, partial=True) except ValidationError as e: return jsonify({"status": 400, "error": e.messages}), 400 # check if the party with the provided party id exists. party_to_edit_query = Party.get_party_by_id(_id) party_to_edit = db().get_single_row(*party_to_edit_query) if party_to_edit: new_name = data["party_name"] # check if the provided name already exists party_by_name = Party.get_party_by_name(new_name) party = db().get_single_row(*party_by_name) if party is None: # construct update party name query query, values = Party.update_party(_id, new_name) # persist changes to the database db().commit_changes(query, values) # query back the database for the edited party. party_edited = db().get_single_row(*party_to_edit_query) return jsonify({ "status": 200, "data": [party_schema.dump(party_edited)] }) # if party name is already registered return jsonify({ "status": 409, "error": "Provided name is already taken or is the same for this party." }), 409 # response when party not found return jsonify({ "status": 404, "error": "Resource requested for edit not found." }), 404
def verify_blacklist(token): """verify provided token is not blacklisted. Get the query to run and check if the token provided is in blacklist Args: token (bytes): user token """ blacklisted_query = BlacklistToken.check_blacklist(token) is_blacklisted = db().get_single_row(*blacklisted_query) return is_blacklisted
def get_parties(): """Method to return all the parties from the database Returns: 1. json : the parties found details in json format """ parties_query = Party.get_parties_query() parties = db().get_all_rows(parties_query) response = parties_schema.dump(parties) return jsonify({"status": 200, "data": response}), 200
def check_party_is_registered(office_id, party_id): """check from the database if a party is already registered for an office Args: office_id (integer): office to check party_id (integer): party to check """ office_party_query = Candidate.get_office_party_by_id(office_id, party_id) office_party = db().get_single_row(*office_party_query) if office_party: return office_party
def check_user_is_registered(candidate_id): """Check if a candidate is already registered as a candidate Args: candidate_id (integer): the candidate unique identifier """ # query database for the candidate candidate_by_id = Candidate.get_candidate_by_id(candidate_id) candidate_registered = db().get_single_row(*candidate_by_id) if candidate_registered: return candidate_registered
def get_offices(): """Method to return all the offices from the database Returns: 1. json : the offices found details in json format """ offices_query = Office.get_offices_query() offices = db().get_all_rows(offices_query) response = offices_schema.dump(offices) return jsonify({ "status": 200, "data": response, }), 200
def get_vote_cast(user_id, office_id): """get the vote cast by a user on an office Args: user_id (integer): the user who cast the vote office_id (integer): the office vote was cast Returns: vote (dictionary): vote user cast """ cast_vote_query = Vote.get_cast_vote(user_id=user_id, office_id=office_id) cast_vote = db().get_single_row(*cast_vote_query) if cast_vote: return cast_vote
def save_new_petition(json_data): """Save the petition to the petition table and return appropriate response to endpoint Args: json_data (json): petition details. """ try: data = petition_load_schema.load(json_data) except ValidationError as e: return jsonify({"status": 400, "error": e.messages}), 400 # get petition details from the validated json input office = data["office"] contested_by = data["contested_by"] body = data["body"] evidence = data["evidence"] # check endpoint authorization res, status = get_logged_in_user(request) if status == 200: # get the user id from the decoded token created_by = res.get_json()['user'].get('user_id') new_petition = Petition(office=office, contested_by=contested_by, created_by=created_by, body=body, evidence=evidence) try: # save the petition and return the id created thereafter petition_id = save_changes(new_petition) except IntegrityError: return jsonify({ "status": 404, "message": "Office and candidate referenced does not exist." }), 404 petition_query = Petition.get_petition_by_id(petition_id) petition = db().get_single_row(*petition_query) # serialize the petition details serialized_petition = petitions_dump_schema.dump(petition) response_object = jsonify({"status": 201, "data": serialized_petition}) return response_object, 201 # if status code == 401 return res, status
def login_user(json_data): """Method checks if the user data provided is valid for login Args: data (json): User email and password """ try: data = auth_schema.load(json_data) except ValidationError as e: return jsonify({"status": 400, "error": e.messages}), 400 email = data["email"] # Query database for if provided user with email exists user_by_email = User.get_user_by_email(email) user_email = db().get_single_row(*user_by_email) if user_email: # check if password provided matches password_candidate = data['password'] user_password = user_email['password'] if User.verify_hash_password(password_candidate, user_password): # get the user id to use for token generation identifier = user_email['id'] access_token = User.encode_auth_token(identifier) response = user_schema.dump(user_email) return jsonify({ "status": 200, "message": "Successfully logged in.", "data": [{ "token": access_token.decode(), "user": [response] }] }), 200 # response for password and email missmatch return jsonify({ "status": 400, "error": "Incorrect user email or password." }), 400 # when no user with particular email exists return jsonify({"status": 404, "message": "User does not exists."}), 404
def get_office(_id): """Method to return the office from the database with the provided id Args: _id (integer): the office unique identifier Returns: 1. json : the office found details in json format 2. json : error if the office is not found """ office_query = Office.get_office_by_id(_id) office = db().get_single_row(*office_query) if office: # response when office exists return jsonify({ "status": 200, "data": [office_schema.dump(office)] }), 200 # response when offices not found return jsonify({ "status": 404, "error": "Resource /offices/{} not found".format(_id) }), 404
def get_party(_id): """Method to return the party from the database with the provided id Args: _id (integer): the party unique identifier Returns: 1. json : the party found details in json format 2. json : error if the party is not found """ party_query = Party.get_party_by_id(_id) party = db().get_single_row(*party_query) if party: # response when party exists return jsonify({ "status": 200, "data": [party_schema.dump(party)] }), 200 else: # response when party not found return jsonify({ "status": 404, "error": "Resource /parties/{} not found".format(_id) }), 404
def save_changes(data): """ Write to the mock db """ query, values = Office.add_office(data) identifier = db().commit_changes_returning_id(query, values) return identifier
def save_changes(data): """ Write to the mock db """ query, values = Party.add_party(data) db().commit_changes(query, values)
def save_new_application(json_data): """Create a user office application instance and save the data to the database Args: json_data (json): office user is vying for and the party name """ # deserialize the data input against the application schema # checks if the input values pass the field validation try: data = application_load_schema.load(json_data) except ValidationError as e: return jsonify({ "status": 400, "error": e.messages }), 400 party = data['party'] office = data['office'] # decode the auth token of logged-in user res, status = get_logged_in_user(request) if status == 200: # get user id from decoded token applicant_id = res.get_json()['user'].get('user_id') party_id = get_party_id(party) office_id = get_office_id(office) if party_id and office_id: new_application = Application( party=party_id, office=office_id ) try: save_changes(applicant_id, new_application) except IntegrityError: # Executed if the user has an application # already made before return jsonify({ "status": 400, "error": "User has an application registered already." }), 400 application_registered_query = Application.get_application( applicant_id) application_registered = db().get_single_row(*application_registered_query) response = application_dump_schema.dump(application_registered) response_object = jsonify({ "status": 201, "data": [response] }) return response_object, 201 return jsonify({ "status": 400, "error": "Party or office referenced does not exists." }), 400
def get_logged_in_user(request_header): """return the details of the logged in user Args: request_header (Response Object): flask request """ # from the request get the authorization header auth_header = request_header.headers.get('Authorization') if auth_header: try: # check if the Authorization follows the format: # 'Bearer token-value' auth_token = auth_header.split(" ")[1] except IndexError: # when no token value can be established from the Authorization # value response_object = jsonify({ 'status': 401, 'message': 'Malformed token. Check the token format.' }) return response_object, 401 else: auth_token = '' if auth_token: # check if token is blacklisted # prevents unauthorized access of resource when the user is logged out is_blacklisted = verify_blacklist(auth_token) if is_blacklisted is None: token_verified, response = verify_auth_decode(auth_token) if token_verified: user_by_id = User.get_user_by_id(response) user = db().get_single_row(*user_by_id) response_object = jsonify({ 'status': 200, 'user': { 'user_id': user['id'], 'user_email': user['email'], 'is_admin': user['isadmin'] } }) return response_object, 200 # token verification error response_object = jsonify({"status": 401, "error": response}) return response_object, 401 # if the user token is in blacklist list response_object = jsonify({ "status": 401, "error": "User is logged out, Please log in again." }) return response_object, 401 # token provided is invalid response_object = jsonify({ 'status': 401, 'message': 'Provide a valid auth token.' }) return response_object, 401
def save_new_candidate(office_id, json_data): """Create a candidate instance and save the data to database Args: office_id (integer): office the user is been registered as candidate to json_data (json): user details and party user belongs to. """ # Deserialize the data input against the candidate schema # check if input values throw validation errors try: data = candidate_load_schema.load(json_data) except ValidationError as e: return jsonify({ "status": 400, "error": e.messages }), 400 candidate = data['candidate'] party = data['party'] office = office_id # check if the office and part provied are have a candidate under a certain # party party_represented = check_party_is_registered(office_id=office, party_id=party) # check if the candidate provided is already registered # in another office registered_candidate = check_user_is_registered(candidate) if party_represented is None and registered_candidate is None: new_candidate = Candidate( candidate=candidate, party=party ) try: save_changes(_id=office_id, data=new_candidate) except IntegrityError: # json when integrityError in the database is raised caused by # foreign key referencing response_object = jsonify({ "status": 409, "error": "Party, office or user referenced does not exists." }) return response_object, 409 else: response_object = jsonify({ "status": 409, "error": "Party or user exists under an office." }) return response_object, 409 # query serialize the results from the database candidate_by_id = Candidate.get_candidate_by_id(candidate) candidate_registered = db().get_single_row(*candidate_by_id) response = candidate_dump_schema.dump(candidate_registered) response_object = jsonify({ "status": 201, "data": [response] }) return response_object, 201