-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.bak.py
More file actions
executable file
·335 lines (283 loc) · 9.87 KB
/
app.bak.py
File metadata and controls
executable file
·335 lines (283 loc) · 9.87 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#!/usr/bin/env python3
'''
HTTP Codes
---
200: OK
201: Created
401: Unauthorized
404: Not Found
501: Not Implemented
URL
---
https://github.com/FMI-Test/api
'''
from flask import Flask, abort, request, Response, jsonify
from flask_cors import CORS
from flask_restplus import Resource, Api, fields, marshal
from functools import wraps
from os import path
from os.path import getmtime
from werkzeug.exceptions import BadRequest
from InvalidUsage import *
from utils import *
import datetime
import dateutil.parser
import json
import re
import os
import os.path
import pprint
import socket
import sys
import time
import requests
# Add parent directory to path
sys.path.append(os.path.abspath (os.path.join(os.path.dirname(__file__), '..')))
PATH = os.path.dirname(os.path.abspath(__file__))
API_PORT = 5100 if isLocal() else 80
API_PREFIX = '/gr2/api/tar'
API_PROTOCOL = 'http://'
API_HOST = '0.0.0.0'
PORT_IN_PATH = ':'+str(API_PORT) if API_PORT != 80 else ''
CONFIG_PATH = os.path.dirname (os.path.abspath (__file__))+'/config'
CONFIG_EXTENSION = '.conf'
API_PATH = API_PROTOCOL+API_HOST+PORT_IN_PATH+API_PREFIX
API_LOCAL_PATH = API_PROTOCOL+API_HOST+PORT_IN_PATH+API_PREFIX
API_PUBLIC_OAS = API_PROTOCOL+API_HOST+PORT_IN_PATH
API_PUBLIC_PATH = API_PROTOCOL+API_HOST+PORT_IN_PATH+API_PREFIX
OAS_URI = API_PATH+'/swagger.json'
OAS_PATH = PATH+'/swagger.json'
AWS_TEXT = 'AWS_PROFILE=<ACCOUNT_ID>/p-eng>'
SSO_TEXT = 'Single-Sign-On ID'
ACC_TEXT = 'AWS Account ID'
cors_config = CORS(
allow_origin=API_PATH,
allow_headers=['X-Special-Header'],
max_age=10,
expose_headers=['X-Special-Header'],
allow_credentials=True
)
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'X-API-KEY' in request.headers:
token = request.headers['X-API-KEY']
if not token:
return {'message': 'Token is missing.'}, 401
if token != 'mytoken':
return {'message': 'Invalid Token !'}, 401
print('TOKEN: {}'.format(token))
return f(*args, **kwargs)
return decorated
def utcDate(time, iso=True):
dt = datetime.datetime.utcfromtimestamp (time)
return dt.isoformat()+'Z' if iso else dt
def isValidSid (sid):
#whitelist sid
return True
app = Flask(__name__)
authorizations = {
'apikey': {
'type': 'apikey',
'in': 'header',
'name': 'X-API-KEY'
}
}
CORS(app)
###############################################################################
# Error Handling
###############################################################################
errors = {
'BadRequest': {
'message': "Bad request.",
'status': 400,
},
'NotFound':{
'message': "Not found.",
'status': 404,
},
'UserAlreadyExistsError': {
'message': "A user with that username already exists.",
'status': 409,
},
'ResourceDoesNotExist': {
'message': "A resource with that ID no longer exists.",
'status': 410,
'extra': "Any extra information we want.",
},
'ResourceNotImplemented': {
'message': "Requested fucntionality planned but not implemented.",
'status': 501,
'extra': "Any extra information you want.",
},
}
@app.route("/")
def hello_world():
return "<p style='font-family:Consolas;font-size: 0.9em;'>Hello, World!</p>"
"""
api = Api(app,
authorizations=authorizations,
catch_all_404s=True,
errors=errors,
version='0.1.0',
prefix=API_PREFIX,
title='Temporary Access Request',
description='** Temporary Access Request** is Managed API to manage Temporary Access Request for AWS Accounts',
contact_email='gr2@example.com',
default_mediatype='application/json'
# default_mediatype=u'application/json'
)
def metricsDecorator(rs):
res = {'Items': [], 'Count': 0}
for k in rs:
print(k)
print(rs[k])
res['Items'].append(rs[k])
res['Items'] = sorted(res['Items'], key=lambda x: (x['ts']))
res['Count'] = len(res['Items'])
return res
def getFile(file):
# if isLocal():
# return jsonify({ 'Action': 'Local execution of getFile('+file+')'})
res = {}
try:
with open(file, 'r') as f:
res = json.load(f)
except Exception as err:
abort(400, 'Requested file not fund!')
return jsonify(res)
def putFile(file, data):
# if isLocal():
# return jsonify({ 'Action': 'Local execution of putFile('+file+',data)'})
try:
with open(file, 'w') as f:
json.dump(data, f, default=str, sort_keys=True, indent=2, separators=(',', ': '))
return True
except Exception as err:
abort(400, 'Unable to write file!')
def end_points(search='', replace=''):
# https://medium.com/better-programming/linux-systemctl-46bd0a11e27b
rs = [
'/operations',
'/access/request/{sso}/{acc}',
'/access/review/{rid}',
'/access/responce/{rid}',
'review/request/{sso}/{acc}',
'review/requests/{sso}',
'review/account/{acc}',
'request/approve/{rid}',
'request/deny/{rid}',
'request/expire/{rid}',
'request/extend/{rid}',
#new
]
res = []
for r in rs:
res.append(r.replace(search, replace))
return res
def dotLine():
return '.............................................................................'
print(dotLine())
print('FLASK RESTFUL PLUS SERVER')
print(json.dumps (end_points(), indent=2, sort_keys=True))
print('SERVER TIMER .............. {}'.format(datetime.datetime.now()))
print('API_LOCAL_PATH ............ {}'.format(API_LOCAL_PATH))
print('API_PUBLIC_PATH ........... {}'.format('NA' if isLocal() else API_PUBLIC_PATH))
print(dotLine())
print('Ctrl+C to Stop the server ...')
print(dotLine())
###############################################################################
# Parameter-less Endpoints
###############################################################################
@api.route('/operations')
@api.doc(description='List lTemporay Access Review Operations.')
class ListOperatations(Resource):
def get(self):
return getFile(PATH+'/api.json')
###############################################################################
# Parametered Endpoints
###############################################################################
@api.route('/access/request/<string:sso>/<string:acc>')
@api.doc(description='Request Temporary Access API endpoints for an AWS Account.')
@api.doc(params={'sso': SSO_TEXT, 'acc': ACC_TEXT})
class ListEndPoints(Resource):
def get(self, sid):
return jsonify(end_points('{sid}', sid))
###############################################################################
# Parametered Slicer
###############################################################################
@api.route('/slicer/<string: sid>/config')
@api.doc(description='Live Slicer Config File.')
@api.doc(params={'sid': SSO_TEXT})
class SlicerConfig(Resource):
@api.doc(security='apikey')
@api.doc(params={
'sid': {'in': 'path', 'description': 'Slicer ID i.e. kcop_fxa_s, slce096_fxb'},
'cfg_content': {'in': 'form', 'description': 'Config File Content'}
})
def post(self, sid):
file=CONFIG_PATH+'/'+sid+CONFIG_EXTENSION
data = request.form['cfg_content']
print('CONFIG FILE: {}'.format(sid+CONFIG_EXTENSION))
print('CONFIG CONTENT ------------------------------------')
print(data)
res = putFile(file, data)
print('Result: {}'.format(res))
return jsonify({'message': 'Update slicer config for Slicer ID: '+sid})
def get(self, sid):
res = {}
return jsonify({'message':'Slicer'+sid, 'data': res})
@api.route('/slicer/<string: sid>/install/<string:ver>')
@api.doc (description='NOT IMPLEMENTED, Install specific version of Live Slicer.')
@api.doc (params={'sid': SSO_TEXT, 'ver': 'Slicer Version to install.'})
class SlicerInstallVersion(Resource):
@api.doc(security='apikey')
def post(self, sid, ver):
return Response(
response = jsonify({'message': 'Installing Slicer version '+str(ver)+' for Slicer ID '+sid}),
status=501, mimetype='application/ison')
# slicer pid
@api.route('/slicer/<string:sid>/content-start')
@api.doc(description='Live Slicer local API call to start content.')
@api.doc(params={'sid': SSO_TEXT})
class SlicerApiContentStart(Resource):
def get(self, sid):
res = {}
port_id = 1234
api_uri = 'http://localhost:{}/content-start'.format(str(port_id))
print('\tAPI URL: {}'.format(api_uri))
print(api)
print(api.route)
try:
req = requests.get(api_uri)
res = json.loads(req.text)
except Exception as e:
res['URLError'] = 1
res['URLErrorMessage'] = str(e)
return jsonify({'message': 'Service API Call', 'data': res})
# limit size and line count
@api.route('/slicer/<string:sid>/log')
@api.doc (description='Live Slicer recent log.')
@api.doc (params={'sid': SSO_TEXT})
class SlicerLog (Resource):
def get(self, sid):
res = {}
return jsonify({'message': 'Slicer recent log: '+sid, 'data': res})
@api.route('/slicer/<string:sid>/oldlogs')
@api.doc(description='NOT IMPLEMENTED, Live Slicer archived log files.')
@api.doc(params={'sid': SSO_TEXT})
class SliceroldLog (Resource):
def get(self, sid):
return Response(
response = jsonify({'message': 'Get Slicer Old Log for Slicer ID '+sid}),
status=501, mimetype='application/json')
@api.route('/slicer/<string:sid>/start')
@api.doc(description='Start Live Slicer, ')
@api.doc(params={'sid': SSO_TEXT})
class SlicerStart (Resource):
@api.doc(security='apikey')
def post(self, sid):
res = {}
return jsonify({'message': 'Start Slicer : '+sid})
"""