1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from manifold.core.query import Query
4 from manifoldapi.manifoldapi import execute_query, execute_admin_query
5 from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user
7 from unfold.page import Page
8 from ui.topmenu import topmenu_items_live, the_user
10 from django.http import HttpResponse, HttpResponseRedirect
11 from django.contrib import messages
12 from django.contrib.auth.decorators import login_required
13 from myslice.theme import ThemeView
15 import json, os, re, itertools
18 class UserView(LoginRequiredAutoLogoutView, ThemeView):
19 template_name = "manageuserview.html"
20 def dispatch(self, *args, **kwargs):
21 return super(UserView, self).dispatch(*args, **kwargs)
24 def get_context_data(self, **kwargs):
26 page = Page(self.request)
27 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js", "js/jquery-ui.js" ] )
28 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css","css/jquery-ui.css" ] )
30 for key, value in kwargs.iteritems():
31 #print "%s = %s" % (key, value)
35 user_query = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','config','email','status')
36 user_details = execute_admin_query(self.request, user_query)
38 # not always found in user_details...
40 for user_detail in user_details:
41 user_id = user_detail['user_id']
42 user_email = user_detail['email']
43 # different significations of user_status
44 if user_detail['status'] == 0:
45 user_status = 'Disabled'
46 elif user_detail['status'] == 1:
47 user_status = 'Validation Pending'
48 elif user_detail['status'] == 2:
49 user_status = 'Enabled'
52 #email = user_detail['email']
53 if user_detail['config']:
54 config = json.loads(user_detail['config'])
56 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
57 account_query = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
58 platform_details = execute_query(self.request, platform_query)
59 account_details = execute_admin_query(self.request, account_query)
61 # initial assignment needed for users having account.config = {}
67 account_reference = ''
72 principal_acc_list = ''
74 platform_name_list = []
75 platform_name_secondary_list = []
76 platform_access_list = []
77 platform_no_access_list = []
78 total_platform_list = []
79 account_type_list = []
80 account_type_secondary_list = []
81 account_reference_list = []
82 delegation_type_list = []
83 user_cred_exp_list = []
86 slice_cred_exp_list = []
87 auth_cred_exp_list = []
91 for platform_detail in platform_details:
92 if 'sfa' in platform_detail['gateway_type']:
93 total_platform = platform_detail['platform']
94 total_platform_list.append(total_platform)
96 for account_detail in account_details:
97 if platform_detail['platform_id'] == account_detail['platform_id']:
98 platform_name = platform_detail['platform']
99 if 'config' in account_detail and account_detail['config'] is not '':
100 account_config = json.loads(account_detail['config'])
101 account_usr_hrn = account_config.get('user_hrn','N/A')
102 account_pub_key = account_config.get('user_public_key','N/A')
103 account_reference = account_config.get ('reference_platform','N/A')
104 # credentials of myslice platform
105 if 'myslice' in platform_detail['platform']:
106 acc_user_cred = account_config.get('delegated_user_credential','N/A')
107 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
108 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
110 if 'N/A' not in acc_user_cred:
111 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
113 user_exp_date = exp_date.group(1)
114 user_cred_exp_list.append(user_exp_date)
116 my_users = [{'cred_exp': t[0]}
117 for t in zip(user_cred_exp_list)]
120 if 'N/A' not in acc_slice_cred:
121 for key, value in acc_slice_cred.iteritems():
122 slice_list.append(key)
124 exp_date = re.search('<expires>(.*)</expires>', value)
126 exp_date = exp_date.group(1)
127 slice_cred_exp_list.append(exp_date)
129 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
130 for t in zip(slice_list, slice_cred_exp_list)]
132 if 'N/A' not in acc_auth_cred:
133 for key, value in acc_auth_cred.iteritems():
134 auth_list.append(key)
136 exp_date = re.search('<expires>(.*)</expires>', value)
138 exp_date = exp_date.group(1)
139 auth_cred_exp_list.append(exp_date)
141 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
142 for t in zip(auth_list, auth_cred_exp_list)]
145 # for reference accounts
146 if 'reference' in account_detail['auth_type']:
147 account_type = 'Reference'
149 platform_name_secondary_list.append(platform_name)
150 account_type_secondary_list.append(account_type)
151 account_reference_list.append(account_reference)
152 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
153 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
155 elif 'managed' in account_detail['auth_type']:
156 account_type = 'Principal'
157 delegation = 'Automatic'
159 account_type = 'Principal'
160 delegation = 'Manual'
161 # for principal (auth_type=user/managed) accounts
162 if 'reference' not in account_detail['auth_type']:
163 platform_name_list.append(platform_name)
164 account_type_list.append(account_type)
165 delegation_type_list.append(delegation)
166 usr_hrn_list.append(account_usr_hrn)
167 pub_key_list.append(account_pub_key)
168 user_status_list.append(user_status)
169 # combining 5 lists into 1 [to render in the template]
170 principal_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'usr_hrn':t[3], 'usr_pubkey':t[4], 'user_status':t[5],}
171 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
172 # to hide private key row if it doesn't exist
173 if 'myslice' in platform_detail['platform']:
174 account_config = json.loads(account_detail['config'])
175 account_priv_key = account_config.get('user_private_key','N/A')
176 if 'sfa' in platform_detail['gateway_type']:
177 platform_access = platform_detail['platform']
178 platform_access_list.append(platform_access)
180 # Removing the platform which already has access
181 for platform in platform_access_list:
182 total_platform_list.remove(platform)
183 # we could use zip. this one is used if columns have unequal rows
184 platform_list = [{'platform_no_access': t[0]}
185 for t in itertools.izip_longest(total_platform_list)]
187 context = super(UserView, self).get_context_data(**kwargs)
188 context['principal_acc'] = principal_acc_list
189 context['ref_acc'] = ref_acc_list
190 context['platform_list'] = platform_list
191 context['my_users'] = my_users
192 context['my_slices'] = my_slices
193 context['my_auths'] = my_auths
194 context['user_status'] = user_status
195 context['user_email'] = user_email
196 context['firstname'] = config.get('firstname',"?")
197 context['lastname'] = config.get('lastname',"?")
198 context['fullname'] = context['firstname'] +' '+ context['lastname']
199 context['authority'] = config.get('authority',"Unknown Authority")
200 context['user_private_key'] = account_priv_key
202 # XXX This is repeated in all pages
203 # more general variables expected in the template
204 context['title'] = 'Platforms connected to MySlice'
205 # the menu items on the top
206 context['topmenu_items'] = topmenu_items_live('My Account', page)
207 # so we can sho who is logged
208 context['username'] = the_user(self.request)
209 context['theme'] = self.theme
210 # context ['firstname'] = config['firstname']
211 prelude_env = page.prelude_env()
212 context.update(prelude_env)
217 #my_acc form value processing
218 def user_process(request, **kwargs):
220 for key, value in kwargs.iteritems():
224 redirect_url = "/portal/user/"+selected_email
226 user_query = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','email','password','config')
227 user_details = execute_admin_query(request, user_query)
229 # getting the user_id from the session
230 for user_detail in user_details:
231 user_id = user_detail['user_id']
232 user_email = user_detail['email']
234 account_query = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
235 account_details = execute_admin_query(request, account_query)
237 platform_query = Query().get('local:platform').select('platform_id','platform')
238 platform_details = execute_admin_query(request, platform_query)
241 for account_detail in account_details:
242 for platform_detail in platform_details:
243 # Add reference account to the platforms
244 if 'add_'+platform_detail['platform'] in request.POST:
245 platform_id = platform_detail['platform_id']
246 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
247 manifold_add_account(request, user_params)
248 messages.info(request, 'Reference Account is added to the selected platform successfully!')
249 return HttpResponseRedirect(redirect_url)
251 # Delete reference account from the platforms
252 if 'delete_'+platform_detail['platform'] in request.POST:
253 platform_id = platform_detail['platform_id']
254 user_params = {'user_id':user_id}
255 manifold_delete_account(request, platform_id, user_id, user_params)
256 messages.info(request, 'Refeence Account is removed from the selected platform')
257 return HttpResponseRedirect(redirect_url)
259 if platform_detail['platform_id'] == account_detail['platform_id']:
260 if 'myslice' in platform_detail['platform']:
261 account_config = json.loads(account_detail['config'])
262 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
263 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
265 # adding the slices and corresponding credentials to list
266 if 'N/A' not in acc_slice_cred:
269 for key, value in acc_slice_cred.iteritems():
270 slice_list.append(key)
271 slice_cred.append(value)
272 # special case: download each slice credentials separately
273 for i in range(0, len(slice_list)):
274 if 'dl_'+slice_list[i] in request.POST:
275 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
276 response = HttpResponse(slice_detail, content_type='text/plain')
277 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
280 # adding the authority and corresponding credentials to list
281 if 'N/A' not in acc_auth_cred:
284 for key, value in acc_auth_cred.iteritems():
285 auth_list.append(key)
286 auth_cred.append(value)
287 # special case: download each slice credentials separately
288 for i in range(0, len(auth_list)):
289 if 'dl_'+auth_list[i] in request.POST:
290 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
291 response = HttpResponse(auth_detail, content_type='text/plain')
292 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
295 if 'submit_name' in request.POST:
296 edited_first_name = request.POST['fname']
297 edited_last_name = request.POST['lname']
300 for user_config in user_details:
301 if user_config['config']:
302 config = json.loads(user_config['config'])
303 config['firstname'] = edited_first_name
304 config['lastname'] = edited_last_name
305 config['authority'] = config.get('authority','Unknown Authority')
306 updated_config = json.dumps(config)
307 user_params = {'config': updated_config}
308 else: # it's needed if the config is empty
309 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
310 user_params = {'config': user_config['config']}
311 # updating config local:user in manifold
312 manifold_update_user(request, user_email, user_params)
313 # this will be depricated, we will show the success msg in same page
314 # Redirect to same page with success message
315 messages.success(request, 'Sucess: First Name and Last Name Updated.')
316 return HttpResponseRedirect(redirect_url)
318 elif 'submit_auth' in request.POST:
319 edited_auth = request.POST['authority']
322 for user_config in user_details:
323 if user_config['config']:
324 config = json.loads(user_config['config'])
325 config['firstname'] = config.get('firstname', 'N/A')
326 config['lastname'] = config.get('lastname','N/A')
327 config['authority'] = edited_auth
328 updated_config = json.dumps(config)
329 user_params = {'config': updated_config}
330 else: # it's needed if the config is empty
331 user_config['config']= '{"firstname": "N/A", "lastname":"N/A", "authority":"' + edited_auth + '"}'
332 user_params = {'config': user_config['config']}
333 # updating config local:user in manifold
334 manifold_update_user(request, user_email, user_params)
335 # this will be depricated, we will show the success msg in same page
336 # Redirect to same page with success message
337 messages.success(request, 'Sucess: Authority Updated.')
338 return HttpResponseRedirect(redirect_url)
340 # XXX TODO: Factorize with portal/registrationview.py
342 elif 'generate' in request.POST:
343 for account_detail in account_details:
344 for platform_detail in platform_details:
345 if platform_detail['platform_id'] == account_detail['platform_id']:
346 if 'myslice' in platform_detail['platform']:
347 from Crypto.PublicKey import RSA
348 private = RSA.generate(1024)
349 private_key = json.dumps(private.exportKey())
350 public = private.publickey()
351 public_key = json.dumps(public.exportKey(format='OpenSSH'))
352 # updating manifold local:account table
353 account_config = json.loads(account_detail['config'])
354 # preserving user_hrn
355 user_hrn = account_config.get('user_hrn','N/A')
356 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
357 updated_config = json.dumps(account_config)
359 user_params = { 'config': keypair, 'auth_type':'managed'}
360 manifold_update_account(request, user_id, user_params)
362 #public_key = public_key.replace('"', '');
363 #user_pub_key = {'keys': public_key}
364 #sfa_update_user(request, user_hrn, user_pub_key)
365 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
366 return HttpResponseRedirect(redirect_url)
368 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
369 return HttpResponseRedirect(redirect_url)
371 elif 'upload_key' in request.POST:
372 for account_detail in account_details:
373 for platform_detail in platform_details:
374 if platform_detail['platform_id'] == account_detail['platform_id']:
375 if 'myslice' in platform_detail['platform']:
376 up_file = request.FILES['pubkey']
377 file_content = up_file.read()
378 file_name = up_file.name
379 file_extension = os.path.splitext(file_name)[1]
380 allowed_extension = ['.pub','.txt']
381 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
382 account_config = json.loads(account_detail['config'])
383 # preserving user_hrn
384 user_hrn = account_config.get('user_hrn','N/A')
385 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
386 #file_content = re.sub("\r", "", file_content)
387 #file_content = re.sub("\n", "\\n",file_content)
388 file_content = ''.join(file_content.split())
389 #update manifold local:account table
390 user_params = { 'config': file_content, 'auth_type':'user'}
391 manifold_update_account(request,user_id,user_params)
393 #user_pub_key = {'keys': file_content}
394 #sfa_update_user(request, user_hrn, user_pub_key)
395 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
396 return HttpResponseRedirect(redirect_url)
398 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
399 return HttpResponseRedirect(redirect_url)
401 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
402 return HttpResponseRedirect(redirect_url)
404 elif 'dl_pubkey' in request.POST:
405 for account_detail in account_details:
406 for platform_detail in platform_details:
407 if platform_detail['platform_id'] == account_detail['platform_id']:
408 if 'myslice' in platform_detail['platform']:
409 account_config = json.loads(account_detail['config'])
410 public_key = account_config['user_public_key']
411 response = HttpResponse(public_key, content_type='text/plain')
412 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
416 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
417 return HttpResponseRedirect(redirect_url)
419 elif 'dl_pkey' in request.POST:
420 for account_detail in account_details:
421 for platform_detail in platform_details:
422 if platform_detail['platform_id'] == account_detail['platform_id']:
423 if 'myslice' in platform_detail['platform']:
424 account_config = json.loads(account_detail['config'])
425 if 'user_private_key' in account_config:
426 private_key = account_config['user_private_key']
427 response = HttpResponse(private_key, content_type='text/plain')
428 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
431 messages.error(request, 'Download error: Private key is not stored in the server')
432 return HttpResponseRedirect(redirect_url)
435 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
436 return HttpResponseRedirect(redirect_url)
438 # elif 'delete' in request.POST:
439 # for account_detail in account_details:
440 # for platform_detail in platform_details:
441 # if platform_detail['platform_id'] == account_detail['platform_id']:
442 # if 'myslice' in platform_detail['platform']:
443 # account_config = json.loads(account_detail['config'])
444 # if 'user_private_key' in account_config:
445 # for key in account_config.keys():
446 # if key == 'user_private_key':
447 # del account_config[key]
449 # updated_config = json.dumps(account_config)
450 # user_params = { 'config': updated_config, 'auth_type':'user'}
451 # manifold_update_account(request,user_params)
452 # messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
453 # messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
454 # return HttpResponseRedirect("/portal/account/")
456 # messages.error(request, 'Delete error: Private key is not stored in the server')
457 # return HttpResponseRedirect(redirect_url)
460 # messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
461 # return HttpResponseRedirect(redirect_url)
464 elif 'clear_cred' in request.POST:
465 for account_detail in account_details:
466 for platform_detail in platform_details:
467 if platform_detail['platform_id'] == account_detail['platform_id']:
468 if 'myslice' in platform_detail['platform']:
469 account_config = json.loads(account_detail['config'])
470 user_cred = account_config.get('delegated_user_credential','N/A')
471 if 'N/A' not in user_cred:
472 user_hrn = account_config.get('user_hrn','N/A')
473 user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
474 user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
475 updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
476 user_params = { 'config': updated_config}
477 manifold_update_account(request, user_id,user_params)
478 messages.success(request, 'All Credentials cleared')
479 return HttpResponseRedirect(redirect_url)
481 messages.error(request, 'Delete error: Credentials are not stored in the server')
482 return HttpResponseRedirect(redirect_url)
484 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
485 return HttpResponseRedirect(redirect_url)
488 # Download delegated_user_cred
489 elif 'dl_user_cred' in request.POST:
490 if 'delegated_user_credential' in account_config:
491 user_cred = account_config['delegated_user_credential']
492 response = HttpResponse(user_cred, content_type='text/plain')
493 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
496 messages.error(request, 'Download error: User credential is not stored in the server')
497 return HttpResponseRedirect(redirect_url)
500 messages.info(request, 'Under Construction. Please try again later!')
501 return HttpResponseRedirect(redirect_url)