82dccbfd4510d44e034c71a071dbe0e88f188ddd
[plcapi.git] / PLC / Methods / GetSession.py
1 import time
2
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Auth import Auth
6 from PLC.Sessions import Session, Sessions
7 from PLC.Nodes import Node, Nodes
8 from PLC.Persons import Person, Persons
9
10 class GetSession(Method):
11     """
12     Returns a new session key if a user or node authenticated
13     successfully, faults otherwise.
14
15     Default value for 'expires' is 24 hours.  Otherwise, the returned 
16     session 'expires' in the given number of seconds.
17     """
18
19     roles = ['admin', 'pi', 'user', 'tech', 'node']
20     accepts = [Auth(),
21                Parameter(int,"expires", nullok=True)]
22     returns = Session.fields['session_id']
23
24
25     def call(self, auth, expires=None):
26         # Authenticated with a session key, just return it
27         if auth.has_key('session'):
28             return auth['session']
29
30         session = Session(self.api)
31
32         if isinstance(self.caller, Person):
33             # XXX Make this configurable
34             if expires is None:
35                 session['expires'] = int(time.time()) + (24 * 60 * 60)
36             else:
37                 session['expires'] = int(time.time()) + int(expires)
38
39         session.sync(commit = False)
40
41         if isinstance(self.caller, Node):
42             session.add_node(self.caller, commit = True)
43         elif isinstance(self.caller, Person):
44             session.add_person(self.caller, commit = True)
45
46         return session['session_id']