当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.Unauthorized方法代码示例

本文整理汇总了Python中werkzeug.exceptions.Unauthorized方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.Unauthorized方法的具体用法?Python exceptions.Unauthorized怎么用?Python exceptions.Unauthorized使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.exceptions的用法示例。


在下文中一共展示了exceptions.Unauthorized方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: has_add_permission

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:18,代码来源:views.py

示例2: mb_user_deleter

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:22,代码来源:index.py

示例3: _authorize_mb_user_deleter

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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') 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:23,代码来源:index.py

示例4: _test_permissions

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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 
开发者ID:alphagov,项目名称:notifications-admin,代码行数:27,代码来源:test_permissions.py

示例5: test_abort_if_not_public

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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 
开发者ID:amiv-eth,项目名称:amivapi,代码行数:26,代码来源:test_auth.py

示例6: eval_job

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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}) 
开发者ID:metabrainz,项目名称:acousticbrainz-server,代码行数:26,代码来源:datasets.py

示例7: has_add_permission

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:15,代码来源:core.py

示例8: test_werkzeug_exceptions

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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'未登录' 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:7,代码来源:test_err_handler.py

示例9: check_credentials

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
def check_credentials():
    try:
        with require_oauth.acquire() as token:
            login_user(token.user)
        return True
    except (Unauthorized, AuthlibFlaskException):
        return False 
开发者ID:opendatateam,项目名称:udata,代码行数:9,代码来源:oauth2.py

示例10: _check_access

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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) 
开发者ID:indico,项目名称:indico-plugins,代码行数:13,代码来源:controllers.py

示例11: test_decorated_with_parenthesis

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
def test_decorated_with_parenthesis(self):
        @auth_required()
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:9,代码来源:test_auth_required.py

示例12: test_decorated_without_parenthesis

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
def test_decorated_without_parenthesis(self):
        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:9,代码来源:test_auth_required.py

示例13: test_anonymous_user_unauthorized

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
def test_anonymous_user_unauthorized(self):
        @auth_required
        def method():
            raise MethodCalled

        with pytest.raises(Unauthorized):
            method() 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:9,代码来源:test_auth_required.py

示例14: handle_bot

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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("") 
开发者ID:zulip,项目名称:python-zulip-api,代码行数:35,代码来源:server.py

示例15: delete_listens

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import Unauthorized [as 别名]
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,
        ) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:29,代码来源:profile.py


注:本文中的werkzeug.exceptions.Unauthorized方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。