Eclectic Media Git auto_bandwidth_test / ca48474
Added a Flask API to handle reporting of results Ariana Giroux 3 months ago
3 changed file(s) with 83 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 import os
1 import jwt
2 import time
3 import sys
4 from json import dumps
5 from pprint import pprint
6 from flask import Flask, jsonify, request, abort
7 from flask_restplus import Api
8
9 from lib.authorization import token_required, authorizations
10
11 app = Flask(__name__)
12 app.secret_key = os.urandom(24)
13
14
15 def generate_token():
16 token = jwt.encode({'user': 'tester'}, app.config['SECRET_KEY'])
17 with open('mykey', 'w+') as keyfile:
18 keyfile.write(token.decode('UTF-8'))
19
20
21 @app.route('/', methods=['PUT'])
22 @token_required
23 def put_data():
24 json_data = request.get_json()
25 submission_instance = [time.asctime()]
26
27 if not list(json_data).count('data'):
28 abort(400, "missing 'data' json key!")
29
30 if not json_data['data'][0].count('[ 3]'):
31 abort(400, "bad data!")
32
33 submission_instance.append(json_data['data'])
34
35 with open('bandwidth_test.log', 'a+') as f:
36 f.write(dumps(submission_instance))
37
38 return 'submission ok'
39
40
41 if __name__ == '__main__':
42 if sys.argv.count('--generate'):
43 generate_token()
44
45 app.run()
(New empty file)
0 import sys
1
2 from flask import request, abort
3 from functools import wraps
4
5
6 def token_required(func):
7 """ Ensure that endpoint is only accessible if the request has a valid token. """
8 @wraps(func)
9 def decorated(*args, **kwargs):
10 if 'X-API-KEY' in request.headers:
11 token = request.headers['X-API-KEY']
12
13 if token != key:
14 abort(401, 'Authorization attempt is missing or invalid')
15
16 else:
17 abort(401, 'Authorization attempt is missing or invalid')
18 # TODO return error on no token
19 return func(*args, **kwargs)
20 return decorated
21
22 authorizations = {
23 'apikey': {
24 'type': 'apiKey',
25 'in': 'header',
26 'name': 'X-API-KEY'
27 }
28 }
29
30 if not sys.argv.count('--generate'):
31 try:
32 with open('mykey') as keyfile: # TODO replace
33 key = keyfile.read().strip('\n')
34 except FileNotFoundError as e:
35 sys.stderr.write('Could not find keyfile! Make sure your JWT key is available at "./mykey"!\n')
36 exit(1)