Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[plcapi.git] / trunk / PLC / Methods / UpdatePerson.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 Auth
6
7 related_fields = Person.related_fields.keys()
8 can_update = lambda (field, value): field in \
9              ['first_name', 'last_name', 'title', 'email',
10               'password', 'phone', 'url', 'bio', 'accepted_aup',
11               'enabled'] + related_fields
12
13 class UpdatePerson(Method):
14     """
15     Updates a person. Only the fields specified in person_fields are
16     updated, all other fields are left untouched.
17     
18     Users and techs can only update themselves. PIs can only update
19     themselves and other non-PIs at their sites.
20
21     Returns 1 if successful, faults otherwise.
22     """
23
24     roles = ['admin', 'pi', 'user', 'tech']
25
26     person_fields = dict(filter(can_update, Person.fields.items() + Person.related_fields.items()))
27
28     accepts = [
29         Auth(),
30         Mixed(Person.fields['person_id'],
31               Person.fields['email']),
32         person_fields
33         ]
34
35     returns = Parameter(int, '1 if successful')
36
37     def call(self, auth, person_id_or_email, person_fields):
38         person_fields = dict(filter(can_update, person_fields.items()))
39
40         # Get account information
41         persons = Persons(self.api, [person_id_or_email])
42         if not persons:
43             raise PLCInvalidArgument, "No such account"
44         person = persons[0]
45
46         if person['peer_id'] is not None:
47             raise PLCInvalidArgument, "Not a local account"
48
49         # Authenticated function
50         assert self.caller is not None
51
52         # Check if we can update this account
53         if not self.caller.can_update(person):
54             raise PLCPermissionDenied, "Not allowed to update specified account"
55         
56         # Make requested associations
57         for field in related_fields:
58             if field in person_fields:
59                 person.associate(auth, field, person_fields[field])
60                 person_fields.pop(field)
61
62         person.update(person_fields)
63         person.update_last_updated(False)
64         person.sync()
65         
66         # Logging variables
67         self.event_objects = {'Person': [person['person_id']]}
68
69         # Redact password
70         if 'password' in person_fields:
71             person_fields['password'] = "Removed by API"
72         self.message = 'Person %d updated: %s.' % \
73                        (person['person_id'], person_fields.keys())
74         if 'enabled' in person_fields:
75             self.message += ' Person enabled'   
76
77         return 1