forked from pierce403/cors.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
90 lines (71 loc) · 2.64 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from flask import render_template
from flask import request
import time
import flask
from flask import Flask
app = Flask(__name__)
import requests
@app.route('/', methods=("GET", "POST", "OPTIONS"))
def index():
qs=request.query_string
if qs:
try:
qs = qs.decode('utf8')
agent = request.headers.get('User-Agent')
oauth = request.headers.get('Authorization')
ctype = request.headers.get('Content-Type')
headers = {}
if agent is not None:
headers['User-Agent'] = agent;
if oauth is not None:
headers['Authorization'] = oauth;
if request.method == "POST":
user_data = {}
if 'application/json' in ctype:
user_data = request.data
else:
user_data = request.form.to_dict()
if 'multipart/form-data' in ctype:
user_files = request.files.to_dict()
r = requests.post(qs, headers = headers, data = user_data, files = user_files)
else:
r = requests.post(qs, headers = headers, data = user_data)
elif request.method == "GET":
r = requests.get(qs, headers = headers)
elif request.method == "OPTIONS":
'''
OPTIONS has recently been used before POST in some libraries
but not all websites have an OPTIONS http method; therefore,
we provide a request to ourself in order to return
the correct headers with correct response code and data
'''
r = requests.options(request.base_url, headers = headers)
rt = r.text
except:
return "nope"
response = flask.Response(rt)
status_code = r.status_code
'''
we don't really care if the requests.options above
returns an OK request or not, we just care about
passing a new response with new headers, and a valid status code
'''
if request.method == "OPTIONS":
status_code = 200
response.headers['Access-Control-Allow-Origin'] = '*'
# ensure that data getting passed back is plain text
response.headers['Content-Type'] = "text/plain"
'''
preflight CORS policy response headers
- Returns Allowed Methods:
In our case, GET and POST are the only ones allowed
- Returns Allowed Headers:
In our case, it is the headers that the user requested to use
so, the ones in Access-Control-Request-Headers
'''
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = request.headers.get('Access-Control-Request-Headers')
return response, status_code
else:
print("nope")
return render_template('index.html')