add the key string to the person record before passing it to the sfa upcall
[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 from PLC.SFA import SFA
10
11 can_update = lambda (field, value): field in ['key_type','key']
12
13 class AddPersonKey(Method):
14     """
15     Adds a new key to the specified account.
16
17     Non-admins can only modify their own keys.
18
19     Returns the new key_id (> 0) if successful, faults otherwise.
20     """
21
22     roles = ['admin', 'pi', 'tech', 'user']
23
24     key_fields = dict(filter(can_update, Key.fields.items()))
25
26     accepts = [
27         Auth(),
28         Mixed(Person.fields['person_id'],
29               Person.fields['email']),
30         key_fields
31         ]
32
33     returns = Parameter(int, 'New key_id (> 0) if successful')
34
35     def call(self, auth, person_id_or_email, key_fields):
36         key_fields = dict(filter(can_update, key_fields.items()))
37
38         # Get account details
39         persons = Persons(self.api, [person_id_or_email])
40         if not persons:
41             raise PLCInvalidArgument, "No such account"
42         person = persons[0]
43
44         if person['peer_id'] is not None:
45             raise PLCInvalidArgument, "Not a local account"
46
47         # If we are not admin, make sure caller is adding a key to their account
48         if 'admin' not in self.caller['roles']:
49             if person['person_id'] != self.caller['person_id']:
50                 raise PLCPermissionDenied, "You may only modify your own keys"
51
52         key = Key(self.api, key_fields)
53         key.sync(commit = False)
54         person.add_key(key, commit = True)
55
56         # Logging variables
57         self.event_objects = {'Person': [person['person_id']],
58                               'Key': [key['key_id']]}
59         self.message = 'Key %d added to person %d' % \
60                         (key['key_id'], person['person_id'])
61
62         # sync with the geni db
63         person['key'] = key_fields['key']
64         sfa = SFA(self.api)
65         sfa.update_record(person, 'user') 
66         
67         return key['key_id']