本文整理汇总了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)
示例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
示例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")
示例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)
示例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
示例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")
示例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)
示例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.")
示例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()
示例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)
},
)
示例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')
示例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')
示例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
示例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
示例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