This repository has been archived by the owner on Nov 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.py
55 lines (41 loc) · 1.99 KB
/
server.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
from flask import Flask, request, jsonify, request_started, request_finished
from jwkest.jwk import SYMKey
from cachelib import SimpleCache
from exceptions import HttpException
from signals import OrderedSignalHandler, ReplayPreventionSignalHandler, \
RateLimitingSignalHandler, EncryptionSignalHandler, TokenSignalHandler
app = Flask(__name__)
cache = SimpleCache()
replay_prevention_signal_handler = ReplayPreventionSignalHandler(cache)
rate_limiting_signal_handler = RateLimitingSignalHandler(cache, 1, 10)
token_signal_handler = TokenSignalHandler(
[SYMKey(use="sig", kid="key1", key="bc926745ef6c8dda6ed2689d08d5793d7525cb81")], leeway=1, cache=cache)
encryption_signal_handler = EncryptionSignalHandler(
[SYMKey(use="enc", kid="key1", key="bc926745ef6c8dda6ed2689d08d5793d7525cb81")])
signal_handler = OrderedSignalHandler(replay_prevention_signal_handler,
rate_limiting_signal_handler,
token_signal_handler,
encryption_signal_handler)
request_started.connect(signal_handler.request_started_handler, app)
request_finished.connect(signal_handler.request_finished_handler, app)
@app.errorhandler(Exception)
def error_handler(exception: Exception):
if isinstance(exception, HttpException):
response = jsonify({'error': exception.message}), exception.code
else:
response = jsonify({'error': str(exception)}), 500
return response
@app.route('/', methods=('GET', 'POST'))
def root():
if request.method == 'POST':
try:
name = request.json['name']
if not isinstance(name, str) or not 0 < len(name) < 26:
raise HttpException("Name attribute must be a string between 1 and 25 characters", 400)
except (TypeError, KeyError):
raise HttpException("Must be JSON object with a name attribute!", 400)
else:
name = 'World!'
return jsonify(Hello=name), 200
if __name__ == '__main__':
app.run()