-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathSession.py
239 lines (177 loc) · 6.82 KB
/
Session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
"""Implementation of client sessions."""
import re
from time import time, localtime
from urllib import parse
from MiscUtils import NoDefault
from MiscUtils.Funcs import uniqueId
class SessionError(Exception):
"""Client session error"""
class Session:
"""Implementation of client sessions.
All methods that deal with time stamps, such as creationTime(),
treat time as the number of seconds since January 1, 1970.
Session identifiers are stored in cookies. Therefore, clients
must have cookies enabled.
Note that the session id should be a string that is valid
as part of a filename. This is currently true, and should
be maintained if the session id generation technique is
modified. Session ids can be used in filenames.
"""
# region Init
def __init__(self, trans, identifier=None):
self._lastAccessTime = self._creationTime = time()
self._isExpired = self._dirty = False
self._numTrans = 0
self._values = {}
app = trans.application()
self._timeout = app.sessionTimeout(trans)
self._prefix = app.sessionPrefix(trans)
self._sessionName = app.sessionName(trans)
if identifier:
if re.search(r'[^\w\.\-]', identifier) is not None:
raise SessionError("Illegal characters in session identifier")
if len(identifier) > 80:
raise SessionError("Session identifier too long")
self._identifier = identifier
else:
attempts = 0
while attempts < 10000:
self._identifier = self._prefix + (
'{:02d}{:02d}{:02d}{:02d}{:02d}{:02d}').format(
*localtime()[:6]) + '-' + uniqueId(self)
if not app.hasSession(self._identifier):
break
attempts += 1
else:
raise SessionError(
"Can't create valid session id"
f" after {attempts} attempts.")
if app.setting('Debug')['Sessions']:
print('>> [session] Created session, timeout =', self._timeout,
'id =', self._identifier, 'self =', self)
# endregion Init
# region Access
def creationTime(self):
"""Return the time when this session was created."""
return self._creationTime
def lastAccessTime(self):
"""Get last access time.
Returns the last time the user accessed the session through
interaction. This attribute is updated in awake(), which is
invoked at the beginning of a transaction.
"""
return self._lastAccessTime
def identifier(self):
"""Return a string that uniquely identifies the session.
This method will create the identifier if needed.
"""
return self._identifier
def isDirty(self):
"""Check whether the session is dirty (has unsaved changes)."""
return self._dirty
def setDirty(self, dirty=True):
"""Set the dirty status of the session."""
self._dirty = dirty
def isExpired(self):
"""Check whether the session has been previously expired.
See also: expiring()
"""
return getattr(self, '_isExpired', False) or self._timeout == 0
def isNew(self):
"""Check whether the session is new."""
return self._numTrans < 2
def timeout(self):
"""Return the timeout for this session in seconds."""
return self._timeout
def setTimeout(self, timeout):
"""Set the timeout on this session in seconds."""
self._timeout = timeout
# endregion Access
# region Invalidate
def invalidate(self):
"""Invalidate the session.
It will be discarded the next time it is accessed.
"""
self._lastAccessTime = 0
self._values = {}
self._dirty = False
self._timeout = 0
# endregion Invalidate
# region Values
def value(self, name, default=NoDefault):
if default is NoDefault:
return self._values[name]
return self._values.get(name, default)
def hasValue(self, name):
return name in self._values
def setValue(self, name, value):
self._values[name] = value
self._dirty = True
def delValue(self, name):
del self._values[name]
self._dirty = True
def values(self):
return self._values
def __getitem__(self, name):
return self.value(name)
def __setitem__(self, name, value):
self.setValue(name, value)
def __delitem__(self, name):
self.delValue(name)
def __contains__(self, name):
return self.hasValue(name)
# endregion Values
# region Transactions
def awake(self, _trans):
"""Let the session awake.
Invoked during the beginning of a transaction, giving a Session an
opportunity to perform any required setup. The default implementation
updates the 'lastAccessTime'.
"""
self._lastAccessTime = time()
self._numTrans += 1
def respond(self, trans):
"""Let the session respond to a request.
The default implementation does nothing, but could do something
in the future. Subclasses should invoke super.
"""
# base method does nothing
def sleep(self, trans):
"""Let the session sleep again.
Invoked during the ending of a transaction, giving a Session an
opportunity to perform any required shutdown. The default
implementation does nothing, but could do something in the future.
Subclasses should invoke super.
"""
# base method does nothing
def expiring(self):
"""Let the session expire.
Called when session is expired by the application.
Subclasses should invoke super.
Session store __delitem__()s should invoke if not isExpired().
"""
self._isExpired = True
def numTransactions(self):
"""Get number of transactions.
Returns the number of transactions in which the session has been used.
"""
return self._numTrans
# endregion Transactions
# region Utility
def sessionEncode(self, url):
"""Encode the session ID as a parameter to a url."""
url = list(parse.urlparse(url)) # make a list
if url[4]:
url[4] += '&'
url[4] += f'{self._sessionName}={self.identifier()}'
url = parse.urlunparse(url)
return url
# endregion Utility
# region Exception reports
_exceptionReportAttrNames = [
'isDirty', 'isExpired', 'lastAccessTime',
'numTransactions', 'timeout', 'values']
def writeExceptionReport(self, handler):
handler.writeTitle(self.__class__.__name__)
handler.writeAttrs(self, self._exceptionReportAttrNames)
# endregion Exception reports