Last active
August 23, 2016 15:03
-
-
Save clayadavis/100c6039d85d756289c77e2317178d22 to your computer and use it in GitHub Desktop.
A route decorator for Flask that performs Mashape authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
from flask import Flask, request | |
app = Flask(__name__) | |
def authenticate_mashape(func): | |
''' | |
Decorator to authenticate request with Mashape. | |
''' | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
# Mashape authentication | |
mashape_secret = request.headers.get('X-Mashape-Proxy-Secret') | |
if mashape_secret is not None: | |
client_ip = request.access_route[-1] | |
if (client_ip in app.config['MASHAPE_IPS'] and | |
mashape_secret == app.config['MASHAPE_SECRET']): | |
return func(*args, **kwargs) | |
# No authentication | |
return "Invalid/expired token", 401 | |
return wrapper | |
# Presumably other methods would be /mashape/foo, /mashape/bar, etc. | |
@app.route('/mashape/') | |
@authenticate_mashape | |
def verify_mashape(): | |
''' | |
Verify backend secret and client token are correct. | |
When decorated with @authenticate_mashape, this verifies that the Mashape | |
config is correct and that the client's token is good. | |
''' | |
return 'OK', 200 | |
# These app configs can go anywhere | |
app.config['MASHAPE_SECRET'] = "your mashape secret key goes here " | |
app.config['MASHAPE_IPS'] = [ | |
"107.23.255.128", | |
"107.23.255.129", | |
"107.23.255.130", | |
"107.23.255.131", | |
"107.23.255.132", | |
"107.23.255.133", | |
"107.23.255.134", | |
"107.23.255.135", | |
"107.23.255.136", | |
"107.23.255.137", | |
"107.23.255.138", | |
"107.23.255.139", | |
"107.23.255.140", | |
"107.23.255.141", | |
"107.23.255.142", | |
"107.23.255.143", | |
"107.23.255.144", | |
"107.23.255.145", | |
"107.23.255.146", | |
"107.23.255.147", | |
"107.23.255.148", | |
"107.23.255.149", | |
"107.23.255.150", | |
"107.23.255.151", | |
"107.23.255.152", | |
"107.23.255.153", | |
"107.23.255.154", | |
"107.23.255.155", | |
"107.23.255.156", | |
"107.23.255.157", | |
"107.23.255.158", | |
"107.23.255.159", | |
"54.172.117.82", | |
"54.174.126.70", | |
"54.175.103.105", | |
"54.209.110.14", | |
"54.86.14.38", | |
"54.86.225.32", | |
"54.86.245.80", | |
"54.88.28.135", | |
"54.88.28.194", | |
"54.88.32.113", | |
"54.88.37.172", | |
"54.88.51.199", | |
"54.88.53.251", | |
"54.88.54.104", | |
"54.88.55.60", | |
"54.88.55.63", | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment