本文整理匯總了Python中falcon.HTTPForbidden方法的典型用法代碼示例。如果您正苦於以下問題:Python falcon.HTTPForbidden方法的具體用法?Python falcon.HTTPForbidden怎麽用?Python falcon.HTTPForbidden使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類falcon
的用法示例。
在下文中一共展示了falcon.HTTPForbidden方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check_auth
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def check_auth(ba_ctx, req):
"""Check request authentication based on boot action context.
Raise proper Falcon exception if authentication fails, otherwise
silently return
:param ba_ctx: Boot Action context from database
:param req: The falcon request object of the API call
"""
identity_key = req.get_header('X-Bootaction-Key', default='')
if identity_key == '':
raise falcon.HTTPUnauthorized(
title='Unauthorized',
description='No X-Bootaction-Key',
challenges=['Bootaction-Key'])
if ba_ctx['identity_key'] != bytes.fromhex(identity_key):
logger.warn(
"Forbidding boot action access - node: %s, identity_key: %s, req header: %s"
% (ba_ctx['node_name'], str(ba_ctx['identity_key']),
str(bytes.fromhex(identity_key))))
raise falcon.HTTPForbidden(
title='Unauthorized', description='Invalid X-Bootaction-Key')
示例2: whitelist_subnets
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def whitelist_subnets(subnets):
"""
Validate source IP address of API call against subnet list
"""
def wrapper(func):
def wrapped(self, req, resp, *args, **kwargs):
# Check for administration subnet whitelist
for subnet in subnets:
if req.context.get("remote_addr") in subnet:
break
else:
logger.info("Rejected access to administrative call %s by %s from %s, source address not whitelisted",
req.env["PATH_INFO"],
req.context.get("user", "unauthenticated user"),
req.context.get("remote_addr"))
raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))
return func(self, req, resp, *args, **kwargs)
return wrapped
return wrapper
示例3: authorize_server
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def authorize_server(func):
"""
Make sure the request originator has a certificate with server flags
"""
from asn1crypto import pem, x509
def wrapped(resource, req, resp, *args, **kwargs):
buf = req.get_header("X-SSL-CERT")
if not buf:
logger.info("No TLS certificate presented to access administrative API call from %s" % req.context.get("remote_addr"))
raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")
header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
cert = x509.Certificate.load(der_bytes) # TODO: validate serial
for extension in cert["tbs_certificate"]["extensions"]:
if extension["extn_id"].native == "extended_key_usage":
if "server_auth" in extension["extn_value"].native:
req.context["machine"] = cert.subject.native["common_name"]
return func(resource, req, resp, *args, **kwargs)
logger.info("TLS authenticated machine '%s' not authorized to access administrative API", cert.subject.native["common_name"])
raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")
return wrapped
示例4: on_put
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def on_put(self, req, resp):
try:
username, mail, created, expires, profile = self.manager.consume(req.get_param("token", required=True))
except RelationalMixin.DoesNotExist:
raise falcon.HTTPForbidden("Forbidden", "No such token or token expired")
body = req.stream.read(req.content_length)
header, _, der_bytes = pem.unarmor(body)
csr = CertificationRequest.load(der_bytes)
common_name = csr["certification_request_info"]["subject"].native["common_name"]
if not common_name.startswith(username + "@"):
raise falcon.HTTPBadRequest("Bad requst", "Invalid common name %s" % common_name)
try:
_, resp.body = self.authority._sign(csr, body, profile=config.PROFILES.get(profile),
overwrite=config.TOKEN_OVERWRITE_PERMITTED)
resp.set_header("Content-Type", "application/x-pem-file")
logger.info("Autosigned %s as proven by token ownership", common_name)
except FileExistsError:
logger.info("Won't autosign duplicate %s", common_name)
raise falcon.HTTPConflict(
"Certificate with such common name (CN) already exists",
"Will not overwrite existing certificate signing request, explicitly delete existing one and try again")
示例5: on_get
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def on_get(self, req, resp):
token = req.get_param('token', True)
data = {}
for key in self.data_keys:
data[key] = req.get_param(key, True)
if not self.validate_token(token, data):
raise falcon.HTTPForbidden('Invalid token for these given values', '')
endpoint = self.config['iris']['hook']['gmail_one_click']
try:
result = self.iclient.post(endpoint, data)
except MaxRetryError:
logger.exception('Hitting iris-api failed for gmail oneclick')
else:
if result.status == 204:
resp.status = falcon.HTTP_204
return
else:
logger.error('Unexpected status code from api %s for gmail oneclick', result.status)
raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API')
示例6: default_exception_handler
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def default_exception_handler(ex, req, resp, params):
if hasattr(ex, 'title') and "Failed data validation" in ex.title:
JsonSchemaException(ex)
message = "Unexpected error occurred: {}".format(ex)
logger.error(message + "\nRequest: {} Params: {}".format(req, params))
if isinstance(ex, falcon.HTTPUnauthorized):
raise ex
if isinstance(ex, falcon.HTTPForbidden):
raise ex
stacktrace = traceback.format_exc()
logger.error(stacktrace)
raise falcon.HTTPInternalServerError(message)
示例7: guarded_session
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def guarded_session():
'''
Context manager that will automatically close session on exceptions
'''
try:
session = Session()
yield session
except IrisValidationException as e:
session.close()
raise HTTPBadRequest('Validation error', str(e))
except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
session.close()
raise
except Exception:
session.close()
logger.exception('SERVER ERROR')
raise
示例8: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def on_post(req, resp, user_name):
"""Update or create the secret key that grants public access to
user_name's oncall calendar for the logged-in user. Updating the
secret key will automatically invalidate existing secret keys. A
subsequent GET will get the secret key.
Current policy only allows the logged-in user to get its own key,
so user_name parameter must be the same as the logged-in user.
"""
challenger = req.context['user']
if challenger != user_name:
raise HTTPForbidden(
'Unauthorized',
'Action not allowed: "%s" is not allowed to update ical_key of "%s"' % (challenger, user_name)
)
key = generate_ical_key()
update_ical_key(challenger, user_name, 'user', key)
resp.status = HTTP_201
resp.body = key
resp.set_header('Content-Type', 'text/plain')
示例9: on_delete
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def on_delete(req, resp, user_name):
"""Delete the secret key that grants public access to user_name's
oncall calendar for the logged-in user.
Current policy only allows the logged-in user to get its own key,
so user_name parameter must be the same as the logged-in user.
"""
challenger = req.context['user']
if challenger != user_name:
raise HTTPForbidden(
'Unauthorized',
'Action not allowed: "%s" is not allowed to delete ical_key of "%s"' % (challenger, user_name)
)
delete_ical_key(challenger, user_name, 'user')
示例10: check_user_auth
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def check_user_auth(user, req):
"""
Check to see if current user is user or admin of team where user is in
"""
if 'app' in req.context:
return
challenger = req.context['user']
if user == challenger:
return
connection = db.connect()
cursor = connection.cursor()
get_allowed_query = '''SELECT DISTINCT(`user`.`name`)
FROM `team_admin`
JOIN `team_user` ON `team_admin`.`team_id` = `team_user`.`team_id`
JOIN `user` ON `user`.`id` = `team_user`.`user_id`
JOIN `user` AS `admin` ON `admin`.`id` = `team_admin`.`user_id`
WHERE `admin`.`name` = %s'''
cursor.execute(get_allowed_query, challenger)
allowed = (user,) in cursor
cursor.close()
connection.close()
if allowed or is_god(challenger):
return
raise HTTPForbidden('Unauthorized', 'Action not allowed for "%s"' % challenger)
示例11: check_team_auth
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def check_team_auth(team, req):
"""
Check to see if the current user is admin of the team
"""
if 'app' in req.context:
return
challenger = req.context['user']
connection = db.connect()
cursor = connection.cursor()
get_allowed_query = '''SELECT `team`.`name`
FROM `team_admin`
JOIN `team` ON `team_admin`.`team_id` = `team`.`id`
JOIN `user` ON `team_admin`.`user_id` = `user`.`id`
WHERE `user`.`name` = %s'''
cursor.execute(get_allowed_query, challenger)
allowed = (team,) in cursor
cursor.close()
connection.close()
if allowed or is_god(challenger):
return
raise HTTPForbidden(
'Unauthorized',
'Action not allowed: "%s" is not an admin for "%s"' % (challenger, team))
示例12: check_calendar_auth_by_id
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def check_calendar_auth_by_id(team_id, req):
if 'app' in req.context:
return
challenger = req.context['user']
query = '''SELECT `user`.`name`
FROM `team_user`
JOIN `user` ON `team_user`.`user_id` = `user`.`id`
WHERE `team_user`.`team_id` = %s
AND `user`.`name` = %s'''
connection = db.connect()
cursor = connection.cursor()
cursor.execute(query, (team_id, challenger))
user_in_team = cursor.rowcount
cursor.close()
connection.close()
if user_in_team != 0 or is_god(challenger):
return
raise HTTPForbidden('Unauthorized', 'Action not allowed: "%s" is not a team member' % (challenger))
示例13: csrf_protection
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def csrf_protection(func):
"""
Protect resource from common CSRF attacks by checking user agent and referrer
"""
import falcon
def wrapped(self, req, resp, *args, **kwargs):
# Assume curl and python-requests are used intentionally
if req.user_agent.startswith("curl/") or req.user_agent.startswith("python-requests/"):
return func(self, req, resp, *args, **kwargs)
# For everything else assert referrer
referrer = req.headers.get("REFERER")
if referrer:
scheme, netloc, path, params, query, fragment = urlparse(referrer)
if ":" in netloc:
host, port = netloc.split(":", 1)
else:
host, port = netloc, None
if host == req.host:
return func(self, req, resp, *args, **kwargs)
# Kaboom!
logger.warning("Prevented clickbait from '%s' with user agent '%s'",
referrer or "-", req.user_agent)
raise falcon.HTTPForbidden("Forbidden",
"No suitable UA or referrer provided, cross-site scripting disabled")
return wrapped
示例14: whitelist_subject
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def whitelist_subject(func):
def wrapped(self, req, resp, cn, *args, **kwargs):
from ipaddress import ip_address
from certidude import authority
from xattr import getxattr
try:
path, buf, cert, signed, expires = authority.get_signed(cn)
except IOError:
raise falcon.HTTPNotFound()
else:
# First attempt to authenticate client with certificate
buf = req.get_header("X-SSL-CERT")
if buf:
header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
origin_cert = x509.Certificate.load(der_bytes)
if origin_cert.native == cert.native:
logger.debug("Subject authenticated using certificates")
return func(self, req, resp, cn, *args, **kwargs)
# For backwards compatibility check source IP address
# TODO: make it disableable
try:
inner_address = getxattr(path, "user.lease.inner_address").decode("ascii")
except IOError:
raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))
else:
if req.context.get("remote_addr") != ip_address(inner_address):
raise falcon.HTTPForbidden("Forbidden", "Remote address %s mismatch" % req.context.get("remote_addr"))
else:
return func(self, req, resp, cn, *args, **kwargs)
return wrapped
示例15: authorize_admin
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPForbidden [as 別名]
def authorize_admin(func):
@whitelist_subnets(config.ADMIN_SUBNETS)
def wrapped(resource, req, resp, *args, **kwargs):
if req.context.get("user").is_admin():
return func(resource, req, resp, *args, **kwargs)
logger.info("User '%s' not authorized to access administrative API", req.context.get("user").name)
raise falcon.HTTPForbidden("Forbidden", "User not authorized to perform administrative operations")
return wrapped