- added class variables: event_type, object_type, object_ids (used by event logger)
[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 PasswordAuth
7
8 class AddPersonKey(Method):
9     """
10     Adds a new key to the specified account.
11
12     Non-admins can only modify their own keys.
13
14     Returns the new key_id (> 0) if successful, faults otherwise.
15     """
16
17     roles = ['admin', 'pi', 'tech', 'user']
18
19     accepts = [
20         PasswordAuth(),
21         Mixed(Person.fields['person_id'],
22               Person.fields['email']),
23         Key.fields['key_type'],
24         Key.fields['key']
25         ]
26
27     returns = Parameter(int, 'New key_id (> 0) if successful')
28
29     event_type = 'Add'
30     object_type = 'Key'
31     object_ids = []
32
33     def call(self, auth, person_id_or_email, key_type, key_value):
34         # Get account details
35         persons = Persons(self.api, [person_id_or_email]).values()
36         if not persons:
37             raise PLCInvalidArgument, "No such account"
38         person = persons[0]
39
40         # If we are not admin, make sure caller is adding a key to their account
41         if 'admin' not in self.caller['roles']:
42             if person['person_id'] != self.caller['person_id']:
43                 raise PLCPermissionDenied, "You may only modify your own keys"
44
45         key = Key(self.api)
46         key['person_id'] = person['person_id']
47         key['key_type'] = key_type
48         key['key'] = key_value
49         key.sync(commit = False)
50         person.add_key(key, commit = True)
51         self.object_ids = [key['key_id']]
52
53         return key['key_id']