|
@@ -0,0 +1,57 @@
|
|
1
|
+from flask.sessions import SessionInterface
|
|
2
|
+import binascii
|
|
3
|
+import os
|
|
4
|
+from lodel.session.lodel_ram_session.lodel_ram_session import LodelRamSession
|
|
5
|
+import copy
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+class LodelRamSessionInterface(SessionInterface):
|
|
9
|
+ __sessions = dict()
|
|
10
|
+
|
|
11
|
+ def open_session(self, app, request):
|
|
12
|
+ self.session_tokensize = int(app.config['lodel.sessions']['tokensize'])
|
|
13
|
+ sid = request.cookies.get(app.session_cookie_name) or self.generate_token()
|
|
14
|
+ session = LodelRamSession(sid)
|
|
15
|
+ if self.__class__.__sessions.get(sid, None) is None:
|
|
16
|
+ self.__class__.__sessions[sid] = session
|
|
17
|
+ return session
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+ def save_session(self, app, session, response):
|
|
21
|
+ domain = self.get_cookie_domain(app)
|
|
22
|
+
|
|
23
|
+ if not session:
|
|
24
|
+ del(self.__class__.__sessions[session.sid])
|
|
25
|
+ response.delete_cookie(app.session_cookie_name, domain=domain)
|
|
26
|
+ return
|
|
27
|
+
|
|
28
|
+ cookie_exp = self.get_expiration_time(app, session)
|
|
29
|
+ response.set_cookie(app.session_cookie_name, session.sid, expires=cookie_exp, httponly=False, domain=domain)
|
|
30
|
+
|
|
31
|
+ ## @brief generates a new session token
|
|
32
|
+ #
|
|
33
|
+ # @return str
|
|
34
|
+ #
|
|
35
|
+ # @remarks There is no valid reason for checking the generated token uniqueness:
|
|
36
|
+ # - checking for uniqueness is slow ;
|
|
37
|
+ # - keeping a dict with a few thousand keys of hundred bytes also is
|
|
38
|
+ # memory expensive ;
|
|
39
|
+ # - should the system get distributed while sharing session storage, there
|
|
40
|
+ # would be no reasonable way to efficiently check for uniqueness ;
|
|
41
|
+ # - sessions do have a really short life span, drastically reducing
|
|
42
|
+ # even more an already close to inexistent risk of collision. A 64 bits
|
|
43
|
+ # id would perfectly do the job, or to be really cautious, a 128 bits
|
|
44
|
+ # one (actual size of UUIDs) ;
|
|
45
|
+ # - if we are still willing to ensure uniqueness, then simply salt it
|
|
46
|
+ # with a counter, or a timestamp, and hash the whole thing with a
|
|
47
|
+ # cryptographically secured method such as sha-2 if we are paranoids
|
|
48
|
+ # and trying to avoid what will never happen, ever ;
|
|
49
|
+ # - sure, two hexadecimal characters is one byte long. Simply go for
|
|
50
|
+ # bit length, not chars length.
|
|
51
|
+ def generate_token(self):
|
|
52
|
+ token = binascii.hexlify(os.urandom(self.session_tokensize))
|
|
53
|
+ if self.__class__.__sessions.get(token, None) is not None:
|
|
54
|
+ token = self.generate_token()
|
|
55
|
+ return token.decode('utf-8')
|
|
56
|
+
|
|
57
|
+
|