1 # -------------------------------------------------------------------------
2 # Copyright (c) 2015-2017 AT&T Intellectual Property
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 # -------------------------------------------------------------------------
21 from datetime import datetime, timedelta
22 from flask import request
24 from osdf.config.base import osdf_config
25 from osdf.logging.osdf_logging import error_log, debug_log
26 from osdf.utils.interfaces import RestClient
28 AUTHZ_PERMS_USER = '{}/authz/perms/user/{}'
30 EXPIRE_TIME = 'expire_time'
33 deploy_config = osdf_config.deployment
40 def authenticate(uid, passwd):
42 perms = get_aaf_permissions(uid, passwd)
43 return has_valid_role(perms)
44 except Exception as exp:
45 error_log.error("Error Authenticating the user {} : {}: ".format(uid, exp))
51 Check whether the user has valid permissions
52 return True if the user has valid permissions
57 def has_valid_role(perms):
58 aaf_user_roles = deploy_config['aaf_user_roles']
60 for roles in aaf_user_roles:
61 path_perm = roles.split(':')
63 role = path_perm[1].split('|')[0]
64 if re.search(uri, request.path) and perms:
65 roles = perms.get('roles')
67 perm_list = roles.get('perm')
74 Make the remote aaf api call if user is not in the cache.
78 def get_aaf_permissions(uid, passwd):
79 key = base64.b64encode(bytes("{}_{}".format(uid, passwd), "ascii"))
80 time_delta = timedelta(hours=deploy_config.get('aaf_cache_expiry_hrs', 3))
82 perms = perm_cache.get(key)
84 if perms and datetime.now() < perms.get(EXPIRE_TIME):
85 debug_log.debug("Returning cached value")
87 debug_log.debug("Invoking AAF authentication API")
88 perms = {EXPIRE_TIME: datetime.now() + time_delta, 'roles': remote_api(passwd, uid)}
89 perm_cache[key] = perms
93 def remote_api(passwd, uid):
94 headers = {"Accept": "application/Users+xml;q=1.0;charset=utf-8;version=2.0,text/xml;q=1.0;version=2.0",
95 "Accept": "application/Users+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"}
96 url = AUTHZ_PERMS_USER.format(deploy_config['aaf_url'], uid)
97 rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug,
99 return rc.request(method='GET', asjson=True)