- make Add() calling convention consistent among all functions that
[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 PasswordAuth
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     for field in key_fields.values():
24         field.optional = True
25
26     accepts = [
27         PasswordAuth(),
28         Key.fields['key_id'],
29         key_fields
30         ]
31
32     returns = Parameter(int, '1 if successful')
33
34     def call(self, auth, key_id, key_fields):
35         key_fields = dict(filter(can_update, key_fields.items()))
36
37         # Get key information
38         keys = Keys(self.api, [key_id]).values()
39         if not keys:
40             raise PLCInvalidArgument, "No such key"
41         key = keys[0]
42
43         if 'admin' not in self.caller['roles']:
44             if key['key_id'] not in self.caller['key_ids']:
45                 raise PLCPermissionDenied, "Key must be associated with one of your accounts"
46
47         key.update(key_fields)
48         key.sync()
49
50         return 1