2a72c306c12343bd10e6898c0451461d5129224d
[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 import re
21 from datetime import datetime, timedelta
22 from flask import request
23
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
27
28 AUTHZ_PERMS_USER = '{}/authz/perms/user/{}'
29
30 EXPIRE_TIME = 'expire_time'
31
32 perm_cache = {}
33 deploy_config = osdf_config.deployment
34
35
36 def clear_cache():
37     perm_cache.clear()
38
39
40 def authenticate(uid, passwd):
41     try:
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))
46     return False
47
48
49 """
50 Check whether the user has valid permissions
51 return True if the user has valid permissions
52 else return false
53 """
54
55
56 def has_valid_role(perms):
57     aaf_user_roles = deploy_config['aaf_user_roles']
58
59     aaf_roles = get_role_list(perms)
60
61     for roles in aaf_user_roles:
62         path_perm = roles.split(':')
63         uri = path_perm[0]
64         perm = path_perm[1].split('|')
65         p = (perm[0], perm[1], perm[2].split()[0])
66         if re.search(uri, request.path) and p in aaf_roles:
67             return True
68     return False
69
70
71 """
72 Build a list of roles tuples from the AAF response.
73
74 """
75
76
77 def get_role_list(perms):
78     role_list = []
79     if perms:
80         roles = perms.get('roles')
81         if roles:
82             perm = roles.get('perm', [])
83             for p in perm:
84                 role_list.append((p['type'], p['instance'], p['action']))
85     return role_list
86
87
88 def get_aaf_permissions(uid, passwd):
89     key = base64.b64encode(bytes("{}_{}".format(uid, passwd), "ascii"))
90     time_delta = timedelta(minutes=deploy_config.get('aaf_cache_expiry_mins', 5))
91
92     perms = perm_cache.get(key)
93
94     if perms and datetime.now() < perms.get(EXPIRE_TIME):
95         debug_log.debug("Returning cached value")
96         return perms
97     debug_log.debug("Invoking AAF authentication API")
98     perms = {EXPIRE_TIME: datetime.now() + time_delta, 'roles': remote_api(passwd, uid)}
99     perm_cache[key] = perms
100     return perms
101
102
103 def remote_api(passwd, uid):
104     headers = {"Accept": "application/Users+xml;q=1.0;charset=utf-8;version=2.0,text/xml;q=1.0;version=2.0",
105                "Accept": "application/Users+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"}
106     url = AUTHZ_PERMS_USER.format(deploy_config['aaf_url'], uid)
107     rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug,
108                     req_id='aaf_user_id')
109     return rc.request(method='GET', asjson=True)