rename to AddPersonKey
[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     def call(self, auth, person_id_or_email, key_type, key_value):
30         # Get account details
31         persons = Persons(self.api, [person_id_or_email]).values()
32         if not persons:
33             raise PLCInvalidArgument, "No such account"
34         person = persons[0]
35
36         # If we are not admin, make sure caller is adding a key to their account
37         if 'admin' not in self.caller['roles']:
38             if person['person_id'] != self.caller['person_id']:
39                 raise PLCPermissionDenied, "You may only modify your own keys"
40
41         key = Key(self.api)
42         key['person_id'] = person['person_id']
43         key['key_type'] = key_type
44         key['key'] = key_value
45         key.sync(commit = False)
46
47         person.add_key(key, commit = True)
48         
49         return key['key_id']