1ab08c27f0f0e69e7a8f9652457f13c0d3d5853f
[plcapi.git] / PLC / Methods / GetPersons.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Persons import Person, Persons
5 from PLC.Auth import PasswordAuth
6
7 class GetPersons(Method):
8     """
9     Return an array of structs containing details about accounts. If
10     person_id_or_email_list is specified, only the specified accounts
11     will be queried.
12
13     Users and techs may only retrieve details about themselves. PIs
14     may retrieve details about themselves and others at their
15     sites. Admins may retrieve details about all accounts.
16     """
17
18     roles = ['admin', 'pi', 'user', 'tech']
19
20     accepts = [
21         PasswordAuth(),
22         [Mixed(Person.fields['person_id'],
23                Person.fields['email'])],
24         Parameter([str], 'List of fields to return')
25         ]
26
27     # Filter out password field
28     can_return = lambda (field, value): field not in ['password']
29     return_fields = dict(filter(can_return, Person.fields.items()))
30     returns = [return_fields]
31
32     def call(self, auth, person_id_or_email_list = None):
33         # If we are not admin, make sure to only return viewable accounts
34         if 'admin' not in self.caller['roles']:
35             # Get accounts that we are able to view
36             valid_person_ids = [self.caller['person_id']]
37             if 'pi' in self.caller['roles'] and self.caller['site_ids']:
38                 sites = Sites(self.api, self.caller['site_ids']).values()
39                 for site in sites:
40                     valid_person_ids += site['person_ids']
41
42             if not valid_person_ids:
43                 return []
44
45             if not person_id_or_email_list:
46                 person_id_or_email_list = valid_person_ids
47
48         persons = Persons(self.api, person_id_or_email_list).values()
49
50         # Filter out accounts that are not viewable
51         if 'admin' not in self.caller['roles']:
52             persons = filter(self.caller.can_view, persons)
53
54         return persons