- removed 'Adm' prefix
[plcapi.git] / PLC / Methods / GetPersons.py
1 import os
2
3 from PLC.Faults import *
4 from PLC.Method import Method
5 from PLC.Parameter import Parameter, Mixed
6 from PLC.Persons import Person, Persons
7 from PLC.Auth import PasswordAuth
8
9 class GetPersons(Method):
10     """
11     Return an array of dictionaries containing details about the
12     specified accounts.
13
14     ins may retrieve details about all accounts by not specifying
15     person_id_or_email_list or by specifying an empty list. Users and
16     techs may only retrieve details about themselves. PIs may retrieve
17     details about themselves and others at their sites.
18
19     If return_fields is specified, only the specified fields will be
20     returned, if set. Otherwise, the default set of fields returned is:
21
22     """
23
24     roles = ['admin', 'pi', 'user', 'tech']
25
26     accepts = [
27         PasswordAuth(),
28         [Mixed(Person.fields['person_id'],
29                Person.fields['email'])],
30         Parameter([str], 'List of fields to return')
31         ]
32
33     # Filter out password field
34     can_return = lambda (field, value): field not in ['password']
35     return_fields = dict(filter(can_return, Person.fields.items()))
36     returns = [return_fields]
37
38     def __init__(self, *args, **kwds):
39         Method.__init__(self, *args, **kwds)
40         # Update documentation with list of default fields returned
41         self.__doc__ += os.linesep.join(self.return_fields.keys())
42
43     def call(self, auth, person_id_or_email_list = None, return_fields = None):
44         # Make sure that only valid fields are specified
45         if return_fields is None:
46             return_fields = self.return_fields
47         elif filter(lambda field: field not in self.return_fields, return_fields):
48             raise PLCInvalidArgument, "Invalid return field specified"
49
50         # Authenticated function
51         assert self.caller is not None
52
53         # Only admins can not specify person_id_or_email_list or
54         # specify an empty list.
55         if not person_id_or_email_list and 'admin' not in self.caller['roles']:
56             raise PLCInvalidArgument, "List of accounts to retrieve not specified"
57
58         # Get account information
59         persons = Persons(self.api, person_id_or_email_list)
60
61         # Filter out accounts that are not viewable and turn into list
62         persons = filter(self.caller.can_view, persons.values())
63
64         # Filter out undesired or None fields (XML-RPC cannot marshal
65         # None) and turn each person into a real dict.
66         valid_return_fields_only = lambda (key, value): \
67                                    key in return_fields and value is not None
68         persons = [dict(filter(valid_return_fields_only, person.items())) \
69                    for person in persons]
70                     
71         return persons