Add the authentication middleware for service.
[pti/o2.git] / o2common / authmw / authmiddleware.py
1 # Copyright (C) 2022 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 from werkzeug.wrappers import Request, Response
16 from o2common.helper import o2logging
17 from o2common.authmw.authprov import auth_definer
18
19 logger = o2logging.get_logger(__name__)
20
21
22 class AuthRequiredExp(Exception):
23     def __init__(self, value):
24         self.value = value
25
26     def dictize(self):
27         return {
28             'WWW-Authenticate': '{}'.format(self.value)}
29
30
31 class AuthFailureExp(Exception):
32     def __init__(self, value):
33         self.value = value
34
35     def dictize(self):
36         return {
37             'WWW-Authenticate': '{}'.format(self.value)}
38
39
40 def _response_wrapper(environ, start_response, header):
41     res = Response(headers=header,
42                    mimetype='text/plain', status=401)
43     return res(environ, start_response)
44
45
46 class authmiddleware():
47
48     '''
49     Auth WSGI middleware
50     '''
51
52     def __init__(self, app):
53         self.app = app
54
55     def __call__(self, environ, start_response):
56         logger.info(__name__ + 'authentication middleware')
57         req = Request(environ, populate_request=True, shallow=True)
58         try:
59             auth_header = req.headers['Authorization']
60
61             if auth_header:
62                 auth_token = auth_header.split(" ")[1]
63
64                 ad = auth_definer('oauth')
65                 # invoke underlying auth mdw to make k8s/keystone api
66                 ret = ad.authenticate(auth_token)
67                 if ret is True:
68                     logger.info(
69                         "auth success with oauth token: " + auth_token)
70                     return self.app(environ, start_response)
71                 else:
72                     raise AuthFailureExp(
73                         'Bearer realm="Authentication Failed"')
74             else:
75                 raise AuthRequiredExp('Bearer realm="Authentication Required"')
76         except AuthRequiredExp as ex:
77             return _response_wrapper(environ, start_response, ex.dictize())
78         except AuthFailureExp as ex:
79             return _response_wrapper(environ, start_response, ex.dictize())
80         except Exception:
81             hint = 'Bearer realm="Authentication Required"'
82             return _response_wrapper(environ, start_response,
83                                      AuthRequiredExp(hint).dictize())