def request_from_github(abort_code=418):
def decorator(f):
"""
Decorator that checks if a request is a GitHub hook request
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if request.method != 'POST':
return 'OK'
else:
# Do initial validations on required headers
if 'X-Github-Event' not in request.headers:
abort(abort_code)
if 'X-Github-Delivery' not in request.headers:
abort(abort_code)
if 'X-Hub-Signature' not in request.headers:
abort(abort_code)
if not request.is_json:
abort(abort_code)
if 'User-Agent' not in request.headers:
abort(abort_code)
ua = request.headers.get('User-Agent')
if not ua.startswith('GitHub-Hookshot/'):
abort(abort_code)
request_ip = ip_address(u'{0}'.format(request.remote_addr))
meta_json = requests.get('https://api.github.com/meta').json()
hook_blocks = meta_json['hooks']
# Check if the POST request is from GitHub
for block in hook_blocks:
if ip_address(request_ip) in ip_network(block):
break
else:
g.log.info("Unauthorized attempt to deploy by IP %s" %
request_ip)
abort(abort_code)
return f(*args, **kwargs)
return decorated_function
return decorator
评论列表
文章目录