當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。