- fix add_object() usage
[plcapi.git] / PLC / Sessions.py
1 import random
2 import base64
3 import time
4
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
10
11 class Session(Row):
12     """
13     Representation of a row in the sessions table. To use, instantiate
14     with a dict of values.
15     """
16
17     table_name = 'sessions'
18     primary_key = 'session_id'
19     join_tables = ['person_session', 'node_session']
20     fields = {
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"),
25         }
26
27     def validate_expires(self, expires):
28         if expires < time.time():
29             raise PLCInvalidArgument, "Expiration date must be in the future"
30
31         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
32
33     add_person = Row.add_object(Person, 'person_session')
34
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" % \
38                        node['node_id'])
39
40         add = Row.add_object(Node, 'node_session')
41         add(self, node, commit = commit)
42
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)
49
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)))
54             # Force insert
55             insert = True
56
57         Row.sync(self, commit, insert)
58
59 class Sessions(Table):
60     """
61     Representation of row(s) from the session table in the database.
62     """
63
64     def __init__(self, api, session_ids = None, expires = int(time.time())):
65         Table.__init__(self, api, Session)
66
67         sql = "SELECT %s FROM view_sessions WHERE True" % \
68               ", ".join(Session.fields)
69
70         if session_ids:
71             sql += " AND session_id IN (%s)" % ", ".join(map(api.db.quote, session_ids))
72
73         if expires is not None:
74             if expires >= 0:
75                 sql += " AND expires > %(expires)d"
76             else:
77                 expires = -expires
78                 sql += " AND expires < %(expires)d"
79
80         self.selectall(sql, locals())