Initial checkin of new API implementation
[plcapi.git] / PLC / Methods / AdmUpdatePerson.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 AdmUpdatePerson(Method):
8     """
9     Updates a person. Only the fields specified in update_fields are
10     updated, all other fields are left untouched.
11
12     To remove a value without setting a new one in its place (for
13     example, to remove an address from the person), specify -1 for int
14     and double fields and 'null' for string fields. first_name and
15     last_name cannot be unset.
16     
17     Users and techs can only update themselves. PIs can only update
18     themselves and other non-PIs at their sites.
19
20     Returns 1 if successful, faults otherwise.
21     """
22
23     roles = ['admin', 'pi', 'user', 'tech']
24
25     can_update = lambda (field, value): field in \
26                  ['first_name', 'last_name', 'title', 'email',
27                   'password', 'phone', 'url', 'bio', 'accepted_aup']
28     update_fields = dict(filter(can_update, Person.fields.items()))
29
30     accepts = [
31         PasswordAuth(),
32         Mixed(Person.fields['person_id'],
33               Person.fields['email']),
34         update_fields
35         ]
36
37     returns = Parameter(int, '1 if successful')
38
39     def call(self, auth, person_id_or_email, update_fields):
40         if filter(lambda field: field not in self.update_fields, update_fields):
41             raise PLCInvalidArgument, "Invalid field specified"
42
43         # XML-RPC cannot marshal None, so we need special values to
44         # represent "unset".
45         for key, value in update_fields.iteritems():
46             if value == -1 or value == "null":
47                 if key in ['first_name', 'last_name']:
48                     raise PLCInvalidArgument, "first_name and last_name cannot be unset"
49                 update_fields[key] = None
50
51         # Get account information
52         persons = Persons(self.api, [person_id_or_email])
53         if not persons:
54             raise PLCInvalidArgument, "No such account"
55
56         person = persons.values()[0]
57
58         # Authenticated function
59         assert self.caller is not None
60
61         # Check if we can update this account
62         if not self.caller.can_update(person):
63             raise PLCPermissionDenied, "Not allowed to update specified account"
64
65         person.update(update_fields)
66         person.flush()
67
68         return 1