-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
executable file
·163 lines (119 loc) · 3.84 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
from flask import Flask, jsonify, request
import requests
from celery import Celery
import processing as proc
import json
SERVER_GO_URL = 'http://serverauth:3030'
SERVER_DB_URL = 'http://serverdb:3031'
app = Flask(__name__)
app.config.update(
CELERY_BROKER_URL='redis://redis:6379',
CELERY_RESULT_BACKEND='redis://redis:6379'
)
def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)
@celery.task(bind=True, time_limit=60)
def start_process(self, req):
self.update_state(state='PROGRESS', meta={
"client": req['uid'],
"output" : 'PROGRESS'
})
user = getUserSignatures(req['uid'])
meta = { "client": req['uid'] }
if(user is None):
meta = {
"client": req['uid'],
"output" : 'FAILURE',
"isAuthValid" : False,
"msg" : "invalid user id"
}
else:
try:
meta["isAuthValid"] = proc.process(req, user)
except:
meta = {
"client": req['uid'],
"output" : 'FAILURE',
"isAuthValid" : False,
"msg" : "Error while computing values",
}
try:
requests.post(f'{SERVER_GO_URL}/authAnswer', data=json.dumps({
"client": req['uid'],
"isAuthValid": meta["isAuthValid"]
}), headers={'Content-Type': 'application/json'})
meta["output"] = "SUCCESS"
except:
meta = {
"client": req['uid'],
"output" : 'FAILURE',
"isAuthValid": False,
"msg": "communication with auth server failed"
}
finally:
return meta
@app.route('/checkAuth', methods=['POST'])
def checkAuth():
req = request.get_json()
for attr in ["uid", "abs", "ord", "time"]:
if attr not in req.keys():
return
async_task = start_process.delay(req)
return jsonify({"taskid":async_task.id})
@app.route('/status/<task_id>', methods=['GET'])
def checkStatus(task_id):
task = start_process.AsyncResult(task_id)
status = task.info.get('output')
if status != 'FAILURE':
response = {
'state': status,
'client': task.info.get('client')
}
if 'isAuthValid' in task.info:
response['isAuthValid'] = task.info.get('isAuthValid', False)
else:
# something went wrong in the background job
response = {
'state': 'FAILURE',
'client': task.info.get('client'),
'msg': task.info.get('msg', ''),
'isAuthValid': False # Invalid authentification
}
if status != 'PROGRESS': # If task is finished, clear results
task.forget()
return jsonify(response)
def getUserSignatures(uid):
res = requests.get(f'{SERVER_DB_URL}/user/id/{uid}')
return res.json()[0]["signatures"]
if __name__ == '__main__':
app.debug = True
app.run()
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response