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