def post(self): """Refresh an existing token.""" post_data = request.get_json() refresh_token = post_data.get("refresh_token") response_object = {} try: resp = User.decode_token(refresh_token) user = get_user_by_id(resp) if not user: auth_namespace.abort(401, "Invalid token") access_token = user.encode_token(user.id, "access") refresh_token = user.encode_token(user.id, "refresh") response_object = { "access_token": access_token.decode(), "refresh_token": refresh_token.decode(), } return response_object, 200 except jwt.ExpiredSignatureError: auth_namespace.abort(401, "Signature expired. Please log in again.") return "Signature expired. Please log in again." except jwt.InvalidTokenError: auth_namespace.abort(401, "Invalid token. Please log in again.")
def put(self, event_id): """Updates an event.""" event = get_event_by_id(event_id) if not event: events_namespace.abort(404, f"Event {event_id} does not exist") post_data = request.get_json() description = post_data.get("description") or event.description points = post_data.get("points") or event.points current_points = post_data.get( "current_points") or event.current_points status = post_data.get("status") or event.status response_object = {} update_event(event, description, points, current_points, status) user_record = get_user_by_id(user_id) if user_record.get_points_alert and points != event.points: try: # Req Change 3: msg = "You now have " + points + " points in the GoodDriver App." send_email(email, "Points updated in GoodDriver App", msg) except: pass response_object["message"] = f"{event.id} was updated!" return response_object, 200
def delete(self, affiliation_id): """Updates an affiliation.""" response_object = {} affiliation = get_affiliation_by_id(affiliation_id) if not affiliation: affiliations_namespace.abort(404, f"Affiliation does not exist") user = get_user_by_id(affiliation.user_id) if not user: users_namespace.abort( 404, f"User {affiliation.user_id} does not exist") try: msg = "Affiliation number " + str( affiliation.id) + " has been deleted from the GoodDriver App." send_email("*****@*****.**", "User affiliation deleted.", msg) # Req Change 3: send_email(user.email, "User affiliation removed from GoodDriver App", msg) except: pass response_object[ "message"] = f" Affiliation {affiliation_id} was removed!" delete_affiliation(affiliation) return response_object, 200
def get(self, user_id): """Returns a single user.""" user = get_user_by_id(user_id) if not user: namespace.abort(404, f"User with id {user_id} does not exists") return user, 200
def post(self): """Creates a new message.""" post_data = request.get_json() thread_id = post_data.get("thread_id") sender_id = post_data.get("sender_id") recipient_id = post_data.get("recipient_id") created_date = datetime.datetime.now() subject = post_data.get("subject") content = post_data.get("content") order_id = post_data.get("order_id") response_object = {} add_message(thread_id, sender_id, recipient_id, subject, content, created_date) user_record = get_user_by_id(recipient_id) if user_record.get_problem_alert: try: # Req Change 3: msg = f"There was a problem with your order, number {str(order_id)}. Please contact your manager." send_email(user_record.email, "Problem with order in GoodDriver App", msg) except: pass response_object["message"] = f"Message was added!" return response_object, 201
def put(self, user_id): """Updates a user.""" print(f"User: {user_id}") user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") post_data = request.get_json() username = post_data.get("username") or user.username email = post_data.get("email") or user.email role = post_data.get("role") or user.role get_points_alert = post_data.get("get_points_alert") if post_data.get( "get_points_alert") == True or post_data.get( "get_points_alert") == False else user.get_points_alert get_order_alert = post_data.get("get_order_alert") if post_data.get( "get_order_alert") == True or post_data.get( "get_order_alert") == False else user.get_order_alert get_problem_alert = post_data.get( "get_problem_alert" ) if post_data.get("get_problem_alert") == True or post_data.get( "get_problem_alert") == False else user.get_problem_alert preferred_contact = post_data.get( "preferred_contact") or user.preferred_contact sponsor_logo = post_data.get("sponsor_logo") or user.sponsor_logo sponsor_headline = post_data.get( "sponsor_headline") or user.sponsor_headline sponsor_slug = post_data.get("sponsor_slug") or user.sponsor_slug response_object = {} update_user(user, username, email, role, get_points_alert, get_order_alert, get_problem_alert, preferred_contact, sponsor_logo, sponsor_headline, sponsor_slug) response_object["message"] = f"{user.id} was updated!" return response_object, 200
def get_id(id): user = get_user_by_id(id) if not user: response_object["message"] = f"{id} was not found!" return response_object, 404 data = user.to_json() response = jsonify(data) return response
def delete(self, user_id): response_object = {} user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") delete_user(user) response_object["message"] = f"{user.email} was removed!" return response_object, 200
def delete_id(id): response_object = {} user = get_user_by_id(id) if not user: response_object["message"] = f"{user.id} was not found!" return response_object, 404 delete_user(user) response_object["message"] = f"{user.id} was removed!" return response_object, 200
def put(self, user_id): post_data = request.get_json() username = post_data.get("username") email = post_data.get("email") response_object = {} user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") update_user(user, username, email) response_object["message"] = f"{user.id} was updated!" return response_object, 200
def put_id(id): put_data = request.get_json() username = put_data.get("username") email = put_data.get("email") response_object = {} user = get_user_by_id(id) if not user: response_object["message"] = f"{user.id} was not found!" return response_object, 404 update_user(user, username, email) response_object["message"] = f"{user.id} was updated!" return response_object, 200
def delete(self, user_id): """Deletes the user. Args: user_id (int): numeric user identifier """ user = get_user_by_id(user_id) if not user: namespace.abort(404, f"User with id {user_id} does not exists") delete_user(user) return { "message": f"{user.email} was deleted", "status": "success" }, 200
def put(self, affiliation_id): """Updates an affiliation.""" affiliation = get_affiliation_by_id(affiliation_id) if not affiliation: affiliations_namespace.abort(404, f"Affiliation does not exist") post_data = request.get_json() user_id = post_data.get("user_id") or affiliation.user_id sponsor_name = post_data.get( "sponsor_name") or affiliation.sponsor_name current_points = post_data.get( "current_points") or affiliation.current_points status = post_data.get("status") or affiliation.status response_object = {} user = get_user_by_id(affiliation.user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") # Alert if points change if user.get_points_alert and current_points != affiliation.current_points: print(f"Email sent") try: # Req Change 3: msg = f"\nYou now have {str(current_points)} points in the GoodDriver App." send_email(user.email, "GoodDriver App points were updated", msg) except: pass ## TO DO ## ## Alert if dropped by sponsor ## Alert if added by sponsor update_affiliation(affiliation, user_id, sponsor_name, current_points, status) response_object[ "message"] = f"Affiliation {affiliation_id} was updated!" return response_object, 200
def get(self): auth_header = request.headers.get("Authorization") or "" if auth_header: try: access_token = auth_header.split(" ")[1] user_id = User.decode_token(access_token) user = get_user_by_id(user_id) if not user: namespace.abort(401, "Invalid token") return user, 200 except jwt.ExpiredSignatureError: namespace.abort(401, "Token expired") except jwt.InvalidTokenError: namespace.abort(401, "Invalid token") except IndexError: namespace.abort(401, "Invalid token") else: namespace.abort(403, "Access token required")
def get(self): auth_header = request.headers.get("Authorization") if auth_header: try: access_token = auth_header.split(" ")[1] resp = User.decode_token(access_token) user = get_user_by_id(resp) if not user: auth_namespace.abort(401, "Invalid token") return user, 200 except jwt.ExpiredSignatureError: auth_namespace.abort( 401, "Signature expired. Please log in again.") return "Signature expired. Please log in again." except jwt.InvalidTokenError: auth_namespace.abort(401, "Invalid token. Please log in again.") else: auth_namespace.abort(403, "Token required")
def get(self, user_id, caller_id): """Returns all events for a single user that are authorized for the caller.""" authorized_list = get_all_events_by_user_id(user_id) if user_id == caller_id: return authorized_list, 200 else: caller = get_user_by_id(caller_id) if caller.role == 'admin': return authorized_list, 200 elif caller.role == 'driver': events_namespace.abort(404, f"Unauthorized request") else: caller = get_all_affiliations_by_user(caller_id) filtered_list = [] for item in authorized_list: if item.sponsor_name == caller[0].sponsor_name: filtered_list.append(item) return filtered_list, 200
def put(self, user_id): """Updates the user.""" payload = request.get_json() username = payload.get("username") email = payload.get("email") user = get_user_by_id(user_id) if not user: namespace.abort(404, f"User with id {user_id} does not exists") if get_user_by_email(email) != user: namespace.abort(400, f"{email} is already taken") update_user(user, username, email) return { "message": f"User {email} was updated", "status": "success" }, 200
def delete(self, user_id): """Updates a user.""" response_object = {} user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") delete_user(user) response_object["message"] = f"{user.email} was removed!" try: msg = "Account number " + str( user_id) + " has been deleted from the GoodDriver App." send_email("*****@*****.**", "User account deleted.", msg) # Req Change 3: send_email( user.email, "User account removed from GoodDriver App", "Your account has been deleted from the GoodDriver App.") except: pass return response_object, 200
def post(self): """Creates a new event.""" post_data = request.get_json() description = post_data.get("description") points = post_data.get("points") user_id = post_data.get("user_id") sponsor_name = post_data.get("sponsor_name") response_object = {} add_event(description, points, user_id, sponsor_name) # Update points on user record user = get_user_by_id(user_id) user_affiliations = get_all_affiliations_by_user(user_id) user_record = {} for item in user_affiliations: if item.sponsor_name == sponsor_name: user_record = item user_id = user_record.user_id sponsor_name = user_record.sponsor_name updated_points = item.current_points + points # current_points = updated_points status = user_record.status update_affiliation(user_record, user_id, sponsor_name, updated_points, status) if user.get_points_alert: try: # Req Change 3: msg = "You now have " + updated_points + " points in the GoodDriver App." send_email(user.email, "Points updated in GoodDriver App", msg) except: pass response_object["message"] = f"Event was added!" return response_object, 201
def put(self, user_id): """Updates a user's password.""" user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") post_data = request.get_json() current_password = post_data.get("current_password") new_password = post_data.get("new_password") response_object = {} new_pwhash = bcrypt.generate_password_hash( new_password, current_app.config.get("BCRYPT_LOG_ROUNDS")).decode() if bcrypt.check_password_hash(user.password, current_password): update_user_password(user, new_pwhash) response_object[ "message"] = f"Password for user {user.id} was updated!" return response_object, 200 else: users_namespace.abort(401, f"Incorrect email or password.")
def test_update_user_with_passord(test_app, test_database, add_user): password_one = "greaterthaneight" password_two = "somethingdifferent" user = add_user("user-to-be-updated", "*****@*****.**", password_one) assert bcrypt.check_password_hash(user.password, password_one) client = test_app.test_client() resp = client.put( f"/users/{user.id}", data=json.dumps({ "username": "******", "email": "*****@*****.**", "password": password_two }), content_type="application/json", ) assert resp.status_code == 200 user = get_user_by_id(user.id) assert bcrypt.check_password_hash(user.password, password_one) assert not bcrypt.check_password_hash(user.password, password_two)
def refresh(): post_data = request.get_json() refresh_token = post_data['refresh_token'] response_object = {} try: resp = User.decode_token(refresh_token) user = get_user_by_id(resp) if not user: response_object["message"] = "Invalid token" return response_object, 401 access_token = user.encode_token(user.id, "access") refresh_token = user.encode_token(user.id, "refresh") response_object = { "access_token": access_token.decode(), "refresh_token": refresh_token.decode(), } return response_object, 200 except jwt.ExpiredSignatureError: auth_namespace.abort(401, "Signature expired. Please log in again.") return "Signature expired. Please log in again." except jwt.InvalidTokenError: auth_namespace.abort(401, "Invalid token. Please log in again.")
def post(self): """Creates new Access and Refresh tokens.""" payload = request.get_json() refresh_token = payload.get("refresh_token") try: user_id = User.decode_token(refresh_token) user = get_user_by_id(user_id) if not user: namespace.abort(401, "Invalid token") access_token = User.encode_token(user.id, "access").decode() refresh_token = User.encode_token(user.id, "refresh").decode() return { "access_token": access_token, "refresh_token": refresh_token }, 200 except jwt.ExpiredSignature: namespace.abort(401, "Token expired") except jwt.InvalidTokenError: namespace.abort(401, "Invalid token")
def test_update_user_with_password(test_app, test_database, add_user, create_payload): username = "******" email = "*****@*****.**" password1 = "A" password2 = "B" user = add_user(username, email, password1) assert bcrypt.check_password_hash(user.password, password1) payload = create_payload(username=username, email=email, password=password2) client = test_app.test_client() response = client.put(f"/users/{user.id}", **payload) data = json.loads(response.data.decode()) assert response.status_code == 200 assert email in data["message"] assert "password" not in data user = get_user_by_id(user.id) assert bcrypt.check_password_hash(user.password, password1) assert not bcrypt.check_password_hash(user.password, password2)
def get_status(): auth_header = request.headers.get("Authorization") response_object = {} if auth_header: try: access_token = auth_header.split(" ")[1] resp = User.decode_token(access_token) user = get_user_by_id(resp) if not user: response_object['message'] = "Invalid token" return response_object, 401 response_object['username'] = user.username response_object['email'] = user.email return response_object, 200 except jwt.ExpiredSignatureError: response_object["message"] = "Signature expired. Please log in again." return response_object, 401 except jwt.InvalidTokenError: response_object["message"] = "Invalid token. Please log in again." return response_object, 401 else: auth_namespace.abort(403, "Token required") response_object["message"] = "Token required." return response_object, 403
def put(self, order_id): """Updates an order.""" order = get_order_by_id(order_id) if not order: orders_namespace.abort(404, f"Order {order_id} does not exist") post_data = request.get_json() status = post_data.get("status") or order.status user_id = post_data.get("user_id") or order.user_id sponsor_name = post_data.get("sponsor_name") or order.sponsor_name response_object = {} # print(f"status: {status}") if status == "submitted": # Process the order # Get the user record and order items user_record = get_user_by_id(user_id) # Req Change 1 # Reject any order from admin or sponsor_mgr if user_record.role != "driver": response_object[ "message"] = f"{order.id} is a dummy order and will not process." return response_object, 412 user_affiliation = check_dupe_affiliation(user_id, sponsor_name) order_items = get_all_order_items_by_order_id(order_id) # Verify sufficient points to satisfy order # 1. Get points in order and summary of items tot_points_in_order = 0 order_summary = "" for item in order_items: details = get_catalog_item_by_id(item.catalog_item_id) tot_points_in_order += item.points_cost order_summary += f"Qty: { str(item.quantity) } - { details.name }, \tPoints cost: { str(item.points_cost * item.quantity) }\n" driver_points_after_order = user_affiliation.current_points - tot_points_in_order order_summary += "--------------------------------------------------------------------------\n" order_summary += f"Total points cost: \t\t\t\t{ str(tot_points_in_order) }\n\n" order_summary += "Your order has been placed. After your order, you have " + str( driver_points_after_order ) + " points remaining in the GoodDriver App.\n" # print(f"Order summary: {order_summary}") # print(f"Driver points after order: {driver_points_after_order}") # print(f"user_record.get_points_alert: {user_record.get_points_alert}") if driver_points_after_order >= 0: # Process order update_order(order, status, user_id, sponsor_name) # Update points on user affiliation sponsor_name = user_affiliation.sponsor_name status = user_affiliation.status current_points = driver_points_after_order update_affiliation(user_affiliation, user_id, sponsor_name, current_points, status) if user_record.get_points_alert: # try: # Req Change 3: send_email(user_record.email, "Order placed in GoodDriver App", order_summary) # except: # pass else: # Driver has insufficient points for order if user_record.get_points_alert: try: # Req Change 3: send_email( user_record.email, "Order was not placed in GoodDriver App", "We're sorry, but you have insufficient points to place your order in the GoodDriver App." ) except: pass response_object[ "message"] = f"{order.id} did not update due to insufficient points." return response_object, 412 else: # Not an order submission, simply update update_order(order, status, user_id, sponsor_name) response_object["message"] = f"{order.id} was updated!" return response_object, 200
def get(self, user_id): user = get_user_by_id(user_id) if not user: users_namespace.abort(404, f"User {user_id} does not exist") return user, 200