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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 from requests.exceptions import ConnectTimeout, ReadTimeout
17 import yarf.restfullogger as logger
18 from yarf.authentication.base_auth import BaseAuthMethod
19 from access_management.backend.authsender import AuthSender
20 from yarf.restfulargs import RestConfig
21 from yarf.helpers import remove_secrets
24 class AMAuth(BaseAuthMethod):
26 super(AMAuth, self).__init__()
29 conf = config.get_section("AM", format='dict')
30 self.logger = logger.get_logger()
32 self.host = conf['host']
33 self.port = conf['port']
34 except KeyError as error:
35 self.logger.error("Failed to find all the needed parameters. Authentication with AM not possible: {}"
37 self.sender = AuthSender(self.host, self.port)
40 def get_info(request):
41 splitted = request.full_path.split("/", 3)
43 domain_object = splitted[3].split("?")[0]
44 return domain, domain_object
47 # touple[0]: true if authenticated
48 # touple[1]: the username for this request
49 def get_authentication(self, request):
52 domain, domain_object = self.get_info(request)
53 method = request.method.upper()
54 except IndexError as error:
55 self.logger.error("Failed to get domain, object or method from request %s", str(error))
59 token = request.headers.get("X-Auth-Token", type=str)
61 self.logger.error("Failed to get the authentication token from request")
63 parameters = {'token': token, 'domain': domain, 'domain_object': domain_object, 'method': method}
66 response = self.sender.send_request(parameters)
67 self.logger.debug(response)
69 if response['username'] != '':
70 username = response['username']
71 if response.get('authorized', None) is not None:
72 if response['authorized']:
73 self.logger.info('User {} is authorized for accessing the given domain {}'.format(response[
74 'username'], remove_secrets(request.full_path)))
77 self.logger.info('User {} is not authorized for accessing the given domain {}'.format(response[
78 'username'], remove_secrets(request.full_path)))
80 self.logger.info('Token({}) is not valid for accessing the given domain {}'.format(token,
81 remove_secrets(request.full_path)))
82 except (ConnectTimeout, ReadTimeout) as e:
83 self.logger.error('Failed to communicate with the authentication server. The following error occurred: {}'.
85 return False, username