1import logging
2
3from hashlib import sha1
4
5from saml2.ident import code_binary
6
7
8logger = logging.getLogger(__name__)
9
10
11def context_match(cfilter, cntx):
12    # TODO
13    return True
14
15# The key to the stored authn statement is placed encrypted in the cookie
16
17
18class SessionStorage(object):
19    """ In memory storage of session information """
20
21    def __init__(self):
22        self.db = {"assertion": {}, "authn": {}}
23        self.assertion = self.db["assertion"]
24        self.authn = self.db["authn"]
25
26    def store_assertion(self, assertion, to_sign):
27        self.assertion[assertion.id] = (assertion, to_sign)
28        key = sha1(code_binary(assertion.subject.name_id)).hexdigest()
29        try:
30            self.authn[key].append(assertion.authn_statement)
31        except KeyError:
32            self.authn[key] = [assertion.authn_statement]
33
34    def get_assertion(self, cid):
35        return self.assertion[cid]
36
37    def get_authn_statements(self, name_id, session_index=None,
38                             requested_context=None):
39        """
40
41        :param name_id:
42        :param session_index:
43        :param requested_context:
44        :return:
45        """
46        result = []
47        key = sha1(code_binary(name_id)).hexdigest()
48        try:
49            statements = self.authn[key]
50        except KeyError:
51            logger.info("Unknown subject %s", name_id)
52            return []
53
54        for statement in statements:
55            if session_index:
56                if statement.session_index != session_index:
57                    continue
58            if requested_context:
59                if not context_match(requested_context,
60                                     statement[0].authn_context):
61                    continue
62            result.append(statement)
63
64        return result
65
66    def remove_authn_statements(self, name_id):
67        logger.debug("remove authn about: %s", name_id)
68        nkey = sha1(code_binary(name_id)).hexdigest()
69
70        del self.authn[nkey]
71