allow filters to be specified in most Get() calls
[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.Filter import Filter
5 from PLC.Persons import Person, Persons
6 from PLC.Auth import Auth
7
8 class GetPersons(Method):
9     """
10     Returns an array of structs containing details about users. If
11     person_filter is specified and is an array of user identifiers or
12     usernames, or a struct of user attributes, only users matching the
13     filter will be returned.
14
15     Users and techs may only retrieve details about themselves. PIs
16     may retrieve details about themselves and others at their
17     sites. Admins may retrieve details about all accounts.
18     """
19
20     roles = ['admin', 'pi', 'user', 'tech']
21
22     accepts = [
23         Auth(),
24         Mixed([Mixed(Person.fields['person_id'],
25                      Person.fields['email'])],
26               Filter(Person.fields))
27         ]
28
29     # Filter out password field
30     can_return = lambda (field, value): field not in ['password']
31     return_fields = dict(filter(can_return, Person.fields.items()))
32     returns = [return_fields]
33
34     def call(self, auth, person_filter = None):
35         # If we are not admin, make sure to only return viewable accounts
36         if 'admin' not in self.caller['roles']:
37             # Get accounts that we are able to view
38             valid_person_ids = [self.caller['person_id']]
39             if 'pi' in self.caller['roles'] and self.caller['site_ids']:
40                 sites = Sites(self.api, self.caller['site_ids']).values()
41                 for site in sites:
42                     valid_person_ids += site['person_ids']
43
44             if not valid_person_ids:
45                 return []
46
47             if person_filter is None:
48                 person_filter = valid_person_ids
49
50         persons = Persons(self.api, person_filter).values()
51
52         # Filter out accounts that are not viewable
53         if 'admin' not in self.caller['roles']:
54             persons = filter(self.caller.can_view, persons)
55
56         return persons