def login(): """The function logs in a new user""" try: print("====================================") data, q_error = request.json, {'Error': 'User not found', 'e': 403} if validation(data, ['username', 'password']) and \ query_username(q_error, True): if check_password_hash(objects['user'].user_password, valid_data['password']): token = objects['user'].generate_auth_token() login_user(objects['user']) user = { "username": objects['user'].user_username, "name": objects['user'].user_name, "email": objects['user'].user_email } print(user, "+++++++++++++++++++++++++++") return jsonify({ 'user': user, 'token': token.decode('ascii'), 'message': 'login was successful' }), 200 else: create_error({'Error': 'Incorrect password'}, 403) return format_error['error'] except Exception as ex: excepts = { 'BadRequest': { 'Error': 'Please ensure all fieds are ' + 'correctly specified', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def delete_account(token): """The function deletes a user's account""" try: user_id, data = Users.decode_token(token), request.json if validation(data, ['password']): user = Users.query.filter_by(id=user_id).first() # check if the password provided matches the known if check_password_hash(user.user_password, valid_data['password']): user.delete() return jsonify({'Error': 'Account deleted'}), 200 else: create_error({'Error': 'Incorrect password'}, 403) return format_error['error'] except Exception as ex: excepts = { 'TypeError': { 'Error': 'Please provide a password ' + 'key and value', 'e': 400 }, 'BadRequest': { 'Error': 'Password is missing', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def get_user(token): """The function logs in a new user""" try: user_id = Users.decode_token(token) user = Users.query.filter_by(id=user_id).first() if (user): user = { "username": user.user_username, "name": user.user_name, "id": user_id, "email": user.user_email } return jsonify({ "user": user, "message": "user records found" }), 200 return jsonify({"Error": "User record not found"}), 401 except Exception as ex: excepts = { 'BadRequest': { 'Error': 'Please ensure all fieds are ' + 'correctly specified', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def reset_password(token): """The function updates a user's password""" try: data, user_id = request.json, Users.decode_token(token) if validation(data, ['password', 'new_password', 'confirm_password' ]) and password_reset_verification(user_id): objects['user'].user_password = generate_password_hash( valid_data['new_password']) objects['user'].update() return jsonify({'message': 'Password was reset'}), 201 return format_error['error'] except Exception as ex: excepts = { 'AttributeError': { 'Error': 'All attributes are expected', 'e': 400 }, 'BadRequest': { 'Error': 'Parse all fields', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def update_recipe(token, category_id, recipe_id): """The function updates a recipe""" try: user_id, data, error = Users.decode_token(token), request.json, \ {'Error': 'category not found', 'e': 404} recipe_category_id = data.pop('recipe_category_id') if int(recipe_category_id) and validation( data, ['recipe_name', 'ingredients', 'description']) \ and check_category_id(user_id, category_id, error, True): return do_recipe_update([data, recipe_category_id], user_id, category_id, recipe_id) return format_error['error'] except Exception as ex: excepts = { 'KeyError': { 'Error': str(ex).strip('\'') + ' key missing', 'e': 400 }, 'IntegrityError': { 'Error': 'Recipe name already ' + 'exists', 'e': 409 }, 'ValueError': { 'Error': 'Invalid entry', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse category id, ' + 'recipe name and ingredients', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def delete_recipe(token, category_id, recipe_id): """The function delete a recipe""" try: # get the user id from the token user_id, error = Users.decode_token(token), \ {'Error': 'Category not found', 'e': 404} if check_category_id(user_id, category_id, error, True): user_recipe = Recipes.query.filter_by( rec_cat=category_id, rec_id=recipe_id).first() if user_recipe is not None: user_recipe.delete() return jsonify({'message': 'recipe deleted'}), 200 else: create_error({'Error': 'Recipe not found'}, 404) return format_error['error'] # capture value error except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry, please ' + 'provide the category id and recipe ' + 'id as integers', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse the recipe id ' + 'and category id', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def view_category_recipes(token, category_id): """The function return recipes in a category""" try: user_id, error = Users.decode_token(token), \ {'Error': 'category not found', 'e': 404} if check_category_id(user_id, category_id, error, True): return get_recipes(user_id, category_id, True) return format_error['error'] # capture value error except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry, please ' + ' provide the category id as ' + 'integer', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse the category ' + 'id', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def add_recipe(token, category_id): """The function adds recipes to the database""" try: user_id, data, error = Users.decode_token(token), request.json, \ {'Error': 'category not found', 'e': 404} if check_category_id(user_id, category_id, error, True): return do_create_recipe(data, category_id) return format_error['error'] except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry, please provide' + ' the category id as integer while ' + 'recipe name and ingredients as string', 'e': 400 }, 'IntegrityError': { 'Error': 'Recipe name already exists', 'e': '409' }, 'BadRequest': { 'Error': 'Please parse category id, ' + 'recipe name and ingredients', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def search_categories(token): """The function searches and returns categories""" try: # TODO validate the search parameters q = str(request.args.get('q', '')).title() page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 5)) user_id = Users.decode_token(token) # check if q is a string and not empty check_response = check_values({'q': q}) if check_response: return do_category_search(user_id, page, per_page, q) return format_error['error'] except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry please provide ' + 'q as a string', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse the q parameter', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def update_category(token, category_id): """The function updates a category""" try: data, user_id, error = request.json, Users.decode_token(token), \ {'Error': 'category not found', 'e': 404} if validation(data, ['category_name', 'category_description']): return update_category(user_id, category_id, error) return format_error['error'] except Exception as ex: excepts = { 'IntegrityError': { 'Error': 'Recipe name already ' + 'exists', 'e': 409 }, 'ValueError': { 'Error': 'Invalid entry', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse both category ' + 'id and category name', 'e': 400 }, 'KeyError': { 'Error': str(ex).strip('\'') + ' is ' + 'missing', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def create_category(token): """The function creates a new category""" try: next = request.args.get('next') data, user_id, error = request.json, Users.decode_token(token), \ {'Error': 'Category name already exists', 'e': 409} if validation(data, ['category_name', 'category_description']) and \ validate_descriptions(valid_data['category_description']) \ and check_category_name(user_id, error, False): return do_add_category(user_id) return format_error['error'] except Exception as ex: excepts = { 'IntegrityError': { 'Error': 'Category name already ' + 'exists', 'e': 409 }, 'BadRequest': { 'Error': 'Please create a category ' + 'name key and value', 'e': 400 }, 'ValueError': { 'Error': "you sent an " + str(ex), 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def view_all_categories(token): """The function returns all categories""" try: user_id, page, per_page = Users.decode_token(token), \ int(request.args.get('page', 1)), \ int(request.args.get('per_page', 5)) return get_paginated_categories(user_id, page, per_page) except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry', 'e': 400 }, 'BadRequest': { 'Error': 'Provide all fields', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def search_recipes(token): """The function searches and returns recipes in the database""" try: q = definitions()[2] user_id = Users.decode_token(token) check_response = check_values({'q': q}) if check_response: return do_recipes_search(user_id) return format_error['error'], 400 except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry, please ' + 'provide q as a string', 'e': 400 }, 'BadRequest': { 'Error': 'Please provide the q ' + 'parameter', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def delete_category(token, category_id): """The function deletes a category""" try: # get user id from token user_id, error = Users.decode_token(token), \ {'Error': 'category not found', 'e': 404} if check_category_id(user_id, category_id, error, True): objects['category'].delete() return jsonify({'message': 'category deleted'}), 200 return format_error['error'] except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry for category id', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse category id', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def user_register(): """The function registers a new user""" try: data, error = request.json, { 'Error': 'Username already exists', 'e': 409 } if validation(data, ['username', 'name', 'password', 'email']) \ and valid_register() and query_username(error, False): user = Users(valid_data['username'], generate_password_hash(valid_data['password']), valid_data['name'], valid_data['email']) user.add() return jsonify({'username': user.user_username}), 201 return format_error['error'] except Exception as ex: excepts = { 'KeyError': { 'Error': str(ex).strip('\'') + ' key is ' + 'missing', 'e': 400 }, 'IntegrityError': { 'Error': 'Email already exists', 'e': '409' }, 'BadRequest': { 'Error': 'All fields keys are required', 'e': 400 }, 'ValueError': { 'Error': str(ex), 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']
def view_one_recipe(token, category_id, recipe_id): """The function returns one recipe""" try: user_id, error = Users.decode_token(token), \ {'Error': 'category not found', 'e': 404} if check_category_id(user_id, category_id, error, True): return get_recipes(user_id, category_id, False, recipe_id) return format_error['error'] except Exception as ex: excepts = { 'ValueError': { 'Error': 'Invalid entry, please ' + 'provide the category id and recipe ' + 'id as integers', 'e': 400 }, 'BadRequest': { 'Error': 'Please parse the recipe id ' + 'and category id', 'e': 400 } } handle_exceptions(type(ex).__name__, excepts) return format_error['error']