def get_many_subresources(model, resource_id, subresource, *args, **kwargs): try: # Get current user from JWT user = Security.get_current_user() # Get entity entity = model.query.filter_by(id=resource_id).first() if entity is None: return make_response(*ErrorHandler.entity_does_not_exist) # Ensure user is authorized to access data is_authorized = Security.check_authorization(entity, user) if not is_authorized: return make_response(*ErrorHandler.user_not_authorized) # Handle subresource of entity subresource_model = getattr(models, subresource.get('model_name')) entity_list = getattr(entity, subresource.get('attribute_name')) data = subresource_model.many_schema.dump(entity_list) # Return data return make_response({'status': 'success', 'data': data}, 200) except exceptions.NoUserFoundFromTokenError as e: return make_response(*ErrorHandler.custom_error(str(e), 400)) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def delete_single(model, resource_id, *args, **kwargs): try: # Get current user from JWT user = Security.get_current_user() # Get entity entity = model.query.filter_by(id=resource_id).first() if entity is None: return make_response(*ErrorHandler.entity_does_not_exist) # Ensure user is authorized to access data is_authorized = Security.check_authorization(entity, user) if not is_authorized: return make_response(*ErrorHandler.user_not_authorized) # Delete data entity.remove() return make_response( { 'status': 'success', 'message': 'Entity deleted.' }, 204) except exceptions.NoUserFoundFromTokenError as e: return make_response(*ErrorHandler.custom_error(str(e), 400)) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def get_many(model, *args, **kwargs): try: # Get current user from JWT user = Security.get_current_user() # Get data from QueryBuilder entity_list, result_length = QueryBuilder(model=model, user=user).get_data() # Get data from entity list data = model.many_schema.dump(entity_list) # Return data return make_response( { 'status': 'success', 'data': data, 'result_length': result_length }, 200) except exceptions.QueryBuilderError as e: return make_response(*ErrorHandler.custom_error(str(e), 412)) except exceptions.NoUserFoundFromTokenError as e: return make_response(*ErrorHandler.custom_error(str(e), 400)) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def get_user_many(*args, **kwargs): try: return '' except ValidationError as e: return make_response(*ErrorHandler.custom_error(e, 400)) except Exception as e: return make_response(*ErrorHandler.generic_error)
def get_user_single(user_id, *args, **kwargs): try: pass except ValidationError as e: return make_response(*ErrorHandler.custom_error(e, 400)) except Exception as e: return make_response(*ErrorHandler.generic_error)
def user_forgot_password(): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) body = request.get_json() # Get email for password reset email = body.get('email') if email is None: return make_response( *ErrorHandler.custom_error('Email is missing.', 400)) # Get user user = models.User.query.filter_by(email=email).first() if user is None: return make_response(*ErrorHandler.user_does_not_exist) # Issue reset token (will be sent via email) current_url = '{}{}/'.format(request.host_url, blueprint.url_prefix[1:]) mail_resp = user.issue_password_reset_token(current_url=current_url) return make_response( { 'status': 'success', 'message': 'Password reset email sent to {}'.format(email) }, 202) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def post_company_single(): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) body = request.get_json() # Load data with schema data = models.Company.single_schema.load(body) # These are the keys passed in the request body that relate to the user that needs to be created for the company user_columns = ['email', 'password', 'is_admin'] # Create company (this also creates the database_tenants record) company = models.Company.create( {k: v for k, v in data.items() if k not in user_columns}) # Create initial user for company user_data = {k: v for k, v in data.items() if k in user_columns} user_data['linked_company'] = company.id user_data['database_tenant_id'] = company.database_tenant_id user_data['is_admin'] = True user = models.User.from_dict(user_data) # Issue access token access_token = user.issue_access_token() return make_response( { 'status': 'success', 'token': access_token, 'data': models.User.single_schema.dump(user) }, 201) except IntegrityError as e: return make_response(*ErrorHandler.entity_already_exists) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def post_many(model, *args, **kwargs): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) try: body = request.get_json() if type(body) is dict: body = [body] except Exception as e: return make_response(*ErrorHandler.request_missing_body_error) # Get current user from JWT user = Security.get_current_user() # Load data with schema data = model.many_schema.load(body) # Set database_tenant_id to current user database_tenant_id data = Security.set_database_tenant(data, user) # Create data objs = model.create(data) # Return message return make_response( { 'status': 'success', 'message': 'Data created.', 'data': model.many_schema.dump( objs ) # model.many_schema.dump([obj.to_dict() for obj in objs]) }, 201) except IntegrityError as e: return make_response(*ErrorHandler.entity_already_exists) except exceptions.NoUserFoundFromTokenError as e: return make_response(*ErrorHandler.custom_error(str(e), 400)) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def patch_single(model, resource_id, *args, **kwargs): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) try: body = request.get_json() except Exception as e: return make_response(*ErrorHandler.request_missing_body_error) # Get current user from JWT user = Security.get_current_user() # Get entity entity = model.query.filter_by(id=resource_id).first() if entity is None: return make_response(*ErrorHandler.entity_does_not_exist) # Ensure user is authorized to access data is_authorized = Security.check_authorization(entity, user) if not is_authorized: return make_response(*ErrorHandler.user_not_authorized) # Get data from schema data = model.single_schema.load(body, partial=True) # Update data entity.update(data) return make_response( { 'status': 'success', 'message': 'Entity updated.' }, 200) except IntegrityError as e: return make_response(*ErrorHandler.entity_already_exists) except exceptions.NoUserFoundFromTokenError as e: return make_response(*ErrorHandler.custom_error(str(e), 400)) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def post_user_many(*args, **kwargs): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) try: body = request.get_json() if type(body) is dict: body = [body] except Exception as e: return make_response(*ErrorHandler.request_missing_body_error) # Get current user from JWT user = Security.get_current_user() # Ensure user is admin if user.is_admin is False: return make_response(*ErrorHandler.custom_error( 'Not authorized to create users. Must be admin.', 401)) # Load data with schema data = models.User.many_schema.load(body) # Set database_tenant_id to current user database_tenant_id data = Security.set_database_tenant(data, user) # Create data objs = models.User.create(data) # Return message return make_response( { 'status': 'success', 'message': 'Data created.', 'data': models.User.many_schema.dump(objs) }, 201) except IntegrityError as e: return make_response(*ErrorHandler.entity_already_exists) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: print(e) return make_response(*ErrorHandler.generic_error)
def get_single_report(): try: # Get requested data data = request.args.to_dict() validated_data = ReportGetArgumentsSchema(many=False).load(data) # Generate report file # ... # Send file # return send_file() return make_response(ReportGetArgumentsSchema().dump(validated_data), 200) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e.messages, 400)) except Exception as e: return make_response(*ErrorHandler.generic_error)
def user_change_password(): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) body = request.get_json() # Ensure current and new passwords aren't missing data = models.User.change_password_schema.load(body) # Get user user = Security.get_current_user() if user is None: return make_response(*ErrorHandler.user_does_not_exist) # Change password user.change_password(data['current_password'], data['new_password']) return make_response( { 'status': 'success', 'message': 'Password updated.' }, 202) except models.exceptions.InvalidPasswordError as e: return make_response(*ErrorHandler.custom_error(str(e), 403)) except Exception as e: return make_response(*ErrorHandler.generic_error)
def login(*args, **kwargs): try: # Get JSON body if not request.is_json: return make_response(*ErrorHandler.request_is_not_json_error) body = request.get_json() # Ensure email and password aren't missing data = models.User.authentication_schema.load(body) # Get user user = models.User.query.filter_by(email=data['email']).first() if user is None: return make_response(*ErrorHandler.user_does_not_exist) # Validate password authorized = user.check_password(data['password']) if not authorized: return make_response(*ErrorHandler.incorrect_password) # Issue authentication token access_token = user.issue_access_token() return make_response({'status': 'success', 'token': access_token}, 201) except ValidationError as e: return make_response(*ErrorHandler.custom_error(e, 400)) except Exception as e: return make_response(*ErrorHandler.generic_error)