b9aa510b5e4f2c7fc96f2d3ae0fa78ccf0633c25
[optf/osdf.git] / osdf / adapters / aaf / aaf_authentication.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #
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
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 import base64
20 from datetime import datetime
21 from datetime import timedelta
22 from flask import request
23 import re
24
25 from osdf.config.base import osdf_config
26 from osdf.logging.osdf_logging import debug_log
27 from osdf.logging.osdf_logging import error_log
28 from osdf.utils.interfaces import RestClient
29
30 AUTHZ_PERMS_USER = '{}/authz/perms/user/{}'
31
32 EXPIRE_TIME = 'expire_time'
33
34 perm_cache = {}
35 deploy_config = osdf_config.deployment
36
37
38 def clear_cache():
39     perm_cache.clear()
40
41
42 def authenticate(uid, passwd):
43     try:
44         perms = get_aaf_permissions(uid, passwd)
45         return has_valid_role(perms)
46     except Exception as exp:
47         error_log.error("Error Authenticating the user {} : {}: ".format(uid, exp))
48     return False
49
50
51 """
52 Check whether the user has valid permissions
53 return True if the user has valid permissions
54 else return false
55 """
56
57
58 def has_valid_role(perms):
59     aaf_user_roles = deploy_config['aaf_user_roles']
60
61     aaf_roles = get_role_list(perms)
62
63     for roles in aaf_user_roles:
64         path_perm = roles.split(':')
65         uri = path_perm[0]
66         perm = path_perm[1].split('|')
67         p = (perm[0], perm[1], perm[2].split()[0])
68         if re.search(uri, request.path) and p in aaf_roles:
69             return True
70     return False
71
72
73 """
74 Build a list of roles tuples from the AAF response.
75
76 """
77
78
79 def get_role_list(perms):
80     role_list = []
81     if perms:
82         roles = perms.get('roles')
83         if roles:
84             perm = roles.get('perm', [])
85             for p in perm:
86                 role_list.append((p['type'], p['instance'], p['action']))
87     return role_list
88
89
90 def get_aaf_permissions(uid, passwd):
91     key = base64.b64encode(bytes("{}_{}".format(uid, passwd), "ascii"))
92     time_delta = timedelta(minutes=deploy_config.get('aaf_cache_expiry_mins', 5))
93
94     perms = perm_cache.get(key)
95
96     if perms and datetime.now() < perms.get(EXPIRE_TIME):
97         debug_log.debug("Returning cached value")
98         return perms
99     debug_log.debug("Invoking AAF authentication API")
100     perms = {EXPIRE_TIME: datetime.now() + time_delta, 'roles': remote_api(passwd, uid)}
101     perm_cache[key] = perms
102     return perms
103
104
105 def remote_api(passwd, uid):
106     headers = {"Accept": "application/Users+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,"
107                          "*/*;q=1.0"}
108     url = AUTHZ_PERMS_USER.format(deploy_config['aaf_url'], uid)
109     rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug,
110                     req_id='aaf_user_id')
111     return rc.request(method='GET', asjson=True)