-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
199 lines (158 loc) · 6.41 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/python
''' Azure Visualizer backend server '''
import os
from flask import Flask, render_template, request, current_app, json
from flask_api import status
import requests
app = Flask(__name__) # Instantiate Flask
''' Configure app.config, otherwise use defaults '''
app.config['PORT'] = os.getenv('PORT', 5000)
app.config['EXPIRE_TIME'] = os.getenv('EXPIRE_TIME', 300)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'AZURESECRETKEY')
app.config['TENANT_ID'] = os.getenv('TENANT_ID', '')
app.config['CLIENT_ID'] = os.getenv('CLIENT_ID', '')
app.config['CLIENT_SECRET'] = os.getenv('CLIENT_SECRET', '')
app.config['SUBSCRIPTION'] = os.getenv('SUBSCRIPTION', '')
app.config['PROTOCOL'] = os.getenv('PROTOCOL','')
@app.route('/', methods=['GET'])
def root():
''' Read the root document and load form'''
return current_app.send_static_file('index.html')
def isServerPreconfigured():
''' Return True if the server was configured using the environmental variables '''
return not(app.config['CLIENT_ID'] == '' or app.config['CLIENT_SECRET'] == '' or app.config['TENANT_ID'] == '' or app.config['SUBSCRIPTION'] == '')
@app.route('/serverlogin', methods=['GET'])
def serverlogin():
''' Provides the status of the server environmetal variable '''
# print(app.config['CLIENT_ID'])
if isServerPreconfigured():
return 'Server Pre-Configured', status.HTTP_200_OK
else:
return 'Server Not Pre-Configured. Setup up your environmental variables properly', status.HTTP_417_EXPECTATION_FAILED
@app.route('/login', methods=['POST'])
def login():
''' Create a login request to Azure'''
if isServerPreconfigured():
print('Serve configured, using environmental variables')
tenant_id = app.config['TENANT_ID']
client_id = app.config['CLIENT_ID']
client_secret = app.config['CLIENT_SECRET']
else:
print('Server not configured using client auth')
payload = json.loads(request.get_data().decode('utf-8'))
tenant_id = payload['tenant_id']
client_id = payload['client_id']
client_secret = payload['client_secret']
url = str.format(
"https://login.microsoftonline.com/{0}/oauth2/token", tenant_id)
payload = str.format("grant_type=client_credentials" +
"&client_id={0}" +
"&client_secret={1}" +
"&resource=https%3A%2F%2Fmanagement.azure.com%2F",
client_id, client_secret)
headers = {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache",
}
print(url)
response = requests.request("POST", url, data=payload, headers=headers)
print("/login status code: " + str(response.status_code))
print(response.text)
if isServerPreconfigured():
app.config['ACCESS_TOKEN'] = json.loads(response.text)['access_token']
print("Server preconfigured")
return json.dumps({'message': 'Server preconfigured'}), status.HTTP_204_NO_CONTENT
else:
print("Client Auth Response")
# response.text, status.HTTP_200_OK
return json.dumps({'access_token': json.loads(response.text)['access_token']})
@app.route('/subscriptions', methods=['GET'])
def subscriptions():
''' Get the azure resources '''
if isServerPreconfigured():
token = app.config['ACCESS_TOKEN']
else:
print('using client token')
token = request.get_data().headers['token']
url = str.format(
"https://management.azure.com/subscriptions?api-version=2017-05-10")
print(url)
headers = {
'cache-control': "no-cache",
'authorization': 'Bearer ' + token
}
response = requests.request("GET", url, data='', headers=headers)
print(response.text)
return response.text, response.status_code
@app.route('/azureresources', methods=['POST'])
def resources():
''' Get the azure routes established by the client '''
if isServerPreconfigured():
token = app.config['ACCESS_TOKEN']
subscription = app.config['SUBSCRIPTION']
else:
print('using client token')
token = request.headers.get('token')
subscription = request.headers.get('subscription')
query = request.get_data().decode('utf-8')
url = str.format(
"https://management.azure.com/subscriptions/{0}{1}", subscription, query)
print(url)
headers = {
'cache-control': "no-cache",
'authorization': 'Bearer ' + token,
'host': 'management.azure.com'
}
response = requests.request("GET", url, data='', headers=headers)
print(response.text)
return response.text, response.status_code
@app.route('/azureroute', methods=['POST'])
def azureroute():
''' Get the azure routes established by the client '''
if isServerPreconfigured():
token = app.config['ACCESS_TOKEN']
else:
print('using client token')
token = request.headers.get('token')
resoure_url = request.get_data().decode('utf-8')
url = str.format(
"https://management.azure.com{0}?api-version=2017-05-10", resoure_url)
print(url)
headers = {
'cache-control': "no-cache",
'authorization': 'Bearer ' + token,
'host': 'management.azure.com'
}
response = requests.request("GET", url, data='', headers=headers)
print(response.text)
return response.text, response.status_code
@app.errorhandler(404)
def page_not_found():
''' Page no found message '''
return render_template('404.html'), 400
@app.errorhandler(500)
def internal_server_error():
''' Server error message '''
return render_template('500.html'), 500
@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
if __name__ == '__main__':
# add the context if you have your own ssl cert
# with this: context=('server.crt', 'server.key')
if app.config['PROTOCOL'] == '' or app.config['PROTOCOL'] == 'HTTPS':
ssl_context='adhoc'
elif app.config['PROTOCOL'] == 'HTTP':
ssl_context=None
app.run(debug=True,
host='0.0.0.0',
threaded=True,
port=int(app.config['PORT']),
ssl_context=ssl_context # self-sign cert
)