Fix documentation
[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 structs containing details about accounts.
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     If return_fields is specified, only the specified fields will be
18     returned, if set. Otherwise, the default set of fields returned is:
19
20     """
21
22     roles = ['admin', 'pi', 'user', 'tech']
23
24     accepts = [
25         PasswordAuth(),
26         [Mixed(Person.fields['person_id'],
27                Person.fields['email'])],
28         Parameter([str], 'List of fields to return')
29         ]
30
31     # Filter out password field
32     can_return = lambda (field, value): field not in ['password']
33     return_fields = dict(filter(can_return, Person.fields.items()))
34     returns = [return_fields]
35
36     def __init__(self, *args, **kwds):
37         Method.__init__(self, *args, **kwds)
38         # Update documentation with list of default fields returned
39         self.__doc__ += os.linesep.join(self.return_fields.keys())
40
41     def call(self, auth, person_id_or_email_list = None, return_fields = None):
42         # Make sure that only valid fields are specified
43         if return_fields is None:
44             return_fields = self.return_fields
45         elif filter(lambda field: field not in self.return_fields, return_fields):
46             raise PLCInvalidArgument, "Invalid return field specified"
47
48         # Authenticated function
49         assert self.caller is not None
50
51         # Only admins can not specify person_id_or_email_list or
52         # specify an empty list.
53         if not person_id_or_email_list and 'admin' not in self.caller['roles']:
54             raise PLCInvalidArgument, "List of accounts to retrieve not specified"
55
56         # Get account information
57         persons = Persons(self.api, person_id_or_email_list)
58
59         # Filter out accounts that are not viewable and turn into list
60         persons = filter(self.caller.can_view, persons.values())
61
62         # Turn each person into a real dict.
63         persons = [dict(person) for person in persons]
64                     
65         return persons