6 from unfold.loginrequired import LoginRequiredAutoLogoutView
8 from manifold.core.query import Query
9 from manifoldapi.manifoldapi import execute_query, execute_admin_query
10 from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account
11 from portal.actions import (
12 sfa_update_user, authority_get_pis, authority_add_pis,
13 authority_remove_pis,authority_check_pis ,clear_user_creds )
15 from unfold.page import Page
16 from ui.topmenu import topmenu_items_live, the_user
18 from django.http import HttpResponse, HttpResponseRedirect
19 from django.contrib import messages
20 from django.contrib.auth.decorators import login_required
21 from myslice.theme import ThemeView
24 class UserView(LoginRequiredAutoLogoutView, ThemeView):
25 template_name = "manageuserview.html"
26 def dispatch(self, *args, **kwargs):
27 return super(UserView, self).dispatch(*args, **kwargs)
30 def get_context_data(self, **kwargs):
32 page = Page(self.request)
33 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js", "js/jquery-ui.js" ] )
34 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css","css/jquery-ui.css" ] )
36 for key, value in kwargs.iteritems():
40 user_query = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','config','email','status')
41 user_details = execute_admin_query(self.request, user_query)
43 # not always found in user_details...
45 for user_detail in user_details:
46 user_id = user_detail['user_id']
47 user_email = user_detail['email']
48 # different significations of user_status
49 if user_detail['status'] == 0:
50 user_status = 'Disabled'
51 elif user_detail['status'] == 1:
52 user_status = 'Validation Pending'
53 elif user_detail['status'] == 2:
54 user_status = 'Enabled'
57 #email = user_detail['email']
58 if user_detail['config']:
59 config = json.loads(user_detail['config'])
60 authority_hrn = config.get('authority','Unknown Authority')
63 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
64 account_query = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
65 platform_details = execute_query(self.request, platform_query)
66 account_details = execute_admin_query(self.request, account_query)
68 # initial assignment needed for users having account.config = {}
74 account_reference = ''
79 principal_acc_list = ''
81 platform_name_list = []
82 platform_name_secondary_list = []
83 platform_access_list = []
84 platform_no_access_list = []
85 total_platform_list = []
86 account_type_list = []
87 account_type_secondary_list = []
88 account_reference_list = []
89 delegation_type_list = []
90 user_cred_exp_list = []
93 slice_cred_exp_list = []
94 auth_cred_exp_list = []
98 for platform_detail in platform_details:
99 if 'sfa' in platform_detail['gateway_type']:
100 total_platform = platform_detail['platform']
101 total_platform_list.append(total_platform)
103 for account_detail in account_details:
104 if platform_detail['platform_id'] == account_detail['platform_id']:
105 platform_name = platform_detail['platform']
106 if 'config' in account_detail and account_detail['config'] is not '':
107 account_config = json.loads(account_detail['config'])
108 account_usr_hrn = account_config.get('user_hrn','N/A')
109 account_pub_key = account_config.get('user_public_key','N/A')
110 account_reference = account_config.get ('reference_platform','N/A')
112 # credentials of myslice platform
113 if 'myslice' in platform_detail['platform']:
114 acc_user_cred = account_config.get('delegated_user_credential','N/A')
115 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
116 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
117 #usr_hrn of myslice platform. used to check pi or no
118 account_usr_hrn_myslice = account_config.get('user_hrn','N/A')
121 if 'N/A' not in acc_user_cred:
122 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
124 user_exp_date = exp_date.group(1)
125 user_cred_exp_list.append(user_exp_date)
127 my_users = [{'cred_exp': t[0]}
128 for t in zip(user_cred_exp_list)]
131 if 'N/A' not in acc_slice_cred:
132 for key, value in acc_slice_cred.iteritems():
133 slice_list.append(key)
135 exp_date = re.search('<expires>(.*)</expires>', value)
137 exp_date = exp_date.group(1)
138 slice_cred_exp_list.append(exp_date)
140 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
141 for t in zip(slice_list, slice_cred_exp_list)]
143 if 'N/A' not in acc_auth_cred:
144 for key, value in acc_auth_cred.iteritems():
145 auth_list.append(key)
147 exp_date = re.search('<expires>(.*)</expires>', value)
149 exp_date = exp_date.group(1)
150 auth_cred_exp_list.append(exp_date)
152 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
153 for t in zip(auth_list, auth_cred_exp_list)]
155 # for reference accounts
156 if 'reference' in account_detail['auth_type']:
157 account_type = 'Reference'
159 platform_name_secondary_list.append(platform_name)
160 account_type_secondary_list.append(account_type)
161 account_reference_list.append(account_reference)
162 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
163 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
165 elif 'managed' in account_detail['auth_type']:
166 account_type = 'Principal'
167 delegation = 'Automatic'
169 account_type = 'Principal'
170 delegation = 'Manual'
171 # for principal (auth_type=user/managed) accounts
172 if 'reference' not in account_detail['auth_type']:
173 platform_name_list.append(platform_name)
174 account_type_list.append(account_type)
175 delegation_type_list.append(delegation)
176 usr_hrn_list.append(account_usr_hrn)
177 pub_key_list.append(account_pub_key)
178 user_status_list.append(user_status)
179 # combining 5 lists into 1 [to render in the template]
180 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],}
181 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
182 # to hide private key row if it doesn't exist
183 if 'myslice' in platform_detail['platform']:
184 account_config = json.loads(account_detail['config'])
185 account_priv_key = account_config.get('user_private_key','N/A')
186 if 'sfa' in platform_detail['gateway_type']:
187 platform_access = platform_detail['platform']
188 platform_access_list.append(platform_access)
190 # Removing the platform which already has access
191 for platform in platform_access_list:
192 total_platform_list.remove(platform)
193 # we could use zip. this one is used if columns have unequal rows
194 platform_list = [{'platform_no_access': t[0]}
195 for t in itertools.izip_longest(total_platform_list)]
198 pi_status = authority_check_pis(self.request, user_email)
200 context = super(UserView, self).get_context_data(**kwargs)
201 context['principal_acc'] = principal_acc_list
202 context['ref_acc'] = ref_acc_list
203 context['platform_list'] = platform_list
204 context['my_users'] = my_users
205 context['my_slices'] = my_slices
206 context['my_auths'] = my_auths
207 context['user_status'] = user_status
208 context['user_email'] = user_email
209 context['firstname'] = config.get('firstname',"?")
210 context['lastname'] = config.get('lastname',"?")
211 context['fullname'] = context['firstname'] +' '+ context['lastname']
212 context['authority'] = config.get('authority',"Unknown Authority")
213 context['user_private_key'] = account_priv_key
214 context['pi'] = pi_status
216 # XXX This is repeated in all pages
217 # more general variables expected in the template
218 context['title'] = 'Platforms connected to MySlice'
219 # the menu items on the top
220 context['topmenu_items'] = topmenu_items_live('My Account', page)
221 # so we can sho who is logged
222 context['username'] = the_user(self.request)
223 context['theme'] = self.theme
224 # context ['firstname'] = config['firstname']
225 prelude_env = page.prelude_env()
226 context.update(prelude_env)
231 #my_acc form value processing
232 def user_process(request, **kwargs):
234 for key, value in kwargs.iteritems():
238 redirect_url = "/portal/user/"+selected_email
240 user_query = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','email','password','config')
241 user_details = execute_admin_query(request, user_query)
243 # getting the user_id from the session
244 for user_detail in user_details:
245 user_id = user_detail['user_id']
246 user_email = user_detail['email']
248 account_query = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
249 account_details = execute_admin_query(request, account_query)
251 platform_query = Query().get('local:platform').select('platform_id','platform')
252 platform_details = execute_admin_query(request, platform_query)
255 for account_detail in account_details:
256 for platform_detail in platform_details:
257 # Add reference account to the platforms
258 if 'add_'+platform_detail['platform'] in request.POST:
259 platform_id = platform_detail['platform_id']
260 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
261 manifold_add_account(request, user_params)
262 messages.info(request, 'Reference Account is added to the selected platform successfully!')
263 return HttpResponseRedirect(redirect_url)
265 # Delete reference account from the platforms
266 if 'delete_'+platform_detail['platform'] in request.POST:
267 platform_id = platform_detail['platform_id']
268 user_params = {'user_id':user_id}
269 manifold_delete_account(request, platform_id, user_id, user_params)
270 messages.info(request, 'Refeence Account is removed from the selected platform')
271 return HttpResponseRedirect(redirect_url)
273 if platform_detail['platform_id'] == account_detail['platform_id']:
274 if 'myslice' in platform_detail['platform']:
275 account_config = json.loads(account_detail['config'])
276 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
277 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
279 # adding the slices and corresponding credentials to list
280 if 'N/A' not in acc_slice_cred:
283 for key, value in acc_slice_cred.iteritems():
284 slice_list.append(key)
285 slice_cred.append(value)
286 # special case: download each slice credentials separately
287 for i in range(0, len(slice_list)):
288 if 'dl_'+slice_list[i] in request.POST:
289 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
290 response = HttpResponse(slice_detail, content_type='text/plain')
291 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
294 # adding the authority and corresponding credentials to list
295 if 'N/A' not in acc_auth_cred:
298 for key, value in acc_auth_cred.iteritems():
299 auth_list.append(key)
300 auth_cred.append(value)
301 # special case: download each slice credentials separately
302 for i in range(0, len(auth_list)):
303 if 'dl_'+auth_list[i] in request.POST:
304 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
305 response = HttpResponse(auth_detail, content_type='text/plain')
306 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
309 if 'submit_name' in request.POST:
310 edited_first_name = request.POST['fname']
311 edited_last_name = request.POST['lname']
314 for user_config in user_details:
315 if user_config['config']:
316 config = json.loads(user_config['config'])
317 config['firstname'] = edited_first_name
318 config['lastname'] = edited_last_name
319 config['authority'] = config.get('authority','Unknown Authority')
320 updated_config = json.dumps(config)
321 user_params = {'config': updated_config}
322 else: # it's needed if the config is empty
323 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
324 user_params = {'config': user_config['config']}
325 # updating config local:user in manifold
326 manifold_update_user(request, user_email, user_params)
327 # this will be depricated, we will show the success msg in same page
328 # Redirect to same page with success message
329 messages.success(request, 'Sucess: First Name and Last Name Updated.')
330 return HttpResponseRedirect(redirect_url)
332 elif 'submit_auth' in request.POST:
333 edited_auth = request.POST['authority']
336 for user_config in user_details:
337 if user_config['config']:
338 config = json.loads(user_config['config'])
339 config['firstname'] = config.get('firstname', 'N/A')
340 config['lastname'] = config.get('lastname','N/A')
341 config['authority'] = edited_auth
342 updated_config = json.dumps(config)
343 user_params = {'config': updated_config}
344 else: # it's needed if the config is empty
345 user_config['config']= '{"firstname": "N/A", "lastname":"N/A", "authority":"' + edited_auth + '"}'
346 user_params = {'config': user_config['config']}
347 # updating config local:user in manifold
348 manifold_update_user(request, user_email, user_params)
349 # this will be depricated, we will show the success msg in same page
350 # Redirect to same page with success message
351 messages.success(request, 'Sucess: Authority Updated.')
352 return HttpResponseRedirect(redirect_url)
354 # XXX TODO: Factorize with portal/registrationview.py
356 elif 'generate' in request.POST:
357 for account_detail in account_details:
358 for platform_detail in platform_details:
359 if platform_detail['platform_id'] == account_detail['platform_id']:
360 if 'myslice' in platform_detail['platform']:
361 from Crypto.PublicKey import RSA
362 private = RSA.generate(1024)
363 private_key = json.dumps(private.exportKey())
364 public = private.publickey()
365 public_key = json.dumps(public.exportKey(format='OpenSSH'))
366 # updating manifold local:account table
367 account_config = json.loads(account_detail['config'])
368 # preserving user_hrn
369 user_hrn = account_config.get('user_hrn','N/A')
370 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
371 updated_config = json.dumps(account_config)
373 user_params = { 'config': keypair, 'auth_type':'managed'}
374 manifold_update_account(request, user_id, user_params)
376 #public_key = public_key.replace('"', '');
377 #user_pub_key = {'keys': public_key}
378 #sfa_update_user(request, user_hrn, user_pub_key)
379 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
380 return HttpResponseRedirect(redirect_url)
382 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
383 return HttpResponseRedirect(redirect_url)
385 elif 'upload_key' in request.POST:
386 for account_detail in account_details:
387 for platform_detail in platform_details:
388 if platform_detail['platform_id'] == account_detail['platform_id']:
389 if 'myslice' in platform_detail['platform']:
390 up_file = request.FILES['pubkey']
391 file_content = up_file.read()
392 file_name = up_file.name
393 file_extension = os.path.splitext(file_name)[1]
394 allowed_extension = ['.pub','.txt']
395 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
396 account_config = json.loads(account_detail['config'])
397 # preserving user_hrn
398 user_hrn = account_config.get('user_hrn','N/A')
399 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
400 #file_content = re.sub("\r", "", file_content)
401 #file_content = re.sub("\n", "\\n",file_content)
402 file_content = ''.join(file_content.split())
403 #update manifold local:account table
404 user_params = { 'config': file_content, 'auth_type':'user'}
405 manifold_update_account(request,user_id,user_params)
407 #user_pub_key = {'keys': file_content}
408 #sfa_update_user(request, user_hrn, user_pub_key)
409 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
410 return HttpResponseRedirect(redirect_url)
412 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
413 return HttpResponseRedirect(redirect_url)
415 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
416 return HttpResponseRedirect(redirect_url)
418 elif 'dl_pubkey' in request.POST:
419 for account_detail in account_details:
420 for platform_detail in platform_details:
421 if platform_detail['platform_id'] == account_detail['platform_id']:
422 if 'myslice' in platform_detail['platform']:
423 account_config = json.loads(account_detail['config'])
424 public_key = account_config['user_public_key']
425 response = HttpResponse(public_key, content_type='text/plain')
426 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
430 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
431 return HttpResponseRedirect(redirect_url)
433 elif 'dl_pkey' in request.POST:
434 for account_detail in account_details:
435 for platform_detail in platform_details:
436 if platform_detail['platform_id'] == account_detail['platform_id']:
437 if 'myslice' in platform_detail['platform']:
438 account_config = json.loads(account_detail['config'])
439 if 'user_private_key' in account_config:
440 private_key = account_config['user_private_key']
441 response = HttpResponse(private_key, content_type='text/plain')
442 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
445 messages.error(request, 'Download error: Private key is not stored in the server')
446 return HttpResponseRedirect(redirect_url)
449 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
450 return HttpResponseRedirect(redirect_url)
452 # elif 'delete' in request.POST:
453 # for account_detail in account_details:
454 # for platform_detail in platform_details:
455 # if platform_detail['platform_id'] == account_detail['platform_id']:
456 # if 'myslice' in platform_detail['platform']:
457 # account_config = json.loads(account_detail['config'])
458 # if 'user_private_key' in account_config:
459 # for key in account_config.keys():
460 # if key == 'user_private_key':
461 # del account_config[key]
463 # updated_config = json.dumps(account_config)
464 # user_params = { 'config': updated_config, 'auth_type':'user'}
465 # manifold_update_account(request,user_params)
466 # messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
467 # messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
468 # return HttpResponseRedirect("/portal/account/")
470 # messages.error(request, 'Delete error: Private key is not stored in the server')
471 # return HttpResponseRedirect(redirect_url)
474 # messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
475 # return HttpResponseRedirect(redirect_url)
478 elif 'clear_cred' in request.POST:
479 clear_user_creds(request, user_email)
480 messages.success(request, 'All Credentials cleared')
481 return HttpResponseRedirect(redirect_url)
484 elif 'makepi' in request.POST:
485 # getting user's authority_hrn
487 for user_config in user_details:
488 if user_config['config']:
489 user_config = json.loads(user_config['config'])
490 authority_hrn = user_config.get('authority','Unknown Authority')
493 for account_detail in account_details:
494 for platform_detail in platform_details:
495 if platform_detail['platform_id'] == account_detail['platform_id']:
496 if 'myslice' in platform_detail['platform']:
497 account_config = json.loads(account_detail['config'])
498 user_hrn = account_config.get('user_hrn','N/A')
500 authority_add_pis(request, authority_hrn, user_hrn)
501 clear_user_creds(request, user_email)
502 messages.success(request, 'User upgraded to PI')
503 return HttpResponseRedirect(redirect_url)
505 elif 'removepi' in request.POST:
506 # getting user's authority_hrn
508 for user_config in user_details:
509 if user_config['config']:
510 user_config = json.loads(user_config['config'])
511 authority_hrn = user_config.get('authority','Unknown Authority')
513 for account_detail in account_details:
514 for platform_detail in platform_details:
515 if platform_detail['platform_id'] == account_detail['platform_id']:
516 if 'myslice' in platform_detail['platform']:
517 account_config = json.loads(account_detail['config'])
518 user_hrn = account_config.get('user_hrn','N/A')
519 authority_remove_pis(request, authority_hrn, user_hrn)
520 clear_user_creds(request, user_email)
521 messages.success(request, 'PI downgraded to user')
522 return HttpResponseRedirect(redirect_url)
526 # Download delegated_user_cred
527 elif 'dl_user_cred' in request.POST:
528 if 'delegated_user_credential' in account_config:
529 user_cred = account_config['delegated_user_credential']
530 response = HttpResponse(user_cred, content_type='text/plain')
531 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
534 messages.error(request, 'Download error: User credential is not stored in the server')
535 return HttpResponseRedirect(redirect_url)
538 messages.info(request, 'Under Construction. Please try again later!')
539 return HttpResponseRedirect(redirect_url)