1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from sfa.trust.credential import Credential
4 from sfa.trust.certificate import Keypair
6 from manifold.core.query import Query
7 from manifoldapi.manifoldapi import execute_query
8 from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, sfa_get_user
10 from unfold.page import Page
11 from ui.topmenu import topmenu_items_live, the_user
13 from django.http import HttpResponse, HttpResponseRedirect
14 from django.contrib import messages
15 from django.contrib.auth.decorators import login_required
17 from myslice.theme import ThemeView
20 import json, os, re, itertools
21 from OpenSSL import crypto
22 from Crypto.PublicKey import RSA
25 class AccountView(LoginRequiredAutoLogoutView, ThemeView):
26 template_name = "account-view.html"
27 def dispatch(self, *args, **kwargs):
28 return super(AccountView, self).dispatch(*args, **kwargs)
31 def get_context_data(self, **kwargs):
32 self.template_name = self.template
33 page = Page(self.request)
34 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js","js/jquery-ui.js" ] )
35 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
38 user_query = Query().get('local:user').select('config','email','status')
39 user_details = execute_query(self.request, user_query)
41 # not always found in user_details...
43 for user_detail in user_details:
44 # different significations of user_status
45 if user_detail['status'] == 0:
46 user_status = 'Disabled'
47 elif user_detail['status'] == 1:
48 user_status = 'Validation Pending'
49 elif user_detail['status'] == 2:
50 user_status = 'Enabled'
53 #email = user_detail['email']
54 if user_detail['config']:
55 config = json.loads(user_detail['config'])
57 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
58 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
59 platform_details = execute_query(self.request, platform_query)
60 account_details = execute_query(self.request, account_query)
62 # initial assignment needed for users having account.config = {}
68 account_reference = ''
73 principal_acc_list = ''
75 platform_name_list = []
76 platform_name_secondary_list = []
77 platform_access_list = []
78 platform_no_access_list = []
79 total_platform_list = []
80 account_type_list = []
81 account_type_secondary_list = []
82 account_reference_list = []
83 delegation_type_list = []
84 user_cred_exp_list = []
87 slice_cred_exp_list = []
88 auth_cred_exp_list = []
92 for platform_detail in platform_details:
93 if 'sfa' in platform_detail['gateway_type']:
94 total_platform = platform_detail['platform']
95 total_platform_list.append(total_platform)
97 for account_detail in account_details:
98 if platform_detail['platform_id'] == account_detail['platform_id']:
99 platform_name = platform_detail['platform']
100 if 'config' in account_detail and account_detail['config'] is not '':
101 account_config = json.loads(account_detail['config'])
102 account_usr_hrn = account_config.get('user_hrn','N/A')
103 account_pub_key = account_config.get('user_public_key','N/A')
104 account_reference = account_config.get ('reference_platform','N/A')
105 # credentials of myslice platform
106 if 'myslice' in platform_detail['platform']:
107 acc_user_cred = account_config.get('delegated_user_credential','N/A')
108 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
109 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
111 if 'N/A' not in acc_user_cred:
112 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
114 user_exp_date = exp_date.group(1)
115 user_cred_exp_list.append(user_exp_date)
117 my_users = [{'cred_exp': t[0]}
118 for t in zip(user_cred_exp_list)]
121 if 'N/A' not in acc_slice_cred:
122 for key, value in acc_slice_cred.iteritems():
123 slice_list.append(key)
125 exp_date = re.search('<expires>(.*)</expires>', value)
127 exp_date = exp_date.group(1)
128 slice_cred_exp_list.append(exp_date)
130 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
131 for t in zip(slice_list, slice_cred_exp_list)]
133 if 'N/A' not in acc_auth_cred:
134 for key, value in acc_auth_cred.iteritems():
135 auth_list.append(key)
137 exp_date = re.search('<expires>(.*)</expires>', value)
139 exp_date = exp_date.group(1)
140 auth_cred_exp_list.append(exp_date)
142 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
143 for t in zip(auth_list, auth_cred_exp_list)]
146 # for reference accounts
147 if 'reference' in account_detail['auth_type']:
148 account_type = 'Reference'
150 platform_name_secondary_list.append(platform_name)
151 account_type_secondary_list.append(account_type)
152 account_reference_list.append(account_reference)
153 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
154 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
156 elif 'managed' in account_detail['auth_type']:
157 account_type = 'Principal'
158 delegation = 'Automatic'
160 account_type = 'Principal'
161 delegation = 'Manual'
162 # for principal (auth_type=user/managed) accounts
163 if 'reference' not in account_detail['auth_type']:
164 platform_name_list.append(platform_name)
165 account_type_list.append(account_type)
166 delegation_type_list.append(delegation)
167 usr_hrn_list.append(account_usr_hrn)
168 pub_key_list.append(account_pub_key)
169 user_status_list.append(user_status)
170 # combining 5 lists into 1 [to render in the template]
171 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],}
172 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
173 # to hide private key row if it doesn't exist
174 if 'myslice' in platform_detail['platform']:
175 account_config = json.loads(account_detail['config'])
176 account_priv_key = account_config.get('user_private_key','N/A')
177 if 'sfa' in platform_detail['gateway_type']:
178 platform_access = platform_detail['platform']
179 platform_access_list.append(platform_access)
181 # Removing the platform which already has access
182 for platform in platform_access_list:
183 total_platform_list.remove(platform)
184 # we could use zip. this one is used if columns have unequal rows
185 platform_list = [{'platform_no_access': t[0]}
186 for t in itertools.izip_longest(total_platform_list)]
189 ## check user is pi or not
190 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
191 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
192 platform_details = execute_query(self.request, platform_query)
193 account_details = execute_query(self.request, account_query)
194 for platform_detail in platform_details:
195 for account_detail in account_details:
196 if platform_detail['platform_id'] == account_detail['platform_id']:
197 if 'config' in account_detail and account_detail['config'] is not '':
198 account_config = json.loads(account_detail['config'])
199 if 'myslice' in platform_detail['platform']:
200 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
202 if acc_auth_cred == {} or acc_auth_cred == 'N/A':
207 context = super(AccountView, self).get_context_data(**kwargs)
208 context['principal_acc'] = principal_acc_list
209 context['ref_acc'] = ref_acc_list
210 context['platform_list'] = platform_list
211 context['my_users'] = my_users
213 context['my_slices'] = my_slices
214 context['my_auths'] = my_auths
215 context['user_status'] = user_status
216 context['person'] = self.request.user
217 context['firstname'] = config.get('firstname',"?")
218 context['lastname'] = config.get('lastname',"?")
219 context['fullname'] = context['firstname'] +' '+ context['lastname']
220 context['authority'] = config.get('authority',"Unknown Authority")
221 context['user_private_key'] = account_priv_key
223 # XXX This is repeated in all pages
224 # more general variables expected in the template
225 context['title'] = 'Platforms connected to MySlice'
226 # the menu items on the top
227 context['topmenu_items'] = topmenu_items_live('My Account', page)
228 # so we can sho who is logged
229 context['username'] = the_user(self.request)
230 context['theme'] = self.theme
231 context['section'] = "User account"
232 # context ['firstname'] = config['firstname']
233 prelude_env = page.prelude_env()
234 context.update(prelude_env)
239 #my_acc form value processing
240 def account_process(request):
241 user_query = Query().get('local:user').select('user_id','email','password','config')
242 user_details = execute_query(request, user_query)
244 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
245 account_details = execute_query(request, account_query)
247 platform_query = Query().get('local:platform').select('platform_id','platform')
248 platform_details = execute_query(request, platform_query)
250 # getting the user_id from the session
251 for user_detail in user_details:
252 user_id = user_detail['user_id']
254 for account_detail in account_details:
255 for platform_detail in platform_details:
256 # Add reference account to the platforms
257 if 'add_'+platform_detail['platform'] in request.POST:
258 platform_id = platform_detail['platform_id']
259 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
260 manifold_add_account(request,user_params)
261 messages.info(request, 'Reference Account is added to the selected platform successfully!')
262 return HttpResponseRedirect("/portal/account/")
264 # Delete reference account from the platforms
265 if 'delete_'+platform_detail['platform'] in request.POST:
266 platform_id = platform_detail['platform_id']
267 user_params = {'user_id':user_id}
268 manifold_delete_account(request,platform_id, user_id, user_params)
269 messages.info(request, 'Reference Account is removed from the selected platform')
270 return HttpResponseRedirect("/portal/account/")
272 if platform_detail['platform_id'] == account_detail['platform_id']:
273 if 'myslice' in platform_detail['platform']:
274 account_config = json.loads(account_detail['config'])
275 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
276 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
281 # adding the slices and corresponding credentials to list
282 if 'N/A' not in acc_slice_cred:
285 for key, value in acc_slice_cred.iteritems():
286 slice_list.append(key)
287 slice_cred.append(value)
288 # special case: download each slice credentials separately
289 for i in range(0, len(slice_list)):
290 if 'dl_'+slice_list[i] in request.POST:
291 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
292 response = HttpResponse(slice_detail, content_type='text/plain')
293 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
296 # adding the authority and corresponding credentials to list
297 if 'N/A' not in acc_auth_cred:
300 for key, value in acc_auth_cred.iteritems():
301 auth_list.append(key)
302 auth_cred.append(value)
303 # special case: download each slice credentials separately
304 for i in range(0, len(auth_list)):
305 if 'dl_'+auth_list[i] in request.POST:
306 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
307 response = HttpResponse(auth_detail, content_type='text/plain')
308 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
313 if 'submit_name' in request.POST:
314 edited_first_name = request.POST['fname']
315 edited_last_name = request.POST['lname']
318 for user_config in user_details:
319 if user_config['config']:
320 config = json.loads(user_config['config'])
321 config['firstname'] = edited_first_name
322 config['lastname'] = edited_last_name
323 config['authority'] = config.get('authority','Unknown Authority')
324 updated_config = json.dumps(config)
325 user_params = {'config': updated_config}
326 else: # it's needed if the config is empty
327 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
328 user_params = {'config': user_config['config']}
329 # updating config local:user in manifold
330 manifold_update_user(request, request.user.email,user_params)
331 # this will be depricated, we will show the success msg in same page
332 # Redirect to same page with success message
333 messages.success(request, 'Sucess: First Name and Last Name Updated.')
334 return HttpResponseRedirect("/portal/account/")
336 elif 'submit_pass' in request.POST:
337 edited_password = request.POST['password']
339 for user_pass in user_details:
340 user_pass['password'] = edited_password
341 #updating password in local:user
342 user_params = { 'password': user_pass['password']}
343 manifold_update_user(request,request.user.email,user_params)
344 # return HttpResponse('Success: Password Changed!!')
345 messages.success(request, 'Sucess: Password Updated.')
346 return HttpResponseRedirect("/portal/account/")
348 # XXX TODO: Factorize with portal/registrationview.py
350 elif 'generate' in request.POST:
351 for account_detail in account_details:
352 for platform_detail in platform_details:
353 if platform_detail['platform_id'] == account_detail['platform_id']:
354 if 'myslice' in platform_detail['platform']:
355 private = RSA.generate(1024)
356 private_key = json.dumps(private.exportKey())
357 public = private.publickey()
358 public_key = json.dumps(public.exportKey(format='OpenSSH'))
359 # updating manifold local:account table
360 account_config = json.loads(account_detail['config'])
361 # preserving user_hrn
362 user_hrn = account_config.get('user_hrn','N/A')
363 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
364 #updated_config = json.dumps(account_config)
366 #user_params = { 'config': keypair, 'auth_type':'managed'}
367 #manifold_update_account(request, user_id, user_params)
369 public_key = public_key.replace('"', '');
370 user_pub_key = {'keys': public_key}
371 #sfa_update_user(request, user_hrn, user_pub_key)
372 sfa_update_user(request, user_hrn, user_pub_key)
373 result_sfa_user = sfa_get_user(request, user_hrn, public_key)
375 result_sfa_user = result_sfa_user[0]
376 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
378 updated_config = json.dumps(account_config)
379 user_params = { 'config': keypair, 'auth_type':'managed'}
380 manifold_update_account(request, user_id, user_params)
381 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
383 raise Exception,"Keys are not matching"
385 messages.error(request, 'Error: An error occured during the update of your public key at the Registry, or your public key is not matching the one stored.')
386 return HttpResponseRedirect("/portal/account/")
388 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
389 return HttpResponseRedirect("/portal/account/")
391 elif 'upload_key' in request.POST:
392 for account_detail in account_details:
393 for platform_detail in platform_details:
394 if platform_detail['platform_id'] == account_detail['platform_id']:
395 if 'myslice' in platform_detail['platform']:
396 up_file = request.FILES['pubkey']
397 file_content = up_file.read()
398 file_name = up_file.name
399 file_extension = os.path.splitext(file_name)[1]
400 allowed_extension = ['.pub','.txt']
401 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
402 account_config = json.loads(account_detail['config'])
403 # preserving user_hrn
404 user_hrn = account_config.get('user_hrn','N/A')
405 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
406 #file_content = re.sub("\r", "", file_content)
407 #file_content = re.sub("\n", "\\n",file_content)
408 file_content = ''.join(file_content.split())
409 #update manifold local:account table
410 user_params = { 'config': file_content, 'auth_type':'user'}
411 manifold_update_account(request, user_id, user_params)
413 user_pub_key = {'keys': file_content}
414 sfa_update_user(request, user_hrn, user_pub_key)
415 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
416 return HttpResponseRedirect("/portal/account/")
418 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
419 return HttpResponseRedirect("/portal/account/")
421 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
422 return HttpResponseRedirect("/portal/account/")
424 elif 'dl_pubkey' in request.POST:
425 for account_detail in account_details:
426 for platform_detail in platform_details:
427 if platform_detail['platform_id'] == account_detail['platform_id']:
428 if 'myslice' in platform_detail['platform']:
429 account_config = json.loads(account_detail['config'])
430 public_key = account_config['user_public_key']
431 response = HttpResponse(public_key, content_type='text/plain')
432 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
436 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
437 return HttpResponseRedirect("/portal/account/")
439 elif 'dl_pkey' in request.POST:
440 for account_detail in account_details:
441 for platform_detail in platform_details:
442 if platform_detail['platform_id'] == account_detail['platform_id']:
443 if 'myslice' in platform_detail['platform']:
444 account_config = json.loads(account_detail['config'])
445 if 'user_private_key' in account_config:
446 private_key = account_config['user_private_key']
447 response = HttpResponse(private_key, content_type='text/plain')
448 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
451 messages.error(request, 'Download error: Private key is not stored in the server')
452 return HttpResponseRedirect("/portal/account/")
455 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
456 return HttpResponseRedirect("/portal/account/")
458 elif 'delete' in request.POST:
459 for account_detail in account_details:
460 for platform_detail in platform_details:
461 if platform_detail['platform_id'] == account_detail['platform_id']:
462 if 'myslice' in platform_detail['platform']:
463 account_config = json.loads(account_detail['config'])
464 if 'user_private_key' in account_config:
465 for key in account_config.keys():
466 if key == 'user_private_key':
467 del account_config[key]
469 updated_config = json.dumps(account_config)
470 user_params = { 'config': updated_config, 'auth_type':'user'}
471 manifold_update_account(request, user_id, user_params)
472 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
473 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
474 return HttpResponseRedirect("/portal/account/")
476 messages.error(request, 'Delete error: Private key is not stored in the server')
477 return HttpResponseRedirect("/portal/account/")
480 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
481 return HttpResponseRedirect("/portal/account/")
483 # download identity for jfed
484 elif 'dl_identity' in request.POST:
485 for account_detail in account_details:
486 for platform_detail in platform_details:
487 if platform_detail['platform_id'] == account_detail['platform_id']:
488 if 'myslice' in platform_detail['platform']:
489 account_config = json.loads(account_detail['config'])
490 if 'user_private_key' in account_config:
491 private_key = account_config['user_private_key']
492 user_hrn = account_config.get('user_hrn','N/A')
493 registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
494 jfed_identity = user_hrn + '\n' + registry + '\n' + private_key
495 response = HttpResponse(jfed_identity, content_type='text/plain')
496 response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
499 messages.error(request, 'Download error: Private key is not stored in the server')
500 return HttpResponseRedirect("/portal/account/")
503 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
504 return HttpResponseRedirect("/portal/account/")
507 elif 'clear_cred' in request.POST:
508 for account_detail in account_details:
509 for platform_detail in platform_details:
510 if platform_detail['platform_id'] == account_detail['platform_id']:
511 if 'myslice' in platform_detail['platform']:
512 account_config = json.loads(account_detail['config'])
513 user_cred = account_config.get('delegated_user_credential','N/A')
514 if 'N/A' not in user_cred:
515 user_hrn = account_config.get('user_hrn','N/A')
516 user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
517 user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
518 updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
519 user_params = { 'config': updated_config}
520 manifold_update_account(request,user_id, user_params)
521 messages.success(request, 'All Credentials cleared')
522 return HttpResponseRedirect("/portal/account/")
524 messages.error(request, 'Delete error: Credentials are not stored in the server')
525 return HttpResponseRedirect("/portal/account/")
527 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
528 return HttpResponseRedirect("/portal/account/")
531 # Download delegated_user_cred
532 elif 'dl_user_cred' in request.POST:
533 if 'delegated_user_credential' in account_config:
534 user_cred = account_config['delegated_user_credential']
535 response = HttpResponse(user_cred, content_type='text/plain')
536 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
539 messages.error(request, 'Download error: User credential is not stored in the server')
540 return HttpResponseRedirect("/portal/account/")
543 elif 'dl_user_cert' in request.POST:
544 if 'user_credential' in account_config:
545 user_cred = account_config['user_credential']
546 obj_cred = Credential(string=user_cred)
547 obj_gid = obj_cred.get_gid_object()
548 str_cert = obj_gid.save_to_string()
549 response = HttpResponse(str_cert, content_type='text/plain')
550 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
553 elif 'delegated_user_credential' in account_config:
554 user_cred = account_config['delegated_user_credential']
555 obj_cred = Credential(string=user_cred)
556 obj_gid = obj_cred.get_gid_object()
557 str_cert = obj_gid.save_to_string()
558 response = HttpResponse(str_cert, content_type='text/plain')
559 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
562 messages.error(request, 'Download error: User credential is not stored in the server')
563 return HttpResponseRedirect("/portal/account/")
565 # Download user p12 = private_key + Certificate
566 elif 'dl_user_p12' in request.POST:
567 if 'user_credential' in account_config and 'user_private_key' in account_config:
568 user_cred = account_config['user_credential']
569 obj_cred = Credential(string=user_cred)
570 obj_gid = obj_cred.get_gid_object()
571 str_cert = obj_gid.save_to_string()
572 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
574 user_private_key = account_config['user_private_key'].encode('ascii')
575 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
577 p12 = crypto.PKCS12()
578 p12.set_privatekey(pkey)
579 p12.set_certificate(cert)
580 pkcs12 = p12.export()
582 response = HttpResponse(pkcs12, content_type='text/plain')
583 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
586 elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
587 user_cred = account_config['delegated_user_credential']
588 obj_cred = Credential(string=user_cred)
589 obj_gid = obj_cred.get_gid_object()
590 str_cert = obj_gid.save_to_string()
591 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
593 user_private_key = account_config['user_private_key'].encode('ascii')
594 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
596 p12 = crypto.PKCS12()
597 p12.set_privatekey(pkey)
598 p12.set_certificate(cert)
599 pkcs12 = p12.export()
601 response = HttpResponse(pkcs12, content_type='text/plain')
602 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
605 messages.error(request, 'Download error: User private key or credential is not stored in the server')
606 return HttpResponseRedirect("/portal/account/")
611 messages.info(request, 'Under Construction. Please try again later!')
612 return HttpResponseRedirect("/portal/account/")