5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
7 from PLC.Table import Row, Table
8 from PLC.Persons import Person, Persons
9 from PLC.Nodes import Node, Nodes
13 Representation of a row in the sessions table. To use, instantiate
14 with a dict of values.
17 table_name = 'sessions'
18 primary_key = 'session_id'
19 join_tables = ['person_session', 'node_session']
21 'session_id': Parameter(str, "Session key"),
22 'person_id': Parameter(int, "Account identifier, if applicable"),
23 'node_id': Parameter(int, "Node identifier, if applicable"),
24 'expires': Parameter(int, "Date and time when session expires, in seconds since UNIX epoch"),
27 def validate_expires(self, expires):
28 if expires < time.time():
29 raise PLCInvalidArgument, "Expiration date must be in the future"
31 return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
33 add_person = Row.add_object(Person, 'person_session')
35 def add_node(self, node, commit = True):
36 # Nodes can have only one session at a time
37 self.api.db.do("DELETE FROM node_session WHERE node_id = %d" % \
40 add = Row.add_object(Node, 'person_session')
41 add(self, node, commit)
43 def sync(self, commit = True, insert = None):
44 if not self.has_key('session_id'):
45 # Before a new session is added, delete expired sessions
46 expired = Sessions(self.api, expires = -int(time.time()))
47 for session in expired:
48 session.delete(commit)
50 # Generate 32 random bytes
51 bytes = random.sample(xrange(0, 256), 32)
52 # Base64 encode their string representation
53 self['session_id'] = base64.b64encode("".join(map(chr, bytes)))
57 Row.sync(self, commit, insert)
59 class Sessions(Table):
61 Representation of row(s) from the session table in the database.
64 def __init__(self, api, session_ids = None, expires = int(time.time())):
65 Table.__init__(self, api, Session)
67 sql = "SELECT %s FROM view_sessions WHERE True" % \
68 ", ".join(Session.fields)
71 sql += " AND session_id IN (%s)" % ", ".join(map(api.db.quote, session_ids))
73 if expires is not None:
75 sql += " AND expires > %(expires)d"
78 sql += " AND expires < %(expires)d"
80 self.selectall(sql, locals())