f7f18a624d5a9b3c91030af2322b227d68186c4f
[plcapi.git] / PLC / Methods / AddPersonKey.py
1 # $Id$
2 from PLC.Faults import *
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Keys import Key, Keys
6 from PLC.Persons import Person, Persons
7 from PLC.Auth import Auth
8
9 can_update = lambda (field, value): field in ['key_type','key']
10
11 class AddPersonKey(Method):
12     """
13     Adds a new key to the specified account.
14
15     Non-admins can only modify their own keys.
16
17     Returns the new key_id (> 0) if successful, faults otherwise.
18     """
19
20     roles = ['admin', 'pi', 'tech', 'user']
21
22     key_fields = dict(filter(can_update, Key.fields.items()))
23
24     accepts = [
25         Auth(),
26         Mixed(Person.fields['person_id'],
27               Person.fields['email']),
28         key_fields
29         ]
30
31     returns = Parameter(int, 'New key_id (> 0) if successful')
32
33     def call(self, auth, person_id_or_email, key_fields):
34         key_fields = dict(filter(can_update, key_fields.items()))
35
36         # Get account details
37         persons = Persons(self.api, [person_id_or_email])
38         if not persons:
39             raise PLCInvalidArgument, "No such account"
40         person = persons[0]
41
42         if person['peer_id'] is not None:
43             raise PLCInvalidArgument, "Not a local account"
44
45         # If we are not admin, make sure caller is adding a key to their account
46         if 'admin' not in self.caller['roles']:
47             if person['person_id'] != self.caller['person_id']:
48                 raise PLCPermissionDenied, "You may only modify your own keys"
49
50         key = Key(self.api, key_fields)
51         key.sync(commit = False)
52         person.add_key(key, commit = True)
53
54         # Logging variables
55         self.event_objects = {'Person': [person['person_id']],
56                               'Key': [key['key_id']]}
57         self.message = 'Key %d added to person %d' % \
58                 (key['key_id'], person['person_id'])
59
60         return key['key_id']