- - removed anything having to do with event_type/event_object
[plcapi.git] / PLC / Methods / AddPersonKey.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.Persons import Person, Persons
6 from PLC.Auth import Auth
7
8 can_update = lambda (field, value): field not in ['key_id']
9
10 class AddPersonKey(Method):
11     """
12     Adds a new key to the specified account.
13
14     Non-admins can only modify their own keys.
15
16     Returns the new key_id (> 0) if successful, faults otherwise.
17     """
18
19     roles = ['admin', 'pi', 'tech', 'user']
20
21     key_fields = dict(filter(can_update, Key.fields.items()))
22
23     accepts = [
24         Auth(),
25         Mixed(Person.fields['person_id'],
26               Person.fields['email']),
27         key_fields
28         ]
29
30     returns = Parameter(int, 'New key_id (> 0) if successful')
31
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 we are not admin, make sure caller is adding a key to their account
43         if 'admin' not in self.caller['roles']:
44             if person['person_id'] != self.caller['person_id']:
45                 raise PLCPermissionDenied, "You may only modify your own keys"
46
47         key = Key(self.api, key_fields)
48         key.sync(commit = False)
49         person.add_key(key, commit = True)
50
51         self.object_ids = [person['person_id'], key['key_id']]
52
53         return key['key_id']