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


Python web.HTTPUnauthorized方法代码示例

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


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

示例1: login

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def login(self, request: web.Request) -> web.Response:
        user = self.check_token(request)
        if not user.user_agent:
            user.user_agent = request.headers.get("User-Agent", None)

        try:
            data = await request.json()
        except json.JSONDecodeError:
            raise web.HTTPBadRequest(body='{"error": "Malformed JSON"}', headers=self._headers)

        try:
            session = await fbchat.Session.from_cookies(data, user_agent=user.user_agent)
        except fbchat.FacebookError:
            self.log.debug("Failed to log in", exc_info=True)
            raise web.HTTPUnauthorized(body='{"error": "Facebook authorization failed"}',
                                       headers=self._headers)
        if not await session.is_logged_in():
            raise web.HTTPUnauthorized(body='{"error": "Facebook authorization failed"}',
                                       headers=self._headers)
        await user.on_logged_in(session)
        if user.command_status and user.command_status.get("action") == "Login":
            user.command_status = None
        return web.Response(body='{}', status=200, headers=self._headers) 
开发者ID:tulir,项目名称:mautrix-facebook,代码行数:25,代码来源:public.py

示例2: login_required

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def login_required(func):
    @wraps(func)
    async def wrapped(*args, **kwargs):
        if middleware._request_property is ...:
            raise RuntimeError('Incorrect usage of decorator.'
                               'Please initialize middleware first')
        request = args[-1]

        if isinstance(request, web.View):
            request = request.request

        if not isinstance(request, web.BaseRequest):  # pragma: no cover
            raise RuntimeError(
                'Incorrect usage of decorator.'
                'Expect web.BaseRequest as an argument')

        if not request.get(middleware._request_property):
            raise web.HTTPUnauthorized(reason='Authorization required')

        return await func(*args, **kwargs)
    return wrapped 
开发者ID:hzlmn,项目名称:aiohttp-jwt,代码行数:23,代码来源:permissions.py

示例3: user_login

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def user_login(request, email, password, connection=None):
    models = request.app.models
    user = await models.user.get_user_by_email(email, connection=connection)
    if user:
        if not user.is_active:
            raise web.HTTPForbidden(reason="User disabled")
        elif check_password(password, user.password):
            await models.user_action_log_entry.create_login(
                request, user_id=user.pk, connection=connection)
            token = request.app.context.jwt.generate(uid=user.id)
            return web.json_response(
                {
                    'uid': user.id,
                    'profile': await user.get_profile(connection=connection),
                    'token': token,
                }, headers={'Authorization': 'Bearer %s' % token},
            )
    raise web.HTTPUnauthorized(reason="Login incorrect") 
开发者ID:dvhb,项目名称:dvhb-hybrid,代码行数:20,代码来源:jwt.py

示例4: middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def middleware(self, request, handler):
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer'):
            token = token[7:]
        else:
            token = request.rel_url.query.get('token')
            if not token:
                token = request.headers.get('token')
        request.verified = False

        if token:
            try:
                payload = self.decode(token)
                request.verified = True
            except jwt.JWTError:
                raise web.HTTPUnauthorized()
        else:
            payload = {}
        request.session = payload
        return await handler(request) 
开发者ID:dvhb,项目名称:dvhb-hybrid,代码行数:22,代码来源:jwt.py

示例5: add

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def add(self, request: web.Request):
        if request.method == "POST":
            logging.info("Received request to ADD bot")
            if "Authorization" not in request.headers:
                raise web.HTTPUnauthorized(reason="Failed to provide token!")  # Token was omitted from the headers
            raise web.HTTPServiceUnavailable()
        else:
            raise web.HTTPServiceUnavailable()

    # @server.route("/bots/<int:snowflake>/",
    #              methods=["GET", "POST"])  # Post to `/bots/:bot_id/` with token in headers 
开发者ID:henry232323,项目名称:RPGBot,代码行数:13,代码来源:server.py

示例6: auth_github

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def auth_github(request):
    """View for signing in with Github

    Currently the only authentication method (and probably will remain so).

    This will redirect to Github to allow OAUTH authentication if
    necessary.

    """
    if 'error' in request.query:
        logger.error(request.query)
        web.HTTPUnauthorized(body="Encountered an error. ")

    session = await get_session(request)
    nexturl = request.query.get('next') or '/'
    baseurl = BOT_BASEURL + "/auth/github?next=" + nexturl
    try:
        ghappapi = request.app['ghappapi']
        ghapi = await ghappapi.oauth_github_user(baseurl, session, request.query)
        if ghapi.username:
            await remember(request, web.HTTPFound(nexturl), ghapi.token)
            return web.HTTPFound(nexturl)
    except web.HTTPFound:
        raise
    except Exception as exc:
        logger.exception("failed to auth")
    return web.HTTPUnauthorized(body="Could not authenticate your Github account") 
开发者ID:bioconda,项目名称:bioconda-utils,代码行数:29,代码来源:views.py

示例7: appconfig

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def appconfig(request):
    session = await aiohttp_session.get_session(request)
    if "token" not in session:
        raise web.HTTPUnauthorized()
    context = {"token": session["token"], "uid": session["uid"],
               "ip": config["webserver"]["server_ip"],
               "address": config["webserver"]["web_address"]}
    return aiohttp_jinja2.render_template("appconfig.xml", request,
                                          context=context) 
开发者ID:AvaCity,项目名称:avacity-2.0,代码行数:11,代码来源:web.py

示例8: four_hundred_one

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def four_hundred_one(request):
    return web.HTTPUnauthorized(reason="I must simulate errors.", text="Simulated server error.") 
开发者ID:instana,项目名称:python-sensor,代码行数:4,代码来源:aioserver.py

示例9: handle_message

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def handle_message(self, request):
        """ Put to message queue and return 202 to client.
        """
        if not request.app['agent'].initialized:
            raise web.HTTPUnauthorized()

        msg = await request.read()
        await self.msg_queue.put(msg)
        raise web.HTTPAccepted() 
开发者ID:hyperledger-archives,项目名称:indy-agent,代码行数:11,代码来源:post_message_handler.py

示例10: raise_error

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def raise_error(self, request):
        raise web.HTTPUnauthorized(
            headers={
                hdrs.WWW_AUTHENTICATE: 'Basic realm={}'.format(self._realm)
            },
        ) 
开发者ID:aio-libs,项目名称:aiohttp-remotes,代码行数:8,代码来源:basic_auth.py

示例11: login

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def login(request):
    response = web.HTTPFound('/')
    form = await request.post()
    username = form.get('username')
    password = form.get('password')

    verified = await check_credentials(
        request.app.user_map, username, password)
    if verified:
        await remember(request, response, username)
        return response

    return web.HTTPUnauthorized(body='Invalid username / password combination') 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:15,代码来源:handlers.py

示例12: login

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def login(self, request):
        response = web.HTTPFound('/')
        form = await request.post()
        login = form.get('login')
        password = form.get('password')
        db_engine = request.app.db_engine
        if await check_credentials(db_engine, login, password):
            await remember(request, response, login)
            raise response

        raise web.HTTPUnauthorized(
            body=b'Invalid username/password combination') 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:14,代码来源:handlers.py

示例13: test_is_anonymous

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def test_is_anonymous(loop, aiohttp_client):

    async def index(request):
        is_anon = await is_anonymous(request)
        if is_anon:
            raise web.HTTPUnauthorized()
        return web.Response()

    async def login(request):
        response = web.HTTPFound(location='/')
        await remember(request, response, 'UserID')
        raise response

    async def logout(request):
        response = web.HTTPFound(location='/')
        await forget(request, response)
        raise response

    app = web.Application()
    _setup(app, CookiesIdentityPolicy(), Autz())
    app.router.add_route('GET', '/', index)
    app.router.add_route('POST', '/login', login)
    app.router.add_route('POST', '/logout', logout)
    client = await aiohttp_client(app)
    resp = await client.get('/')
    assert web.HTTPUnauthorized.status_code == resp.status

    await client.post('/login')
    resp = await client.get('/')
    assert web.HTTPOk.status_code == resp.status

    await client.post('/logout')
    resp = await client.get('/')
    assert web.HTTPUnauthorized.status_code == resp.status 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:36,代码来源:test_dict_autz.py

示例14: test_login_required

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def test_login_required(loop, aiohttp_client):
    with pytest.raises(DeprecationWarning):

        @login_required
        async def index(request):
            return web.Response()

        async def login(request):
            response = web.HTTPFound(location='/')
            await remember(request, response, 'UserID')
            raise response

        async def logout(request):
            response = web.HTTPFound(location='/')
            await forget(request, response)
            raise response

        app = web.Application()
        _setup(app, CookiesIdentityPolicy(), Autz())
        app.router.add_route('GET', '/', index)
        app.router.add_route('POST', '/login', login)
        app.router.add_route('POST', '/logout', logout)

        client = await aiohttp_client(app)
        resp = await client.get('/')
        assert web.HTTPUnauthorized.status_code == resp.status

        await client.post('/login')
        resp = await client.get('/')
        assert web.HTTPOk.status_code == resp.status

        await client.post('/logout')
        resp = await client.get('/')
        assert web.HTTPUnauthorized.status_code == resp.status 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:36,代码来源:test_dict_autz.py

示例15: test_check_authorized

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPUnauthorized [as 别名]
def test_check_authorized(loop, aiohttp_client):
    async def index(request):
        await check_authorized(request)
        return web.Response()

    async def login(request):
        response = web.HTTPFound(location='/')
        await remember(request, response, 'UserID')
        raise response

    async def logout(request):
        response = web.HTTPFound(location='/')
        await forget(request, response)
        raise response

    app = web.Application()
    _setup(app, CookiesIdentityPolicy(), Autz())
    app.router.add_route('GET', '/', index)
    app.router.add_route('POST', '/login', login)
    app.router.add_route('POST', '/logout', logout)
    client = await aiohttp_client(app)
    resp = await client.get('/')
    assert web.HTTPUnauthorized.status_code == resp.status

    await client.post('/login')
    resp = await client.get('/')
    assert web.HTTPOk.status_code == resp.status

    await client.post('/logout')
    resp = await client.get('/')
    assert web.HTTPUnauthorized.status_code == resp.status 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:33,代码来源:test_dict_autz.py


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