a1754ff752d754e4efcec229327da05c1d0b3b37
[plcapi.git] / PLC / Methods / UpdateKey.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Keys import Key, Keys
5 from PLC.Auth import Auth
6
7 can_update = lambda (field, value): field in \
8              ['key_type', 'key']
9
10 class UpdateKey(Method):
11     """
12     Updates the parameters of an existing key with the values in
13     key_fields.
14
15     Non-admins may only update their own keys.
16
17     Returns 1 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         Key.fields['key_id'],
27         key_fields
28         ]
29
30     returns = Parameter(int, '1 if successful')
31
32     def call(self, auth, key_id, key_fields):
33         key_fields = dict(filter(can_update, key_fields.items()))
34
35         # Get key information
36         keys = Keys(self.api, [key_id])
37         if not keys:
38             raise PLCInvalidArgument, "No such key"
39         key = keys[0]
40
41         if key['peer_id'] is not None:
42             raise PLCInvalidArgument, "Not a local key"
43
44         if 'admin' not in self.caller['roles']:
45             if key['key_id'] not in self.caller['key_ids']:
46                 raise PLCPermissionDenied, "Key must be associated with one of your accounts"
47
48         key.update(key_fields)
49         key.sync()
50         
51         # Logging variables
52         self.object_ids = [key['key_id']]
53         self.message = 'key %d updated: %s' % \
54                 (key['key_id'], ", ".join(key_fields.keys()))
55         return 1