Python werkzeug.exceptions.Unauthorized() Examples

The following are 24 code examples of werkzeug.exceptions.Unauthorized(). 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: views.py    From MPContribs with MIT License 6 votes vote down vote up
def has_add_permission(self, request, obj):
        # limit the number of projects a user can own (unless admin)
        groups = self.get_groups(request)
        if "admin" in groups:
            return True

        # is_approved can only be set by an admin
        if "admin" not in groups and obj.is_approved:
            raise Unauthorized(f"Only admins can set `is_approved=True`")

        # project already created at this point -> count-1 and revert
        nr_projects = Projects.objects(owner=obj.owner).count() - 1
        if nr_projects > 2:
            Projects.objects(project=obj.project).delete()
            raise Unauthorized(f"{obj.owner} already owns {nr_projects} projects.")
        return True 
Example #2
Source File: datasets.py    From acousticbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def eval_job(dataset_id, job_id):
    # Getting dataset to check if it exists and current user is allowed to view it.
    ds = get_dataset(dataset_id)
    job = db.dataset_eval.get_job(job_id)
    if not job or job["dataset_id"] != ds["id"]:
        return jsonify({
            "success": False,
            "error": "Can't find evaluation job with a specified ID for this dataset.",
        }), 404

    if request.method == "DELETE":
        if not current_user.is_authenticated or ds["author"] != current_user.id:
            return jsonify({
                "success": False,
                "error": "You are not allowed to delete this evaluation job.",
            }), 401  # Unauthorized
        try:
            db.dataset_eval.delete_job(job_id)
        except db.exceptions.DatabaseException as e:
            return jsonify({
                "success": False,
                "error": str(e),
            }), 400  # Bad Request
        return jsonify({"success": True}) 
Example #3
Source File: test_auth.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #4
Source File: index.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def mb_user_deleter(musicbrainz_row_id):
    """ This endpoint is used by MusicBrainz to delete accounts once they
    are deleted on MusicBrainz too.

    See https://tickets.metabrainz.org/browse/MBS-9680 for details.

    Args: musicbrainz_row_id (int): the MusicBrainz row ID of the user to be deleted.

    Returns: 200 if the user has been successfully found and deleted from LB

    Raises:
        NotFound if the user is not found in the LB database
        Unauthorized if the MusicBrainz access token provided with the query is invalid
    """
    _authorize_mb_user_deleter(request.args.get('access_token', ''))
    user = db_user.get_by_mb_row_id(musicbrainz_row_id)
    if user is None:
        raise NotFound('Could not find user with MusicBrainz Row ID: %d' % musicbrainz_row_id)
    delete_user(user['musicbrainz_id'])
    return jsonify({'status': 'ok'}), 200 
Example #5
Source File: index.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def _authorize_mb_user_deleter(auth_token):
    headers = {'Authorization': 'Bearer {}'.format(auth_token)}
    r = requests.get(current_app.config['MUSICBRAINZ_OAUTH_URL'], headers=headers)
    try:
        r.raise_for_status()
    except HTTPError:
        raise Unauthorized('Not authorized to use this view')

    data = {}
    try:
        data = r.json()
    except ValueError:
        raise Unauthorized('Not authorized to use this view')

    try:
        # 2007538 is the row ID of the `UserDeleter` account that is
        # authorized to access the `delete-user` endpoint
        if data['sub'] != 'UserDeleter' or data['metabrainz_user_id'] != 2007538:
            raise Unauthorized('Not authorized to use this view')
    except KeyError:
        raise Unauthorized('Not authorized to use this view') 
Example #6
Source File: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
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 #7
Source File: exceptions.py    From Flask with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: exceptions.py    From Flask with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: datasets.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def edit(dataset_id):
    ds = get_dataset(dataset_id)
    if ds["author"] != current_user.id:
        raise Unauthorized("You can't edit this dataset.")

    return render_template(
        "datasets/edit.html",
        mode="edit",
        dataset_id=str(dataset_id),
        dataset_name=ds["name"],
    ) 
Example #10
Source File: paranoid.py    From flask-paranoid with MIT License 5 votes vote down vote up
def _default_invalid_session_handler(self):
        try:
            raise Unauthorized()
        except Exception as e:
            response = current_app.handle_user_exception(e)
        return response 
Example #11
Source File: test_decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def test_anonymous_user_unauthorized(self):
        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
Example #12
Source File: test_decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def test_decorated_with_without_parenthesis(self):
        @auth_required()
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method()

        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
Example #13
Source File: authnz_test.py    From confidant with Apache License 2.0 5 votes vote down vote up
def test_require_csrf_token(mocker):
    mock_fn = mocker.Mock()
    mock_fn.__name__ = 'mock_fn'
    mock_fn.return_value = 'unittestval'

    wrapped = authnz.require_csrf_token(mock_fn)

    mocker.patch('confidant.authnz.settings.USE_AUTH', False)
    assert wrapped() == 'unittestval'

    mocker.patch('confidant.authnz.settings.USE_AUTH', True)
    app = create_app()
    with app.app_context():
        g_mock = mocker.patch('confidant.authnz.g')
        g_mock.auth_type = 'kms'
        assert wrapped() == 'unittestval'

        g_mock.auth_type = 'google oauth'
        u_mock = mocker.patch('confidant.authnz.user_mod')
        u_mock.check_csrf_token = mocker.Mock(return_value=True)
        assert wrapped() == 'unittestval'

        g_mock.auth_type = 'google oauth'
        u_mock = mocker.patch('confidant.authnz.user_mod')
        u_mock.check_csrf_token = mocker.Mock(return_value=False)
        with pytest.raises(Unauthorized):
            wrapped() 
Example #14
Source File: profile.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def delete_listens():
    """ Delete all the listens for the currently logged-in user from ListenBrainz.

    If POST request, this view checks for the correct authorization token and
    deletes the listens. If deletion is successful, redirects to user's profile page, 
    else flashes an error and redirects to user's info page.

    If GET request, this view renders a page asking the user to confirm that they 
    wish to delete their listens.
    """
    if request.method == 'POST':
        if request.form.get('token') and (request.form.get('token') == current_user.auth_token):
            try:
                delete_listens_history(current_user.musicbrainz_id)
            except Exception as e:
                current_app.logger.error('Error while deleting listens for %s: %s', current_user.musicbrainz_id, str(e))
                flash.error('Error while deleting listens for %s, please try again later.' % current_user.musicbrainz_id)
                return redirect(url_for('profile.info'))
            flash.info('Successfully deleted listens for %s.' % current_user.musicbrainz_id)
            return redirect(url_for('user.profile', user_name=current_user.musicbrainz_id))
        else:
            raise Unauthorized("Auth token invalid or missing.")
    else:
        return render_template(
            'profile/delete_listens.html',
            user=current_user,
        ) 
Example #15
Source File: server.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def handle_bot() -> str:
    event = request.get_json(force=True)
    for bot_name, config in bots_config.items():
        if config['email'] == event['bot_email']:
            bot = bot_name
            bot_config = config
            break
    else:
        raise BadRequest("Cannot find a bot with email {} in the Botserver "
                         "configuration file. Do the emails in your botserverrc "
                         "match the bot emails on the server?".format(event['bot_email']))
    if bot_config['token'] != event['token']:
        raise Unauthorized("Request token does not match token found for bot {} in the "
                           "Botserver configuration file. Do the outgoing webhooks in "
                           "Zulip point to the right Botserver?".format(event['bot_email']))
    app.config.get("BOTS_LIB_MODULES", {})[bot]
    bot_handler = app.config.get("BOT_HANDLERS", {})[bot]
    message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot]
    is_mentioned = event['trigger'] == "mention"
    is_private_message = event['trigger'] == "private_message"
    message = event["message"]
    message['full_content'] = message['content']
    # Strip at-mention botname from the message
    if is_mentioned:
        # message['content'] will be None when the bot's @-mention is not at the beginning.
        # In that case, the message shall not be handled.
        message['content'] = lib.extract_query_without_mention(message=message, client=bot_handler)
        if message['content'] is None:
            return json.dumps("")

    if is_private_message or is_mentioned:
        message_handler.handle_message(message=message, bot_handler=bot_handler)
    return json.dumps("") 
Example #16
Source File: test_auth_required.py    From flask-unchained with MIT License 5 votes vote down vote up
def test_anonymous_user_unauthorized(self):
        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
Example #17
Source File: test_auth_required.py    From flask-unchained with MIT License 5 votes vote down vote up
def test_decorated_without_parenthesis(self):
        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
Example #18
Source File: test_auth_required.py    From flask-unchained with MIT License 5 votes vote down vote up
def test_decorated_with_parenthesis(self):
        @auth_required()
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
Example #19
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _check_access(self):
        from indico_storage_s3.plugin import S3StoragePlugin
        auth = request.authorization
        if not S3StoragePlugin.settings.get('bucket_info_enabled'):
            raise NotFound
        username = S3StoragePlugin.settings.get('username')
        password = S3StoragePlugin.settings.get('password')
        if not auth or not auth.password or auth.username != username or auth.password != password:
            response = current_app.response_class('Authorization required', 401,
                                                  {'WWW-Authenticate': 'Basic realm="Indico - S3 Buckets"'})
            raise Unauthorized(response=response) 
Example #20
Source File: oauth2.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_credentials():
    try:
        with require_oauth.acquire() as token:
            login_user(token.user)
        return True
    except (Unauthorized, AuthlibFlaskException):
        return False 
Example #21
Source File: test_err_handler.py    From hobbit-core with MIT License 5 votes vote down vote up
def test_werkzeug_exceptions(self):
        resp = ErrHandler.handler(wkz_exc.Unauthorized())
        assert resp.status_code == 401
        data = json.loads(resp.get_data())
        assert data['message'] == u'未登录' 
Example #22
Source File: core.py    From MPContribs with MIT License 5 votes vote down vote up
def has_add_permission(self, request, obj):
        if not self.is_admin_or_project_user(request, obj):
            return False

        if hasattr(obj, "identifier") and obj.project.unique_identifiers:
            if self.resource.document.objects(
                project=obj.project.id, identifier=obj.identifier
            ).count():
                raise Unauthorized(
                    f"{obj.identifier} already added for {obj.project.id}"
                )

        return True 
Example #23
Source File: oauth.py    From amivapi with GNU Affero General Public License v3.0 4 votes vote down vote up
def oauth_redirect(redirect_uri, state):
    """Process login and redirect user.

    Loads and validates all inputs from request. First check if the request
    contains a cookie with token to use, otherwise check for login data in
    form.

    Returns:
        flask.Response: Flask redirect response

    Raises:
        werkzeug.exceptions.Unauthorized: If the user cannot be authenticated
    """
    # First check for token in cookie
    token = request.cookies.get('token')
    if token:
        authenticate_token(token)
        if g.current_user is None:
            # Session ended since we served the login page. Back to login.
            # This is caught by the except below.
            abort(401, "Your session has expired, please log in again.")
    # Otherwise check for login data
    else:
        resp = post_internal(
            'sessions',
            {
                'username': request.form.get('username'),
                'password': request.form.get('password')
            }
        )[0]
        if 'token' not in resp:
            abort(401, "post_internal to sessions failed: %s" % resp)
        token = resp['token']

    # We have a valid token! Let's bring the user back to the oauth client.
    redirect_uri = _append_url_params(redirect_uri,
                                      access_token=token,
                                      token_type='bearer',
                                      scope='amiv',
                                      state=state)

    # If the user wants to be remembered, save the token as cookie
    # so the next time only 'confirm' needs to be pressed
    response = current_app.make_response(redirect(redirect_uri))
    if request.form.get('remember'):
        response.set_cookie('token', token)
    return response 
Example #24
Source File: oauth.py    From amivapi with GNU Affero General Public License v3.0 4 votes vote down vote up
def oauth():
    """Endpoint for OAuth login. OAuth clients redirect users here."""
    response_type = request.args.get('response_type')
    client_id = request.args.get('client_id')
    redirect_uri = request.args.get('redirect_uri')
    scope = request.args.get('scope')
    state = request.args.get('state')
    token = request.cookies.get('token', '')
    error_msg = ''

    # Check this is a request by a proper client
    redirect_uri = validate_oauth_authorization_request(
        response_type, client_id, redirect_uri, scope, state)

    # Check if the user already has a token
    authenticate_token(token)
    if g.current_user is None:
        user = None
    else:
        # Get first name for personal greeting
        query = {'_id': ObjectId(g.current_user)}
        projection = {'firstname': 1}  # Firstame is a required field for users
        data = current_app.data.driver.db['users'].find_one(query, projection)
        user = data['firstname']

    # Handle POST: Logout or Login+Redirect
    if request.method == 'POST':
        # Check if the user wants to log out
        logout = request.form.get('submit') == 'logout'
        if logout:
            # Reset token and user
            token = user = ''
        else:
            try:
                return oauth_redirect(redirect_uri, state)
            except Unauthorized as error:
                # Login failed. Set error message and reset token
                token = ''
                error_msg = ("Login failed! If you think there is an error, "
                             "please contact AMIV with the exact time of your "
                             "login.")
                current_app.logger.info("Login failed with error: %s" % error)

    # Serve the login page (reset cookie if needed)
    response = make_response(render_template("loginpage.html",
                                             client_id=client_id,
                                             user=user,
                                             error_msg=error_msg))
    response.set_cookie('token', token)
    return response