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