-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.py
More file actions
127 lines (99 loc) · 4.78 KB
/
middleware.py
File metadata and controls
127 lines (99 loc) · 4.78 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
import jwt
import falcon
import json
import sqlalchemy.orm.scoping as scoping
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler('test.log'))
logger.setLevel(logging.INFO)
class JWTAuthenticator(object):
def process_request(self, req, resp):
if req.method == "OPTIONS":
return
token = req.get_header('Authorization')
if req.path != '/register' and req.path != '/login' and 'confirmation' not in req.path:
if token is None:
description = ('Please provide an auth token '
'as part of the request.')
raise falcon.HTTPUnauthorized('Auth token required',
description,
href='http://docs.example.com/auth')
if token != None:
try:
token = token.split()
decoded_token = jwt.decode(token[1], 'habberdashery212', algorithm='HS512', verify=False)
req.context['user'] = decoded_token['user']
except jwt.exceptions.DecodeError:
description = ('The provided auth token is not valid. '
'Please request a new token and try again.')
description += token[2]
raise falcon.HTTPUnauthorized('Authentication required',
description,
href='http://docs.example.com/auth',
scheme='Token; UUID')
def process_response(self, req, resp, resource):
if 'user' in req.context:
if req.context['user'] is not None:
if 'result' in req.context:
result = req.context['result']
token_input = result.copy()
token_input['user'] = req.context['user']
token = jwt.encode(token_input, 'habberdashery212', algorithm='HS512')
if req.path!='/register':
resp.set_header('Authorization', "Bearer " + token.decode('utf-8'))
result['token'] = "Bearer " + token.decode('utf-8')
class SQLAlchemySessionManager(object):
def __init__(self, session_factory, auto_commit=False):
self._session_factory = session_factory
self._scoped = isinstance(session_factory, scoping.ScopedSession)
self._auto_commit = auto_commit
def process_request(self, req, resp):
req.context['session'] = self._session_factory
def process_response(self, req, resp, params):
session = req.context['session']
if self._auto_commit:
session.commit()
if self._scoped:
session.remove()
else:
session.close()
class RequireJSON(object):
def process_request(self, req, resp):
if not req.client_accepts_json:
raise falcon.HTTPNotAcceptable(
'This API only supports responses encoded as JSON.',
href='http://docs.examples.com/api/json')
if req.method in ('POST', 'PUT'):
if req.content_type is not None:
if 'application/json' not in req.content_type:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports requests encoded as JSON.',
href='http://docs.examples.com/api/json')
class JSONTranslator(object):
def process_request(self, req, resp):
# req.stream corresponds to the WSGI wsgi.input environ variable,
# and allows you to read bytes from the request body.
#
# See also: PEP 3333
if req.content_length in (None, 0):
# Nothing to do
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['doc'] = json.loads(body.decode('utf-8'))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')
def process_response(self, req, resp, resource):
if 'result' not in req.context:
return
resp.body = json.dumps(req.context['result'])
class ResponseLoggerMiddleware(object):
def process_response(self, req, resp, resource):
logger.info('{0} {1} {2} {3}'.format(req.method, req.relative_uri, resp.status[:3], req.context['result']))