Python aiohttp.web.HTTPUnauthorized() Examples
The following are 25
code examples of aiohttp.web.HTTPUnauthorized().
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
aiohttp.web
, or try the search function
.
Example #1
Source File: jwt.py From dvhb-hybrid with MIT License | 49224 votes |
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")
Example #2
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
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
Example #3
Source File: jwt.py From dvhb-hybrid with MIT License | 5 votes |
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)
Example #4
Source File: routes.py From dask-gateway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _wrap_authenticated(handler, user=False, token=False): if not user and not token: return handler @wraps(handler) async def inner(request): if token: backend = request.app["backend"] auth_header = request.headers.get("Authorization") if auth_header: auth_type, auth_token = auth_header.split(" ", 1) if auth_type == "token": cluster_name = request.match_info["cluster_name"] cluster = await backend.get_cluster(cluster_name) if cluster is not None and cluster.token == auth_token: # Use `none` to indicate api token authenticated request["user"] = None return await handler(request) if not user: raise web.HTTPUnauthorized(headers={"WWW-Authenticate": "token"}) if user: auth = request.app["authenticator"] return await auth.authenticate_and_handle(request, handler) return inner
Example #5
Source File: auth.py From dask-gateway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def unauthorized(kind): return web.HTTPUnauthorized( headers={"WWW-Authenticate": kind}, reason="Authentication required" )
Example #6
Source File: permissions.py From aiohttp-jwt with MIT License | 5 votes |
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
Example #7
Source File: api.py From aiohttp-security with Apache License 2.0 | 5 votes |
def has_permission( permission, context=None, ): """Decorator that restricts access only for authorized users with correct permissions. If user is not authorized - raises HTTPUnauthorized, if user is authorized and does not have permission - raises HTTPForbidden. """ def wrapper(fn): @wraps(fn) async def wrapped(*args, **kwargs): request = args[-1] if not isinstance(request, web.BaseRequest): msg = ("Incorrect decorator usage. " "Expecting `def handler(request)` " "or `def handler(self, request)`.") raise RuntimeError(msg) await check_permission(request, permission, context) return await fn(*args, **kwargs) return wrapped warnings.warn("has_permission decorator is deprecated, " "use check_permission instead", DeprecationWarning) return wrapper
Example #8
Source File: api.py From aiohttp-security with Apache License 2.0 | 5 votes |
def check_permission(request, permission, context=None): """Checker that passes only to authoraised users with given permission. If user is not authorized - raises HTTPUnauthorized, if user is authorized and does not have permission - raises HTTPForbidden. """ await check_authorized(request) allowed = await permits(request, permission, context) if not allowed: raise web.HTTPForbidden()
Example #9
Source File: api.py From aiohttp-security with Apache License 2.0 | 5 votes |
def check_authorized(request): """Checker that raises HTTPUnauthorized for anonymous users. """ userid = await authorized_userid(request) if userid is None: raise web.HTTPUnauthorized() return userid
Example #10
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
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
Example #11
Source File: server.py From RPGBot with GNU General Public License v3.0 | 5 votes |
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
Example #12
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
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
Example #13
Source File: handlers.py From aiohttp-security with Apache License 2.0 | 5 votes |
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')
Example #14
Source File: handlers.py From aiohttp-security with Apache License 2.0 | 5 votes |
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')
Example #15
Source File: basic_auth.py From aiohttp-remotes with MIT License | 5 votes |
def raise_error(self, request): raise web.HTTPUnauthorized( headers={ hdrs.WWW_AUTHENTICATE: 'Basic realm={}'.format(self._realm) }, )
Example #16
Source File: public.py From mautrix-facebook with GNU Affero General Public License v3.0 | 5 votes |
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)
Example #17
Source File: post_message_handler.py From indy-agent with Apache License 2.0 | 5 votes |
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()
Example #18
Source File: app_aiohttp.py From python-sensor with MIT License | 5 votes |
def four_hundred_one(request): return web.HTTPUnauthorized(reason="I must simulate errors.", text="Simulated server error.")
Example #19
Source File: aioserver.py From python-sensor with MIT License | 5 votes |
def four_hundred_one(request): return web.HTTPUnauthorized(reason="I must simulate errors.", text="Simulated server error.")
Example #20
Source File: web.py From avacity-2.0 with MIT License | 5 votes |
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)
Example #21
Source File: views.py From bioconda-utils with MIT License | 5 votes |
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")
Example #22
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 4 votes |
def test_check_permission(loop, aiohttp_client): async def index_read(request): await check_permission(request, 'read') return web.Response() async def index_write(request): await check_permission(request, 'write') return web.Response() async def index_forbid(request): await check_permission(request, 'forbid') 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', '/permission/read', index_read) app.router.add_route('GET', '/permission/write', index_write) app.router.add_route('GET', '/permission/forbid', index_forbid) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/permission/read') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/permission/read') assert web.HTTPOk.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPOk.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPForbidden.status_code == resp.status await client.post('/logout') resp = await client.get('/permission/read') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPUnauthorized.status_code == resp.status
Example #23
Source File: permissions.py From aiohttp-jwt with MIT License | 4 votes |
def check_permissions( scopes, permissions_property='scopes', comparison=match_all, ): if not callable(comparison): raise TypeError('comparison should be a func') if isinstance(scopes, str): scopes = scopes.split(' ') def scopes_checker(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') payload = request.get(middleware._request_property) if not payload: raise web.HTTPUnauthorized(reason='Authorization required') user_scopes = payload.get(permissions_property, []) if not isinstance(user_scopes, collections.Iterable): raise web.HTTPForbidden(reason='Invalid permissions format') if not comparison(scopes, user_scopes): raise web.HTTPForbidden(reason='Insufficient scopes') return await func(*args, **kwargs) return wrapped return scopes_checker
Example #24
Source File: core.py From dask-gateway with BSD 3-Clause "New" or "Revised" License | 4 votes |
def routes_handler(self, request): self._proxy_contacted.set() # Authenticate the api request auth_header = request.headers.get("Authorization") if not auth_header: raise web.HTTPUnauthorized(headers={"WWW-Authenticate": "token"}) auth_type, auth_token = auth_header.split(" ", 1) if auth_type != "token" or auth_token != self.api_token: raise web.HTTPUnauthorized(headers={"WWW-Authenticate": "token"}) watch = request.query.get("watch", False) if watch: last_id = request.query.get("last_id", 0) try: last_id = int(last_id) except Exception: raise web.HTTPUnprocessableEntity( reason="invalid `last_id`: %s" % last_id ) events = self._events_after(last_id) if events is None: raise web.HTTPGone(reason="`last_id` is too old, full refresh required") queue = asyncio.Queue() if events: queue.put_nowait(events) self._watchers.add(queue) try: response = web.StreamResponse( headers={"Content-Type": "application/json"} ) await response.prepare(request) async with self.cg.cancellable(): while True: events = await queue.get() msg = {"events": events} await response.write(json.dumps(msg).encode() + b"\n") finally: self._watchers.discard(queue) await response.write_eof() return response else: msg = {"routes": list(self.routes.values()), "id": self._next_id - 1} return web.json_response(msg)
Example #25
Source File: server.py From RPGBot with GNU General Public License v3.0 | 4 votes |
def convert(self, request: web.Request): try: snowflake = int(request.match_info['snowflake']) except: raise web.HTTPBadRequest(reason="Malformed request") if request.method == "GET": logging.info(f"Received request to view info on bot {snowflake}") snowflake = int(snowflake) resp = dict((await self.get_botdata(snowflake))[0]) return web.json_response(resp) else: try: if "Authorization" not in request.headers: raise web.HTTPUnauthorized(reason="Failed to provide token!") # Token was omitted from the headers token = request.headers["Authorization"] # The user token snowflake = int(snowflake) # The bot snowflake req = f"""SELECT * FROM userdata WHERE token = '{token.replace("'", "''")}';""" async with self.pool.acquire() as connection: response = await connection.fetch(req) # Get bots and webhook / gather type if response: bots, type = response[0]["bots"], response[0]["type"] if snowflake not in bots: # That bot is not associated with that token raise web.HTTPUnauthorized(reason="That snowflake is not valid!") formdata = await request.post() async with self.pool.acquire() as connection: name = await connection.fetchval( f"""SELECT name FROM botdata WHERE id = {snowflake};""" ) # Get the bot's name url = await connection.fetchval( f"""SELECT url FROM botdata WHERE name = '{formdata["to_bot"].replace("'", "''")}';""" ) # Get the URL of the bot we're sending to if url is None: # That bot is not in our database! raise web.HTTPBadRequest(reason="That is an invalid bot!") payload = { "from_bot": name, "amount": formdata["amount"], "to_bot": formdata["to_bot"], "server_id": formdata["server_id"] } dumped = json.dumps(payload, indent=4) logging.info(f"Received request to convert {formdata['amount']} from {name} " f"to {formdata['to_bot']} on server {formdata['server_id']}") if type is 0: # If using webhooks try: await self.session.post(url, json=dumped) # Post the payload to the other bot's URL except Exception as e: raise web.HTTPInternalServerError(reason="An error occurred forwarding to the bot!") return web.json_response(payload) else: # If we don't get a response from the given token, the token doesn't exist raise web.HTTPUnauthorized(reason="Invalid token!") except web.HTTPException: raise except: # Generic error catching, always gives 400 cause how could it be _my_ issue? return web.HTTPBadRequest(reason="An error occurred!")