Python werkzeug.exceptions.Forbidden() Examples
The following are 30
code examples of werkzeug.exceptions.Forbidden().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
werkzeug.exceptions
, or try the search function
.
Example #1
Source File: delete.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def post(self, name): if not may(DELETE): raise Forbidden() try: with current_app.storage.open(name) as item: if not item.meta[COMPLETE] and not may(ADMIN): error = 'Upload incomplete. Try again later.' return render_template('error.html', heading=item.meta[FILENAME], body=error), 409 if item.meta[LOCKED] and not may(ADMIN): raise Forbidden() current_app.storage.remove(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise return redirect_next_referrer('bepasty.index')
Example #2
Source File: setkv.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def post(self, name): if self.REQUIRED_PERMISSION is not None and not may(self.REQUIRED_PERMISSION): raise Forbidden() try: with current_app.storage.openwrite(name) as item: if item.meta[self.KEY] == self.NEXT_VALUE: error = '%s already is %r.' % (self.KEY, self.NEXT_VALUE) elif not item.meta[COMPLETE]: error = 'Upload incomplete. Try again later.' else: error = None if error: return render_template('error.html', heading=item.meta[FILENAME], body=error), 409 item.meta[self.KEY] = self.NEXT_VALUE return redirect_next_referrer('bepasty.display', name=name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise
Example #3
Source File: test_lock_it_down.py From flask-bouncer with MIT License | 6 votes |
def test_bypass_route(): app = Flask("test_lock_it_down_raise_exception") app.debug = True bouncer = Bouncer(app, ensure_authorization=True) @bouncer.authorization_method def define_authorization(user, they): they.can('browse', Article) # Non decorated route -- should raise an Forbidden @app.route("/articles") @skip_authorization def articles_index(): return "A bunch of articles" client = app.test_client() jonathan = User(name='jonathan', admin=False) with user_set(app, jonathan): resp = client.get('/articles') eq_(b"A bunch of articles", resp.data)
Example #4
Source File: __init__.py From build-relengapi with Mozilla Public License 2.0 | 6 votes |
def query_token(body): """Get a token, specified by the token key given in the request body (this avoids embedding a token in a URL, where it might be logged). The caller must have permission to view this type of token, unless the token is limited-duration (in which case the API is simply decoding the JSON web token anyway).""" # use the token loader to interpret the token user = loader.token_loader.from_str(body) if not user: raise NotFound if not can_access_token('view', user.claims['typ'], getattr(user, 'authenticated_email', None)): raise Forbidden return user_to_jsontoken(user)
Example #5
Source File: test_lock_it_down.py From flask-bouncer with MIT License | 6 votes |
def test_lock_it_down_raise_exception(): app = Flask("test_lock_it_down_raise_exception") app.debug = True bouncer = Bouncer(app, ensure_authorization=True) @bouncer.authorization_method def define_authorization(user, they): they.can('browse', Article) # Non decorated route -- should raise an Forbidden @app.route("/articles") def articles_index(): return "A bunch of articles" client = app.test_client() jonathan = User(name='jonathan', admin=False) with user_set(app, jonathan): resp = client.get('/articles')
Example #6
Source File: upload.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def get(self, name): if not may(CREATE): raise Forbidden() try: item = current_app.storage.open(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: return 'No file found.', 404 raise if item.meta[COMPLETE]: error = 'Upload complete. Cannot delete fileupload garbage.' else: error = None if error: return error, 409 try: item = current_app.storage.remove(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise return 'Upload aborted'
Example #7
Source File: lodgeit.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def post(self): if not may(CREATE): raise Forbidden() lang = request.form.get('language') content_type = self.TRANS.get(lang) content_type_hint = 'text/plain' filename = None t = request.form['code'] # t is already unicode, but we want utf-8 for storage t = t.encode('utf-8') size = len(t) f = BytesIO(t) maxlife_timestamp = FOREVER name = create_item(f, filename, size, content_type, content_type_hint, maxlife_stamp=maxlife_timestamp) return redirect_next('bepasty.display', name=name, _anchor=url_quote(filename))
Example #8
Source File: __init__.py From build-relengapi with Mozilla Public License 2.0 | 6 votes |
def issue_usr(body, requested_permissions): email = get_user_email() if not email: raise Forbidden("Authenticate with a user-related " "mechanism to issue user tokens") session = g.db.session('relengapi') token_row = tables.Token( typ='usr', user=email, description=body.description, permissions=requested_permissions, disabled=False) session.add(token_row) session.commit() rv = token_row.to_jsontoken() rv.token = tokenstr.claims_to_str( {'iss': 'ra2', 'typ': 'usr', 'jti': 't%d' % token_row.id}) return rv
Example #9
Source File: test_anonymous_user_required.py From flask-unchained with MIT License | 6 votes |
def test_authed_user_api_request_forbidden(self, client, monkeypatch): client.login_user() # really we're mocking flask.request.is_json to True, but for some # reason, monkeypatch shits a brick trying to mock @property attrs monkeypatch.setattr('flask.request._parsed_content_type', ['application/json']) @anonymous_user_required def method(): raise MethodCalled with pytest.raises(Forbidden): method() monkeypatch.undo()
Example #10
Source File: test_auth.py From amivapi with GNU Affero General Public License v3.0 | 6 votes |
def test_abort_if_not_public(self): """Test that if g.requires_auth has an effect. If it is True and no user is there (and no admin) then it will abort. """ with self._init_context(): # user is None by default, admin is False # g.auth_required not set (e.g. no amivauth subclass) -> nothing abort_if_not_public() # Set to False -> nothing g.auth_required = False abort_if_not_public() # Set to True -> abort(401)/Forbidden g.auth_required = True with self.assertRaises(Unauthorized): abort_if_not_public() # User was found -> no abort g.current_user = "something" abort_if_not_public() # Tests for authentication
Example #11
Source File: test_permissions.py From notifications-admin with MIT License | 6 votes |
def _test_permissions( client, usr, permissions, will_succeed, kwargs=None, ): request.view_args.update({'service_id': 'foo'}) if usr: client.login(usr) decorator = user_has_permissions(*permissions, **(kwargs or {})) decorated_index = decorator(index) if will_succeed: decorated_index() else: try: if ( decorated_index().location != '/sign-in?next=%2F' or decorated_index().status_code != 302 ): pytest.fail("Failed to throw a forbidden or unauthorised exception") except (Forbidden, Unauthorized): pass
Example #12
Source File: test_permissions.py From notifications-admin with MIT License | 6 votes |
def test_user_doesnt_have_permissions_for_organisation( client, mocker, ): user = _user_with_permissions() user['organisations'] = ['org_1', 'org_2'] mocker.patch('app.user_api_client.get_user', return_value=user) client.login(user) request.view_args = {'org_id': 'org_3'} @user_has_permissions() def index(): pass with pytest.raises(Forbidden): index()
Example #13
Source File: test_auth.py From amivapi with GNU Affero General Public License v3.0 | 5 votes |
def test_resource_write_permission(self): """Test if write permission is checked correctly.""" user = "somethingsomething" with self._init_context(current_user=user, auth_required=True): # using AmivTokenAuth subclass # Abort(403) will raise the "Forbidden" exception with self.assertRaises(Forbidden): check_resource_write_permission('fake') # If the auth class returns true it wont be aborted, no exception g.current_user = 'allowed' check_resource_write_permission('fake') # Tests for `abort_if_not_public`
Example #14
Source File: __init__.py From build-relengapi with Mozilla Public License 2.0 | 5 votes |
def revoke_token(token_id): """Revoke an authentication token, identified by its ID. The caller must have permission to revoke this type of token; if that is a ``.my`` permission, then the user email must match. The response status is 204 on success. Revoking an already-revoked token returns 403.""" session = g.db.session('relengapi') token_data = tables.Token.query.filter_by(id=token_id).first() # don't leak info about which tokens exist -- return the same # status whether the token is missing or permission is missing if not token_data: raise Forbidden if not can_access_token('revoke', token_data.typ, token_data.user): raise Forbidden perms_str = ', '.join(str(p) for p in token_data.permissions) log = logger.bind(token_typ=token_data.typ, token_permissions=perms_str, token_id=token_id, mozdef=True) log.info("Revoking {} token #{} with permissions {}".format( token_data.typ, token_data.id, perms_str)) tables.Token.query.filter_by(id=token_id).delete() session.commit() return None, 204
Example #15
Source File: datasets.py From acousticbrainz-server with GNU General Public License v2.0 | 5 votes |
def delete(dataset_id): ds = get_dataset(dataset_id) if ds["author"] != current_user.id: raise Forbidden("You can't delete this dataset.") if request.method == "POST": db.dataset.delete(ds["id"]) flash.success("Dataset has been deleted.") return redirect(url_for("user.profile", musicbrainz_id=current_user.musicbrainz_id)) else: # GET return render_template("datasets/delete.html", dataset=ds)
Example #16
Source File: __init__.py From build-relengapi with Mozilla Public License 2.0 | 5 votes |
def issue_token(body): """Issue a new token. The body should not include a ``token`` or ``id``, but should include a ``typ`` and the necessary fields for that type. The response will contain both ``token`` and ``id``. You must have permission to issue the given token type.""" typ = body.typ # verify permission to issue this type perm = p.get('base.tokens.{}.issue'.format(typ)) if not perm.can(): raise Forbidden("You do not have permission to create this token type") # verify required parameters; any extras will be ignored for attr in required_token_attributes[typ]: if getattr(body, attr) is wsme.Unset: raise BadRequest("missing %s" % attr) # prohibit silly requests if body.disabled: raise BadRequest("can't issue disabled tokens") # All types have permissions, so handle those here -- ensure the request is # for a subset of the permissions the user can perform requested_permissions = [p.get(a) for a in body.permissions] if None in requested_permissions: raise BadRequest("bad permissions") if not set(requested_permissions) <= current_user.permissions: raise BadRequest("bad permissions") # Dispatch the rest to the per-type function. Note that WSME has already # ensured `typ` is one of the recognized types. token = token_issuers[typ](body, requested_permissions) perms_str = ', '.join(str(p) for p in requested_permissions) log = logger.bind(token_typ=token.typ, token_permissions=perms_str, mozdef=True) if token.id: log = log.bind(token_id=token.id) log.info("Issuing {} token to {} with permissions {}".format( token.typ, current_user, perms_str)) return token
Example #17
Source File: run.py From sample-platform with ISC License | 5 votes |
def forbidden(error: Forbidden) -> Dict[str, str]: """Handle unauthorized and forbidden access error.""" user_name = 'Guest' if g.user is None else g.user.name user_role = 'Guest' if g.user is None else g.user.role.value log.debug(f'{user_name} (role: {user_role}) tried to access {error.description}') return { 'user_role': user_role, 'endpoint': error.description }
Example #18
Source File: test_auth.py From amivapi with GNU Affero General Public License v3.0 | 5 votes |
def test_item_write_permission(self): """Test if write permission is checked correctly.""" user = "a" item_abort = {'_id': 'b'} item_pass = {'_id': user} with self._init_context(current_user=user, auth_required=True): # Abort(403) will raise the "Forbidden" exception with self.assertRaises(Forbidden): check_item_write_permission('fake', item_abort) # If the auth class returns true it wont be aborted, no exception check_item_write_permission('fake', item_pass)
Example #19
Source File: test_decorators.py From flask-react-spa with MIT License | 5 votes |
def test_without_one_of_roles(self, client): client.login_user() @auth_required(one_of=['ROLE_FAIL', 'ROLE_ALSO_FAIL']) def method(): raise MethodCalled with pytest.raises(Forbidden): method()
Example #20
Source File: test_decorators.py From flask-react-spa with MIT License | 5 votes |
def test_without_role(self, client): client.login_user() @auth_required(role='ROLE_FAIL') def method(): raise MethodCalled with pytest.raises(Forbidden): method()
Example #21
Source File: test_decorators.py From flask-react-spa with MIT License | 5 votes |
def test_without_all_roles(self, client): client.login_user() @auth_required(roles=['ROLE_USER', 'ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(Forbidden): method()
Example #22
Source File: exceptions.py From Flask with Apache License 2.0 | 5 votes |
def test_aborter(self): abort = exceptions.abort self.assert_raises(exceptions.BadRequest, abort, 400) self.assert_raises(exceptions.Unauthorized, abort, 401) self.assert_raises(exceptions.Forbidden, abort, 403) self.assert_raises(exceptions.NotFound, abort, 404) self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) self.assert_raises(exceptions.NotAcceptable, abort, 406) self.assert_raises(exceptions.RequestTimeout, abort, 408) self.assert_raises(exceptions.Gone, abort, 410) self.assert_raises(exceptions.LengthRequired, abort, 411) self.assert_raises(exceptions.PreconditionFailed, abort, 412) self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413) self.assert_raises(exceptions.RequestURITooLarge, abort, 414) self.assert_raises(exceptions.UnsupportedMediaType, abort, 415) self.assert_raises(exceptions.UnprocessableEntity, abort, 422) self.assert_raises(exceptions.InternalServerError, abort, 500) self.assert_raises(exceptions.NotImplemented, abort, 501) self.assert_raises(exceptions.BadGateway, abort, 502) self.assert_raises(exceptions.ServiceUnavailable, abort, 503) myabort = exceptions.Aborter({1: exceptions.NotFound}) self.assert_raises(LookupError, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1) myabort = exceptions.Aborter(extra={1: exceptions.NotFound}) self.assert_raises(exceptions.NotFound, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1)
Example #23
Source File: test_decorators.py From flask-react-spa with MIT License | 5 votes |
def test_it_accepts_auth_required_kwargs(self, client, monkeypatch, models): client.login_user() monkeypatch.setattr('flask.request.view_args', {'id': models.user.id}) @auth_required_same_user(role='ROLE_USER') def method(): raise MethodCalled with pytest.raises(MethodCalled): method() @auth_required_same_user(roles=['ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(Forbidden): method() @auth_required_same_user(one_of=['ROLE_USER', 'ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(MethodCalled): method() @auth_required_same_user(role='ROLE_USER', and_one_of=['ROLE_USER1', 'ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(MethodCalled): method() monkeypatch.undo()
Example #24
Source File: TestControllers.py From sample-platform with ISC License | 5 votes |
def test_user_deactivate_wrong_user(self, mock_g, mock_login): """ Test deactivating user from different user id. """ from mod_auth.controllers import deactivate mock_g.user = MockUser(id=1, role="None") with self.assertRaises(Forbidden): deactivate(2)
Example #25
Source File: TestControllers.py From sample-platform with ISC License | 5 votes |
def test_user_role_wrong_user(self, mock_g, mock_login): """ Test accessing role change from non-admin user id. """ from mod_auth.controllers import role mock_g.user = MockUser(id=1, role="None") with self.assertRaises(Forbidden): role(2)
Example #26
Source File: TestControllers.py From sample-platform with ISC License | 5 votes |
def test_user_reset_wrong_user(self, mock_g, mock_login): """ Test accessing reset user from different non-admin user id. """ from mod_auth.controllers import reset_user mock_g.user = MockUser(id=1, role="None") with self.assertRaises(Forbidden): reset_user(2)
Example #27
Source File: TestControllers.py From sample-platform with ISC License | 5 votes |
def test_user_view_wrong_user(self, mock_g, mock_login): """ Test accessing different user from user id. """ from mod_auth.controllers import user mock_g.user = MockUser(id=1, role="None") with self.assertRaises(Forbidden): user(2)
Example #28
Source File: test_decorators.py From flask-react-spa with MIT License | 5 votes |
def test_without_role_and_one_of_roles(self, client): client.login_user() @auth_required(role='ROLE_FAIL', one_of=['ROLE_USER']) def method(): raise MethodCalled with pytest.raises(Forbidden): method() @auth_required(roles=['ROLE_FAIL'], one_of=['ROLE_USER']) def method(): raise MethodCalled with pytest.raises(Forbidden): method() @auth_required(role='ROLE_USER', one_of=['ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(Forbidden): method() @auth_required(roles=['ROLE_USER'], one_of=['ROLE_FAIL']) def method(): raise MethodCalled with pytest.raises(Forbidden): method()
Example #29
Source File: base.py From cloudkitty with Apache License 2.0 | 5 votes |
def dispatch_request(self, *args, **kwargs): try: return super(BaseResource, self).dispatch_request(*args, **kwargs) except policy.PolicyNotAuthorized: raise http_exceptions.Forbidden( "You are not authorized to perform this action")
Example #30
Source File: flask_bouncer.py From flask-bouncer with MIT License | 5 votes |
def check_authorization(self, response): """checks that an authorization call has been made during the request""" if not hasattr(request, '_authorized'): raise Forbidden elif not request._authorized: raise Forbidden return response