cleaned up imports in portal/views.py
[unfold.git] / portal / actions.py
1 from django.http                 import HttpResponse
2 from manifold.core.query         import Query
3 from manifold.manifoldapi        import execute_query
4 from portal.models               import PendingUser, PendingSlice
5 import json
6
7 # Get the list of authorities
8
9 def authority_get_pis(authority_hrn):
10     query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
11     results = execute_query(query)
12     if not results:
13         raise Exception, "Authority not found: %s" % authority_hrn
14     result, = results
15     return result['pi_users']
16
17 def authority_get_pi_emails(authority_hrn):
18     user_hrns = authority_get_pis(authority_hrn)
19     
20     query = Query.get('user').filter_by('user_hrn', 'included', user_hrns).select('user_email')
21     results = execute_query(query)
22     
23     return [result['user_email'] for result in results]
24
25 # SFA add record (user, slice)
26
27 def sfa_add_user(user_params):
28     # sfi.py add --xrn=fed4fire.upmc.timur_friedman --type=user --key=/root/.sfi/timur.pub --email=timur.friedman@lip6.fr --extra=first_name=Timur --extra=last_name=Friedman --extra=enabled=true
29     # user_params: xrn type key email + first_name last_name enabled
30     query = Query.create('user').set(user_params).select('user_hrn')
31     results = execute_query(query)
32     if not results:
33         raise Exception, "Failed creating SFA user: %s" % user_params['user_hrn']
34     result, = results
35     return result['user_hrn']
36
37 def sfa_add_slice(slice_params):
38     pass
39
40 # Propose hrn
41
42 def manifold_add_user(request, user_params):
43     # user_params: email, password e.g., user_params = {'email':'aa@aa.com','password':'demo'}
44     query = Query.create('local:user').set(user_params).select('email')
45     results = execute_query(request,query)
46     if not results:
47         raise Exception, "Failed creating manifold user: %s" % user_params['email']
48     result, = results
49     return result['email']
50
51 def manifold_update_user(request, user_params):
52     # user_params: password, config e.g., 
53     query = Query.update('local:user').filter_by('email', '==', request.user.email).set(user_params).select('email')
54     results = execute_query(request,query)
55     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
56     # That's why I commented the exception part. -- Yasin 
57     #if not results:
58     #    raise Exception, "Failed updating manifold user: %s" % user_params['email']
59     #result, = results
60     return results
61
62 def manifold_add_account(request, account_params):
63     query = Query.create('local:account').set(account_params).select(['user', 'platform'])
64     results = execute_query(request,query)
65     if not results:
66         raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
67     result, = results
68     return (result['user'], result['platform'])
69
70 def manifold_update_account(request,account_params):
71     # account_params: config
72     query = Query.update('local:account').filter_by('email', '==', request.user.email).set(account_params).select('email')
73     results = execute_query(request,query)
74     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
75     # That's why I commented the exception part. -- Yasin 
76     #if not results:
77     #    raise Exception, "Failed updating manifold account: config %s" % account_params['config']
78     #result, = results
79     return results
80
81
82 def make_request_user(user):
83     request = {}
84     request['type'] = 'user'
85     request['id'] = user.id
86     request['timestamp'] = 'TODO' # XXX in DB ?
87     request['authority_hrn'] = user.authority_hrn
88     request['first_name'] = user.first_name
89     request['last_name'] = user.last_name
90     request['email'] = user.email
91     return request
92
93 def make_request_slice(slice):
94     request = {}
95     request['type'] = 'slice'
96     request['id'] = slice.id
97     request['timestamp'] = 'TODO' # XXX in DB ?
98     request['authority_hrn'] = slice.authority_hrn
99     request['number_of_nodes'] = slice.number_of_nodes
100     request['type_of_nodes'] = slice.type_of_nodes
101     request['purpose'] = slice.purpose
102     return request
103
104 def make_requests(pending_users, pending_slices):
105     print "pending users =", pending_users
106     print "pending slices =", pending_slices
107
108     requests = []
109     for user in pending_users:
110         requests.append(make_request_user(user))
111     for slice in pending_slices:
112         requests.append(make_request_slice(slice))
113     return requests   
114
115 def get_request_by_id(ids):
116     sorted_ids = { 'user': [], 'slice': [] }
117     for type__id in ids:
118         type, id = type__id.split('__')
119         sorted_ids[type].append(id)
120         
121     if not ids:
122         pending_users  = PendingUser.objects.all()
123         pending_slices = PendingSlice.objects.all()
124     else:
125         pending_users  = PendingUser.objects.filter(id__in=sorted_ids['user']).all()
126         pending_slices = PendingSlice.objects.filter(id__in=sorted_ids['slice']).all()
127
128     return make_requests(pending_users, pending_slices)
129
130 def get_request_by_authority(authority_hrns):
131     if not authority_hrns:
132         pending_users  = PendingUser.objects.all()
133         pending_slices = PendingSlice.objects.all()
134     else:
135         pending_users  = PendingUser.objects.filter(authority_hrn__in=authority_hrns).all()
136         pending_slices = PendingSlice.objects.filter(authority_hrn__in=authority_hrns).all()
137
138     return make_requests(pending_users, pending_slices)
139     
140 SFA_USER_KEYS         = ['xrn', 'type', 'key', 'first_name', 'last_name', 'email']
141 SFA_SLICE_KEYS        = []
142 MANIFOLD_USER_KEYS    = ['email', 'password']
143 MANIFOLD_ACCOUNT_KEYS = []
144
145 def portal_validate_request(request_ids):
146     status = {}
147
148     if not isinstance(request_ids, list):
149         request_ids = [request_ids]
150
151     requests = get_request_by_id(request_ids)
152     for request in requests:
153         # type, id, timestamp, details, allowed -- MISSING: authority_hrn
154         # CAREFUL about details
155         # user  : first name, last name, email, password, keypair
156         # slice : number of nodes, type of nodes, purpose
157         
158         request_status = {}
159
160         if request['type'] == 'user':
161             try:
162                 sfa_user_params = { key: request[key] for key in SFA_USER_KEYS }
163                 sfa_user_params['enabled'] = True
164                 # XXX # sfa_add_user(sfa_user_params)
165                 request_status['SFA user'] = {'status': True }
166             except Exception, e:
167                 request_status['SFA user'] = {'status': False, 'description': str(e)}
168
169             try:
170                 manifold_user_params = { key: request[key] for key in MANIFOLD_USER_KEYS }
171                 # XXX # manifold_add_user(manifold_user_params)
172                 request_status['MySlice user'] = {'status': True }
173             except Exception, e:
174                 request_status['MySlice user'] = {'status': False, 'description': str(e)}
175
176             # XXX
177             #manifold_account_params = { key: request[key] for key in MANIFOLD_ACCOUNT_KEYS }
178             #manifold_add_account(manifold_account_params)
179             request_status['MySlice testbed accounts'] = {'status': False }
180
181         elif request['type'] == 'slice':
182             try:
183                 sfa_slice_params = { key: request[key] for key in SFA_SLICE_KEYS }
184                 # XXX # sfa_add_slice(sfa_slice_params)
185                 request_status['SFA slice'] = {'status': True }
186             except Exception, e:
187                 request_status['SFA slice'] = {'status': False, 'description': str(e)}
188
189         status['%s__%s' % (request['type'], request['id'])] = request_status
190
191     # XXX remove from database succeeded actions
192
193     return status
194
195
196 def validate_action(*args, **kwargs):
197     ids = filter(None, kwargs['id'].split('/'))
198     status = portal_validate_request(ids)
199     json_answer = json.dumps(status)
200     return HttpResponse (json_answer, mimetype="application/json")
201
202 # Django and ajax
203 # http://djangosnippets.org/snippets/942/