forked from alerta/alerta
/
views.py
919 lines (752 loc) · 26.3 KB
/
views.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
import datetime
from flask import g, request, render_template
from flask.ext.cors import cross_origin
from uuid import uuid4
from alerta.app import app, db
from alerta.app.switch import Switch
from alerta.app.auth import auth_required, admin_required
from alerta.app.utils import jsonify, jsonp, parse_fields, process_alert
from alerta.app.metrics import Timer
from alerta.alert import Alert
from alerta.heartbeat import Heartbeat
from alerta.plugins import RejectException
LOG = app.logger
# Set-up metrics
gets_timer = Timer('alerts', 'queries', 'Alert queries', 'Total time to process number of alert queries')
receive_timer = Timer('alerts', 'received', 'Received alerts', 'Total time to process number of received alerts')
delete_timer = Timer('alerts', 'deleted', 'Deleted alerts', 'Total time to process number of deleted alerts')
status_timer = Timer('alerts', 'status', 'Alert status change', 'Total time and number of alerts with status changed')
tag_timer = Timer('alerts', 'tagged', 'Tagging alerts', 'Total time to tag number of alerts')
untag_timer = Timer('alerts', 'untagged', 'Removing tags from alerts', 'Total time to un-tag number of alerts')
@app.route('/_', methods=['OPTIONS', 'PUT', 'POST', 'DELETE', 'GET'])
@cross_origin()
@jsonp
def test():
return jsonify(
status="ok",
method=request.method,
json=request.json,
data=request.data.decode('utf-8'),
args=request.args,
app_root=app.root_path,
)
@app.route('/')
def index():
rules = []
for rule in app.url_map.iter_rules():
if rule.endpoint not in ['test', 'static']:
rules.append(rule)
return render_template('index.html', rules=rules)
@app.route('/alerts', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_alerts():
gets_started = gets_timer.start_timer()
try:
query, sort, _, page, limit, query_time = parse_fields(request)
except Exception as e:
gets_timer.stop_timer(gets_started)
return jsonify(status="error", message=str(e)), 400
try:
severity_count = db.get_counts(query=query, fields={"severity": 1}, group="severity")
except Exception as e:
return jsonify(status="error", message=str(e)), 500
try:
status_count = db.get_counts(query=query, fields={"status": 1}, group="status")
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if limit < 1:
return jsonify(status="error", message="page 'limit' of %s is not valid" % limit), 416
total = sum(severity_count.values())
pages = ((total - 1) // limit) + 1
if total and page > pages or page < 0:
return jsonify(status="error", message="page out of range: 1-%s" % pages), 416
fields = dict()
fields['history'] = {'$slice': app.config['HISTORY_LIMIT']}
try:
alerts = db.get_alerts(query=query, fields=fields, sort=sort, page=page, limit=limit)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
alert_response = list()
if len(alerts) > 0:
last_time = None
for alert in alerts:
body = alert.get_body()
body['href'] = "%s/%s" % (request.base_url.replace('alerts', 'alert'), alert.id)
if not last_time:
last_time = body['lastReceiveTime']
elif body['lastReceiveTime'] > last_time:
last_time = body['lastReceiveTime']
alert_response.append(body)
gets_timer.stop_timer(gets_started)
return jsonify(
status="ok",
total=total,
page=page,
pageSize=limit,
pages=pages,
more=page < pages,
alerts=alert_response,
severityCounts=severity_count,
statusCounts=status_count,
lastTime=last_time,
autoRefresh=Switch.get('auto-refresh-allow').is_on(),
)
else:
gets_timer.stop_timer(gets_started)
return jsonify(
status="ok",
message="not found",
total=total,
page=page,
pageSize=limit,
pages=pages,
more=False,
alerts=[],
severityCounts=severity_count,
statusCounts=status_count,
lastTime=query_time,
autoRefresh=Switch.get('auto-refresh-allow').is_on()
)
@app.route('/alerts/history', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_history():
try:
query, _, _, _, limit, query_time = parse_fields(request)
except Exception as e:
return jsonify(status="error", message=str(e)), 400
try:
history = db.get_history(query=query, limit=limit)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
for alert in history:
alert['href'] = "%s/%s" % (request.base_url.replace('alerts/history', 'alert'), alert['id'])
if len(history) > 0:
return jsonify(
status="ok",
history=history,
lastTime=history[-1]['updateTime']
)
else:
return jsonify(
status="ok",
message="not found",
history=[],
lastTIme=query_time
)
@app.route('/alert', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def receive_alert():
recv_started = receive_timer.start_timer()
try:
incomingAlert = Alert.parse_alert(request.data)
except ValueError as e:
receive_timer.stop_timer(recv_started)
return jsonify(status="error", message=str(e)), 400
if g.get('customer', None):
incomingAlert.customer = g.get('customer')
if request.headers.getlist("X-Forwarded-For"):
incomingAlert.attributes.update(ip=request.headers.getlist("X-Forwarded-For")[0])
else:
incomingAlert.attributes.update(ip=request.remote_addr)
try:
alert = process_alert(incomingAlert)
except RejectException as e:
receive_timer.stop_timer(recv_started)
return jsonify(status="error", message=str(e)), 403
except RuntimeWarning as e:
receive_timer.stop_timer(recv_started)
return jsonify(status="ok", id=incomingAlert.id, message=str(e)), 202
except Exception as e:
receive_timer.stop_timer(recv_started)
return jsonify(status="error", message=str(e)), 500
receive_timer.stop_timer(recv_started)
if alert:
body = alert.get_body()
body['href'] = "%s/%s" % (request.base_url, alert.id)
return jsonify(status="ok", id=alert.id, alert=body), 201, {'Location': '%s/%s' % (request.base_url, alert.id)}
else:
return jsonify(status="error", message="insert or update of received alert failed"), 500
@app.route('/alert/<id>', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_alert(id):
try:
alert = db.get_alert(id=id)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if alert:
if g.get('role', None) != 'admin' and not alert.customer == g.get('customer', None):
return jsonify(status="error", message="not found", total=0, alert=None), 404
body = alert.get_body()
body['href'] = request.base_url
return jsonify(status="ok", total=1, alert=body)
else:
return jsonify(status="error", message="not found", total=0, alert=None), 404
@app.route('/alert/<id>/status', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def set_status(id):
# FIXME - should only allow role=user to set status for alerts for that customer
status_started = status_timer.start_timer()
data = request.json
if data and 'status' in data:
try:
alert = db.set_status(id=id, status=data['status'], text=data.get('text', ''))
except Exception as e:
return jsonify(status="error", message=str(e)), 500
else:
status_timer.stop_timer(status_started)
return jsonify(status="error", message="must supply 'status' as parameter"), 400
if alert:
status_timer.stop_timer(status_started)
return jsonify(status="ok")
else:
status_timer.stop_timer(status_started)
return jsonify(status="error", message="not found"), 404
@app.route('/alert/<id>/tag', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def tag_alert(id):
# FIXME - should only allow role=user to set status for alerts for that customer
tag_started = tag_timer.start_timer()
data = request.json
if data and 'tags' in data:
try:
response = db.tag_alert(id, data['tags'])
except Exception as e:
return jsonify(status="error", message=str(e)), 500
else:
tag_timer.stop_timer(tag_started)
return jsonify(status="error", message="must supply 'tags' as list parameter"), 400
tag_timer.stop_timer(tag_started)
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/alert/<id>/untag', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def untag_alert(id):
# FIXME - should only allow role=user to set status for alerts for that customer
untag_started = untag_timer.start_timer()
data = request.json
if data and 'tags' in data:
try:
response = db.untag_alert(id, data['tags'])
except Exception as e:
return jsonify(status="error", message=str(e)), 500
else:
untag_timer.stop_timer(untag_started)
return jsonify(status="error", message="must supply 'tags' as list parameter"), 400
untag_timer.stop_timer(untag_started)
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/alert/<id>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_alert(id):
if (request.method == 'DELETE' or
(request.method == 'POST' and '_method' in request.json and request.json['_method'] == 'delete')):
started = delete_timer.start_timer()
try:
response = db.delete_alert(id)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
delete_timer.stop_timer(started)
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
# Return severity and status counts
@app.route('/alerts/count', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_counts():
try:
query, _, _, _, _, _ = parse_fields(request)
except Exception as e:
return jsonify(status="error", message=str(e)), 400
try:
severity_count = db.get_counts(query=query, fields={"severity": 1}, group="severity")
except Exception as e:
return jsonify(status="error", message=str(e)), 500
try:
status_count = db.get_counts(query=query, fields={"status": 1}, group="status")
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if sum(severity_count.values()):
return jsonify(
status="ok",
total=sum(severity_count.values()),
severityCounts=severity_count,
statusCounts=status_count
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
severityCounts=severity_count,
statusCounts=status_count
)
@app.route('/alerts/top10', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_top10():
try:
query, _, group, _, _, _ = parse_fields(request)
except Exception as e:
return jsonify(status="error", message=str(e)), 400
try:
top10 = db.get_topn(query=query, group=group, limit=10)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
for item in top10:
for resource in item['resources']:
resource['href'] = "%s/%s" % (request.base_url.replace('alerts/top10', 'alert'), resource['id'])
if top10:
return jsonify(
status="ok",
total=len(top10),
top10=top10
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
top10=[],
)
@app.route('/environments', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_environments():
try:
query, _, _, _, limit, _ = parse_fields(request)
except Exception as e:
return jsonify(status="error", message=str(e)), 400
try:
environments = db.get_environments(query=query, limit=limit)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if environments:
return jsonify(
status="ok",
total=len(environments),
environments=environments
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
environments=[],
)
@app.route('/services', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_services():
try:
query, _, _, _, limit, _ = parse_fields(request)
except Exception as e:
return jsonify(status="error", message=str(e)), 400
try:
services = db.get_services(query=query, limit=limit)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if services:
return jsonify(
status="ok",
total=len(services),
services=services
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
services=[],
)
@app.route('/blackouts', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def get_blackouts():
try:
blackouts = db.get_blackouts()
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if len(blackouts):
return jsonify(
status="ok",
total=len(blackouts),
blackouts=blackouts,
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
blackouts=[],
time=datetime.datetime.utcnow()
)
@app.route('/blackout', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def create_blackout():
if request.json and 'environment' in request.json:
environment = request.json['environment']
else:
return jsonify(status="error", message="must supply 'environment' as parameter"), 400
resource = request.json.get("resource", None)
service = request.json.get("service", None)
event = request.json.get("event", None)
group = request.json.get("group", None)
tags = request.json.get("tags", None)
start_time = request.json.get("startTime", None)
end_time = request.json.get("endTime", None)
duration = request.json.get("duration", None)
if start_time:
start_time = datetime.datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S.%fZ')
if end_time:
end_time = datetime.datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S.%fZ')
try:
blackout = db.create_blackout(environment, resource, service, event, group, tags, start_time, end_time, duration)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
return jsonify(status="ok", blackout=blackout), 201, {'Location': '%s/%s' % (request.base_url, blackout)}
@app.route('/blackout/<path:blackout>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_blackout(blackout):
if request.method == 'DELETE' or (request.method == 'POST' and request.json['_method'] == 'delete'):
try:
response = db.delete_blackout(blackout)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/heartbeats', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_heartbeats():
try:
heartbeats = db.get_heartbeats()
except Exception as e:
return jsonify(status="error", message=str(e)), 500
hb_list = list()
for hb in heartbeats:
body = hb.get_body()
if g.get('role', None) != 'admin' and not body['customer'] == g.get('customer', None):
continue
body['href'] = "%s/%s" % (request.base_url.replace('heartbeats', 'heartbeat'), hb.id)
hb_list.append(body)
if hb_list:
return jsonify(
status="ok",
total=len(heartbeats),
heartbeats=hb_list,
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
heartbeats=hb_list,
time=datetime.datetime.utcnow()
)
@app.route('/heartbeat', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def create_heartbeat():
try:
heartbeat = Heartbeat.parse_heartbeat(request.data)
except ValueError as e:
return jsonify(status="error", message=str(e)), 400
if g.get('role', None) != 'admin':
heartbeat.customer = g.get('customer', None)
try:
heartbeat = db.save_heartbeat(heartbeat)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
body = heartbeat.get_body()
body['href'] = "%s/%s" % (request.base_url, heartbeat.id)
return jsonify(status="ok", id=heartbeat.id, heartbeat=body), 201, {'Location': '%s/%s' % (request.base_url, heartbeat.id)}
@app.route('/heartbeat/<id>', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_heartbeat(id):
try:
heartbeat = db.get_heartbeat(id=id)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if heartbeat:
if g.get('role', None) != 'admin' and not heartbeat.customer == g.get('customer', None):
return jsonify(status="error", message="not found", total=0, alert=None), 404
body = heartbeat.get_body()
body['href'] = request.base_url
return jsonify(status="ok", total=1, heartbeat=body)
else:
return jsonify(status="error", message="not found", total=0, heartbeat=None), 404
@app.route('/heartbeat/<id>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_heartbeat(id):
if request.method == 'DELETE' or (request.method == 'POST' and request.json['_method'] == 'delete'):
try:
response = db.delete_heartbeat(id)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/users', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def get_users():
try:
users = db.get_users()
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if len(users):
return jsonify(
status="ok",
total=len(users),
users=users,
domains=app.config['ALLOWED_EMAIL_DOMAINS'],
orgs=app.config['ALLOWED_GITHUB_ORGS'],
groups=app.config['ALLOWED_GITLAB_GROUPS'],
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
users=[],
domains=app.config['ALLOWED_EMAIL_DOMAINS'],
orgs=app.config['ALLOWED_GITHUB_ORGS'],
time=datetime.datetime.utcnow()
)
@app.route('/user', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def create_user():
if request.json and 'name' in request.json:
name = request.json["name"]
login = request.json["login"]
password = request.json.get("password", None)
provider = request.json["provider"]
text = request.json.get("text", "")
try:
user = db.save_user(str(uuid4()), name, login, password, provider, text)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
else:
return jsonify(status="error", message="must supply user 'name', 'login' and 'provider' as parameters"), 400
if user:
return jsonify(status="ok", user=user), 201, {'Location': '%s/%s' % (request.base_url, user)}
else:
return jsonify(status="error", message="User with that login already exists"), 409
@app.route('/user/<user>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_user(user):
if request.method == 'DELETE' or (request.method == 'POST' and request.json['_method'] == 'delete'):
try:
response = db.delete_user(user)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/customers', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def get_customers():
try:
customers = db.get_customers()
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if len(customers):
return jsonify(
status="ok",
total=len(customers),
customers=customers,
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
customers=[],
time=datetime.datetime.utcnow()
)
@app.route('/customer', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def create_customer():
if request.json and 'customer' in request.json and 'match' in request.json:
customer = request.json["customer"]
match = request.json["match"]
try:
cid = db.create_customer(customer, match)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
else:
return jsonify(status="error", message="must supply user 'customer' and 'match' as parameters"), 400
if cid:
return jsonify(status="ok", id=cid), 201, {'Location': '%s/%s' % (request.base_url, cid)}
else:
return jsonify(status="error", message="Customer lookup for this match already exists"), 409
@app.route('/customer/<customer>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_customer(customer):
if request.method == 'DELETE' or (request.method == 'POST' and request.json['_method'] == 'delete'):
try:
response = db.delete_customer(customer)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404
@app.route('/keys', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_keys():
query = dict()
if g.get('role', None) != 'admin':
query['customer'] = g.get('customer')
try:
keys = db.get_keys(query)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if len(keys):
return jsonify(
status="ok",
total=len(keys),
keys=keys,
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
keys=[],
time=datetime.datetime.utcnow()
)
@app.route('/keys/<user>', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
@jsonp
def get_user_keys(user):
query = {"user": user}
if g.get('role', None) != 'admin':
query['customer'] = g.get('customer')
try:
keys = db.get_keys(query)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if len(keys):
return jsonify(
status="ok",
total=len(keys),
keys=keys,
time=datetime.datetime.utcnow()
)
else:
return jsonify(
status="ok",
message="not found",
total=0,
keys=[],
time=datetime.datetime.utcnow()
)
@app.route('/key', methods=['OPTIONS', 'POST'])
@cross_origin()
@auth_required
@jsonp
def create_key():
if request.json and 'user' in request.json:
user = request.json['user']
else:
return jsonify(status="error", message="must supply 'user' as parameter"), 400
type = request.json.get("type", "read-only")
if type not in ['read-only', 'read-write']:
return jsonify(status="error", message="API key must be read-only or read-write"), 400
customer = g.get('customer', None) or request.json.get("customer", None)
text = request.json.get("text", "API Key for %s" % user)
try:
key = db.create_key(user, type, customer, text)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
return jsonify(status="ok", key=key), 201, {'Location': '%s/%s' % (request.base_url, key)}
@app.route('/key/<path:key>', methods=['OPTIONS', 'DELETE', 'POST'])
@cross_origin()
@auth_required
@admin_required
@jsonp
def delete_key(key):
query = {"key": key}
if not db.get_keys(query):
return jsonify(status="error", message="not found"), 404
if request.method == 'DELETE' or (request.method == 'POST' and request.json['_method'] == 'delete'):
try:
response = db.delete_key(key)
except Exception as e:
return jsonify(status="error", message=str(e)), 500
if response:
return jsonify(status="ok")
else:
return jsonify(status="error", message="not found"), 404