final names RetrieveSliceSliverKeys and RetrieveSlicePersonKeys
[plcapi.git] / PLC / Methods / RetrieveSlicePersonKeys.py
1 from types import StringTypes
2
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Filter import Filter
6 from PLC.Auth import Auth
7 from PLC.Slices import Slice, Slices 
8 from PLC.Persons import Person, Persons
9 from PLC.Keys import Key, Keys
10
11 class RetrieveSlicePersonKeys(Method):
12     """
13     This method exposes the public ssh keys for people in a slice
14     It expects a slice name or id, and returns a dictionary on emails.
15     This method is designed to help third-party software authenticate
16     users (e.g. the OMF Experiment Controller). 
17     For this reason it is accessible with anonymous authentication.
18     """
19
20     roles = ['admin', 'pi', 'user', 'tech', 'anonymous' ]
21
22     applicable_fields = {
23         'slice_id' : Slice.fields['slice_id'],
24         'name' : Slice.fields['name'],
25         }
26
27     accepts = [
28         Auth(),
29         Mixed(Slice.fields['slice_id'],
30               Slice.fields['name']),
31         Filter(Person.fields),
32         ]
33
34     returns = Parameter (dict, " ssh keys hashed on emails")
35
36     def call(self, auth, slice_id_or_name, person_filter=None):
37
38         if person_filter is None: person_filter = {}
39
40         # the people in the slice
41         slice=Slices (self.api, slice_id_or_name, ['person_ids'])[0]
42         slice_person_ids = slice['person_ids']
43         
44         # if caller has not specified person_id, use slice_person_ids
45         if 'person_id' not in person_filter:
46             person_filter['person_id']=slice_person_ids
47         # otherwise, compute intersection
48         else:
49             caller_provided = person_filter['person_id']
50             if not isinstance (caller_provided,list):
51                 caller_provided = [ caller_provided, ]
52             person_filter['person_id'] = list ( set(caller_provided).intersection(slice_person_ids) )
53         
54         def merge (l1,l2): return l1+l2
55
56         persons = Persons (self.api, person_filter, ['email','key_ids'] )
57         key_id_to_email_hash = \
58             dict ( reduce ( merge , [ [ (kid,p['email']) for kid in p['key_ids']] for p in persons ] ) ) 
59         
60         all_key_ids = reduce (merge, [ p['key_ids'] for p in persons ] )
61
62         all_keys = Keys (self.api, all_key_ids)
63         
64         result={}
65         for key in all_keys:
66             key_id=key['key_id']
67             email = key_id_to_email_hash[key_id]
68             if email not in result: result[email]=[]
69             result[email].append (key['key'])
70
71         return  result