def handle_error(self, error): """ Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error. """ status_code = getattr(error, 'status_code', self.DEFAULT_VALIDATION_STATUS) abort(status_code, messages=error.messages)
def test(cls, obj, field, value, state): """ Additional check for 'current_password' as User hasn't field 'current_password' """ if field == 'current_password': if current_user.password != value and obj.password != value: abort(code=HTTPStatus.FORBIDDEN, message="Wrong password") else: state['current_password'] = value return True return PatchJSONParameters.test(obj, field, value, state)
def load_story_details(self, value): """ Load details field into corresponding story schema """ if isinstance(value, str): value = json.loads(value) story_type = int(value.get('type', StoryType.INVALID)) if story_type != StoryType.INVALID: schema = story_details_schema.get(story_type) if schema is not None: obj = schema.load(value) if obj.errors: abort(code=HTTPStatus.BAD_REQUEST, message=str(obj.errors)) return obj.data return None
def validate_captcha(self, data): """" Check reCAPTCHA if necessary. NOTE: we remove 'recaptcha_key' from data once checked because we don't need it in the resource """ recaptcha_key = data.pop('recaptcha_key', None) captcha_is_valid = False if not recaptcha_key: no_captcha_permission = permissions.AdminRolePermission() if no_captcha_permission.check(): captcha_is_valid = True # NOTE: This hardcoded CAPTCHA key is just for demo purposes. elif recaptcha_key == 'secret_key': captcha_is_valid = True if not captcha_is_valid: abort(code=HTTPStatus.FORBIDDEN, message="CAPTCHA key is incorrect.")
def dump_story_details(self, story_obj): """ Format story details. :param story_obj: an instance of Story :return: detailed Schema or empty """ assert isinstance(story_obj, Story) res = dict() details_field = story_details_fields.get(story_obj.type) # TODO: raise meaingful exception if details_field is not None: details = getattr(story_obj, details_field) schema = story_details_schema.get(story_obj.type) if schema is not None: res = schema.dump(details) if res.errors: abort(code=HTTPStatus.BAD_REQUEST, message=str(res.errors)) return res.data return res
def authorize(*args, **kwargs): """ This endpoint asks user if he grants access to his data to the requesting application. """ # TODO: improve implementation. This implementation is broken because we # don't use cookies, so there is no session which client could carry on. # OAuth2 server should probably be deployed on a separate domain, so we # can implement a login page and store cookies with a session id. # ALTERNATIVELY, authorize page can be implemented as SPA (single page # application) if not current_user.is_authenticated: return abort(code=HTTPStatus.UNAUTHORIZED) if request.method == 'GET': client_id = kwargs.get('client_id') oauth2_client = OAuth2Client.query.get_or_404(client_id=client_id) kwargs['client'] = oauth2_client kwargs['user'] = current_user # TODO: improve template design return render_template('authorize.html', **kwargs) confirm = request.form.get('confirm', 'no') return confirm == 'yes'
def commit_or_abort( self, session, default_error_message="The operation failed to complete"): """ Context manager to simplify a workflow in resources Args: session: db.session instance default_error_message: Custom error message Exampple: >>> with api.commit_or_abort(db.session): ... user = User(**args) ... db.session.add(user) ... return user """ default_error_message = default_error_message.strip('.:') try: with session.begin(): yield except ValueError as exception: logger.error("Value error to commit data: {}".format( str(exception))) abort(code=HTTPStatus.CONFLICT, message=str(exception)) except sqlalchemy.exc.IntegrityError as e: logger.error("Database integrity error: {}".format(str(e))) abort(code=HTTPStatus.CONFLICT, message="{}: {}".format(default_error_message, str(e))) except Exception as e: logger.error("Failed to commit data: {}".format(str(e))) if hasattr(e, 'code'): code = e.code else: code = HTTPStatus.BAD_REQUEST abort(code=code, message="{}: {}".format(default_error_message, str(e)))
def deny(self): """ Abort HTTP request by raising HTTP error exception with a specified HTTP code. """ return abort(code=self.DENY_ABORT_HTTP_CODE, message=self.DENY_ABORT_MESSAGE)
def api_invalid_response(req): """ This is a default handler for OAuth2Provider, which raises abort exception with error message in JSON format. """ abort(code=HTTPStatus.UNAUTHORIZED.value)