def collection(request): method = request.method comp = request.env.file_upload if method == 'OPTIONS': headers = {} if comp.tus_enabled: headers['Tus-Resumable'] = '1.0.0' headers['Tus-Version'] = '1.0.0' headers['Tus-Extension'] = 'creation,termination' headers['Tus-Max-Size'] = str(comp.max_size) return Response(status=200, headers=headers) tus = _tus_resumable_header(request) if method == 'POST' and tus: return _collection_post_tus(request) if method == 'POST' and not tus: return _collection_post(request) if method == 'PUT' and not tus: return _collection_put(request) raise exc.HTTPMethodNotAllowed()
def test_405_can_have_custom_message(self): custom_405 = http_error(httpexceptions.HTTPMethodNotAllowed(), errno=ERRORS.METHOD_NOT_ALLOWED, message="Disabled from conf.") with mock.patch('tests.core.testapp.views.Mushroom._extract_filters', side_effect=custom_405): response = self.app.get(self.sample_url, headers=self.headers, status=405) self.assertFormattedError(response, 405, ERRORS.METHOD_NOT_ALLOWED, "Method Not Allowed", "Disabled from conf.")
def flush_post(request): settings = request.registry.settings flush_enabled = settings.get('kinto.flush_endpoint_enabled', False) if not asbool(flush_enabled): raise httpexceptions.HTTPMethodNotAllowed() request.registry.storage.flush() return httpexceptions.HTTPAccepted()
def default_bucket(request): if request.method.lower() == 'options': path = request.path.replace('default', 'unknown') subrequest = build_request(request, { 'method': 'OPTIONS', 'path': path }) return request.invoke_subrequest(subrequest) if Authenticated not in request.effective_principals: # Pass through the forbidden_view_config raise httpexceptions.HTTPForbidden() settings = request.registry.settings if asbool(settings['readonly']): raise httpexceptions.HTTPMethodNotAllowed() bucket_id = request.default_bucket_id # Implicit object creations. # Make sure bucket exists create_bucket(request, bucket_id) # Make sure the collection exists create_collection(request, bucket_id) path = request.path.replace('/buckets/default', '/buckets/{}'.format(bucket_id)) querystring = request.url[(request.url.index(request.path) + len(request.path)):] try: # If 'id' is provided as 'default', replace with actual bucket id. body = request.json body['data']['id'] = body['data']['id'].replace('default', bucket_id) except: body = request.body or {"data": {}} subrequest = build_request(request, { 'method': request.method, 'path': path + querystring, 'body': body, }) subrequest.bound_data = request.bound_data try: response = request.invoke_subrequest(subrequest) except httpexceptions.HTTPException as error: is_redirect = error.status_code < 400 if error.content_type == 'application/json' or is_redirect: response = reapply_cors(subrequest, error) else: # Ask the upper level to format the error. raise error return response
def edit_profile(self): """Handle POST payload from profile update form.""" if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() # Nothing to do here for non logged-in users if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_userid(self.request.domain, self.request.authenticated_userid) response = {'model': {'email': user.email}} # We allow updating subscriptions without validating a password subscriptions = appstruct.get('subscriptions') if subscriptions: data = json.loads(subscriptions) err = _update_subscription_data(self.request, data) if err is not None: return err return response # Any updates to fields below this point require password validation. # # `pwd` is the current password # `password` (used below) is optional, and is the new password # if not User.validate_user(user, appstruct.get('pwd')): return {'errors': {'pwd': _('Invalid password')}, 'code': 401} email = appstruct.get('email') if email: email_user = User.get_by_email(email) if email_user: if email_user.id != user.id: return { 'errors': { 'pwd': _('That email is already used') }, } response['model']['email'] = user.email = email password = appstruct.get('password') if password: user.password = password return response
def default_bucket(request): if request.method.lower() == "options": path = request.path.replace("default", "unknown") subrequest = build_request(request, { "method": "OPTIONS", "path": path }) return request.invoke_subrequest(subrequest) if Authenticated not in request.effective_principals: # Pass through the forbidden_view_config raise httpexceptions.HTTPForbidden() settings = request.registry.settings if asbool(settings["readonly"]): raise httpexceptions.HTTPMethodNotAllowed() bucket_id = request.default_bucket_id # Implicit object creations. # Make sure bucket exists create_bucket(request, bucket_id) # Make sure the collection exists create_collection(request, bucket_id) path = request.path.replace("/buckets/default", f"/buckets/{bucket_id}") querystring = request.url[(request.url.index(request.path) + len(request.path)):] try: # If 'id' is provided as 'default', replace with actual bucket id. body = request.json body["data"]["id"] = body["data"]["id"].replace("default", bucket_id) except Exception: body = request.body or {"data": {}} subrequest = build_request(request, { "method": request.method, "path": path + querystring, "body": body }) subrequest.bound_data = request.bound_data try: response = request.invoke_subrequest(subrequest) except httpexceptions.HTTPException as error: is_redirect = error.status_code < 400 if error.content_type == "application/json" or is_redirect: response = reapply_cors(subrequest, error) else: # Ask the upper level to format the error. raise error return response
def assert_endpoint_enabled(request, collection_name): """Check that endpoint is not disabled from configuration. """ settings = request.registry.settings method = request.method.lower() setting_key = 'record_%s_%s_enabled' % (collection_name, method) enabled = settings.get(setting_key, False) if not enabled: error_msg = 'Endpoint disabled for this collection in configuration.' response = errors.http_error(httpexceptions.HTTPMethodNotAllowed(), errno=errors.ERRORS.METHOD_NOT_ALLOWED, message=error_msg) raise response
def item(request): method = request.method tus = _tus_resumable_header(request) if method == 'HEAD' and tus: return _item_head_tus(request) if method == 'GET' and not tus: return _item_get(request) if method == 'PATCH' and tus: return _item_patch_tus(request) if method == 'DELETE': return _item_delete(request, tus) raise exc.HTTPMethodNotAllowed()
def default_bucket(request): if request.method.lower() == 'options': path = request.path.replace('default', 'unknown') subrequest = build_request(request, { 'method': 'OPTIONS', 'path': path }) return request.invoke_subrequest(subrequest) if getattr(request, 'prefixed_userid', None) is None: # Pass through the forbidden_view_config raise httpexceptions.HTTPForbidden() settings = request.registry.settings if asbool(settings['readonly']): raise httpexceptions.HTTPMethodNotAllowed() bucket_id = request.default_bucket_id path = request.path.replace('/buckets/default', '/buckets/%s' % bucket_id) querystring = request.url[(request.url.index(request.path) + len(request.path)):] # Make sure bucket exists create_bucket(request, bucket_id) # Make sure the collection exists create_collection(request, bucket_id) subrequest = build_request(request, { 'method': request.method, 'path': path + querystring, 'body': request.body }) subrequest.bound_data = request.bound_data try: response = request.invoke_subrequest(subrequest) except httpexceptions.HTTPException as error: is_redirect = error.status_code < 400 if error.content_type == 'application/json' or is_redirect: response = reapply_cors(subrequest, error) else: # Ask the upper level to format the error. raise error return response
def reset_password(self): """ Handle submission of the reset password form. This function checks that the activation code (i.e. reset token) provided by the form is valid, retrieves the user associated with the activation code, and resets their password. """ schema = schemas.ResetPasswordSchema().bind(request=self.request) form = deform.Form(schema) code = self.request.matchdict.get('code') if code is None: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None: return httpexceptions.HTTPNotFound() if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() err, appstruct = validate_form(form, self.request.POST.items()) if err is not None: return err user.password = appstruct['password'] self.request.db.delete(activation) self.request.session.flash(_('Your password has been reset!'), 'success') self.request.registry.notify(PasswordResetEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.reset_password_redirect)
def root(request): if request.method not in ['GET', 'POST']: raise httpexceptions.HTTPMethodNotAllowed() body = request.repository.handle_request(query_string(request)) return xml_response(body)