1# Interface to external user info resources
2
3import copy
4
5
6class UserInfo(object):
7    """ Read only interface to a user info store """
8
9    def __init__(self):
10        pass
11
12    def __call__(self, **kwargs):
13        pass
14
15
16class UserInfoDB(UserInfo):
17    """ Read only interface to a user info store """
18
19    def __init__(self, db=None):
20        self.db = db
21
22    @staticmethod
23    def filter(userinfo, user_info_claims=None):
24        """
25        Return only those claims that are asked for.
26        It's a best effort task; if essential claims are not present
27        no error is flagged.
28
29        :param userinfo: A dictionary containing the available user info.
30        :param user_info_claims: A dictionary specifying the asked for claims
31        :return: A dictionary of filtered claims.
32        """
33
34        if user_info_claims is None:
35            return copy.copy(userinfo)
36        else:
37            result = {}
38            missing = []
39            optional = []
40            for key, restr in user_info_claims.items():
41                try:
42                    result[key] = userinfo[key]
43                except KeyError:
44                    if restr == {"essential": True}:
45                        missing.append(key)
46                    else:
47                        optional.append(key)
48            return result
49
50    def __call__(self, userid, user_info_claims=None, **kwargs):
51        try:
52            return self.filter(self.db[userid], user_info_claims)
53        except KeyError:
54            return {}
55
56