1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from manifold.core.query import Query
4 from manifold.manifoldapi import execute_query
5 from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account
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 django.core.mail import send_mail
16 import json, os, re, itertools
19 class AccountView(LoginRequiredAutoLogoutView):
20 template_name = "account-view.html"
21 def dispatch(self, *args, **kwargs):
22 return super(AccountView, self).dispatch(*args, **kwargs)
25 def get_context_data(self, **kwargs):
27 page = Page(self.request)
28 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
29 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
32 user_query = Query().get('local:user').select('config','email')
33 user_details = execute_query(self.request, user_query)
35 # not always found in user_details...
37 for user_detail in user_details:
38 #email = user_detail['email']
39 if user_detail['config']:
40 config = json.loads(user_detail['config'])
42 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
43 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
44 platform_details = execute_query(self.request, platform_query)
45 account_details = execute_query(self.request, account_query)
47 # initial assignment needed for users having account.config = {}
53 account_reference = ''
58 principal_acc_list = ''
59 platform_name_list = []
60 platform_name_secondary_list = []
61 platform_access_list = []
62 platform_no_access_list = []
63 total_platform_list = []
64 account_type_list = []
65 account_type_secondary_list = []
66 account_reference_list = []
67 delegation_type_list = []
68 user_cred_exp_list = []
71 slice_cred_exp_list = []
72 auth_cred_exp_list = []
76 for platform_detail in platform_details:
77 if 'sfa' in platform_detail['gateway_type'] and platform_detail['disabled']==0:
78 total_platform = platform_detail['platform']
79 total_platform_list.append(total_platform)
81 for account_detail in account_details:
82 if platform_detail['platform_id'] == account_detail['platform_id']:
83 platform_name = platform_detail['platform']
84 account_config = json.loads(account_detail['config'])
85 account_usr_hrn = account_config.get('user_hrn','N/A')
86 account_pub_key = account_config.get('user_public_key','N/A')
87 account_reference = account_config.get ('reference_platform','N/A')
89 acc_user_cred = account_config.get('delegated_user_credential','N/A')
90 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
91 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
93 if 'N/A' not in acc_user_cred:
94 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
96 user_exp_date = exp_date.group(1)
97 user_cred_exp_list.append(user_exp_date)
99 my_users = [{'cred_exp': t[0]}
100 for t in zip(user_cred_exp_list)]
103 if 'N/A' not in acc_slice_cred:
104 for key, value in acc_slice_cred.iteritems():
105 slice_list.append(key)
107 exp_date = re.search('<expires>(.*)</expires>', value)
109 exp_date = exp_date.group(1)
110 slice_cred_exp_list.append(exp_date)
112 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
113 for t in zip(slice_list, slice_cred_exp_list)]
115 if 'N/A' not in acc_auth_cred:
116 for key, value in acc_auth_cred.iteritems():
117 auth_list.append(key)
119 exp_date = re.search('<expires>(.*)</expires>', value)
121 exp_date = exp_date.group(1)
122 auth_cred_exp_list.append(exp_date)
124 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
125 for t in zip(auth_list, auth_cred_exp_list)]
128 # for reference accounts
129 if 'reference' in account_detail['auth_type']:
130 account_type = 'Reference'
132 platform_name_secondary_list.append(platform_name)
133 account_type_secondary_list.append(account_type)
134 account_reference_list.append(account_reference)
135 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
136 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
138 elif 'managed' in account_detail['auth_type']:
139 account_type = 'Principal'
140 delegation = 'Automatic'
142 account_type = 'Principal'
143 delegation = 'Manual'
144 # for principal (auth_type=user/managed) accounts
145 if 'reference' not in account_detail['auth_type']:
146 platform_name_list.append(platform_name)
147 account_type_list.append(account_type)
148 delegation_type_list.append(delegation)
149 usr_hrn_list.append(account_usr_hrn)
150 pub_key_list.append(account_pub_key)
151 # combining 5 lists into 1 [to render in the template]
152 principal_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'usr_hrn':t[3], 'usr_pubkey':t[4]}
153 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list)]
154 # to hide private key row if it doesn't exist
155 if 'myslice' in platform_detail['platform']:
156 account_config = json.loads(account_detail['config'])
157 account_priv_key = account_config.get('user_private_key','N/A')
158 if 'sfa' in platform_detail['gateway_type']:
159 platform_access = platform_detail['platform']
160 platform_access_list.append(platform_access)
162 # Removing the platform which already has access
163 for platform in platform_access_list:
164 total_platform_list.remove(platform)
165 # we could use zip. this one is used if columns have unequal rows
166 platform_list = [{'platform_no_access': t[0]}
167 for t in itertools.izip_longest(total_platform_list)]
169 context = super(AccountView, self).get_context_data(**kwargs)
170 context['principal_acc'] = principal_acc_list
171 context['ref_acc'] = ref_acc_list
172 context['platform_list'] = platform_list
173 context['my_users'] = my_users
174 context['my_slices'] = my_slices
175 context['my_auths'] = my_auths
176 context['person'] = self.request.user
177 context['firstname'] = config.get('firstname',"?")
178 context['lastname'] = config.get('lastname',"?")
179 context['fullname'] = context['firstname'] +' '+ context['lastname']
180 context['authority'] = config.get('authority',"Unknown Authority")
181 context['user_private_key'] = account_priv_key
183 # XXX This is repeated in all pages
184 # more general variables expected in the template
185 context['title'] = 'Platforms connected to MySlice'
186 # the menu items on the top
187 context['topmenu_items'] = topmenu_items_live('My Account', page)
188 # so we can sho who is logged
189 context['username'] = the_user(self.request)
190 # context ['firstname'] = config['firstname']
191 prelude_env = page.prelude_env()
192 context.update(prelude_env)
197 #my_acc form value processing
198 def account_process(request):
199 user_query = Query().get('local:user').select('user_id','email','password','config')
200 user_details = execute_query(request, user_query)
202 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
203 account_details = execute_query(request, account_query)
205 platform_query = Query().get('local:platform').select('platform_id','platform')
206 platform_details = execute_query(request, platform_query)
208 # getting the user_id from the session
209 for user_detail in user_details:
210 user_id = user_detail['user_id']
212 for account_detail in account_details:
213 for platform_detail in platform_details:
214 # Add reference account to the platforms
215 if 'add_'+platform_detail['platform'] in request.POST:
216 platform_id = platform_detail['platform_id']
217 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
218 manifold_add_account(request,user_params)
219 messages.info(request, 'Reference Account is added to the selected platform successfully!')
220 return HttpResponseRedirect("/portal/account/")
222 # Delete reference account from the platforms
223 if 'delete_'+platform_detail['platform'] in request.POST:
224 platform_id = platform_detail['platform_id']
225 user_params = {'user_id':user_id}
226 manifold_delete_account(request,platform_id,user_params)
227 messages.info(request, 'Reference Account is removed from the selected platform')
228 return HttpResponseRedirect("/portal/account/")
230 if platform_detail['platform_id'] == account_detail['platform_id']:
231 if 'myslice' in platform_detail['platform']:
232 account_config = json.loads(account_detail['config'])
233 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
234 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
239 # adding the slices and corresponding credentials to list
240 if 'N/A' not in acc_slice_cred:
243 for key, value in acc_slice_cred.iteritems():
244 slice_list.append(key)
245 slice_cred.append(value)
246 # special case: download each slice credentials separately
247 for i in range(0, len(slice_list)):
248 if 'dl_'+slice_list[i] in request.POST:
249 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
250 response = HttpResponse(slice_detail, content_type='text/plain')
251 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
254 # adding the authority and corresponding credentials to list
255 if 'N/A' not in acc_auth_cred:
258 for key, value in acc_auth_cred.iteritems():
259 auth_list.append(key)
260 auth_cred.append(value)
261 # special case: download each slice credentials separately
262 for i in range(0, len(auth_list)):
263 if 'dl_'+auth_list[i] in request.POST:
264 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
265 response = HttpResponse(auth_detail, content_type='text/plain')
266 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
271 if 'submit_name' in request.POST:
272 edited_first_name = request.POST['fname']
273 edited_last_name = request.POST['lname']
276 for user_config in user_details:
277 if user_config['config']:
278 config = json.loads(user_config['config'])
279 config['firstname'] = edited_first_name
280 config['lastname'] = edited_last_name
281 config['authority'] = config.get('authority','Unknown Authority')
282 updated_config = json.dumps(config)
283 user_params = {'config': updated_config}
284 else: # it's needed if the config is empty
285 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
286 user_params = {'config': user_config['config']}
287 # updating config local:user in manifold
288 manifold_update_user(request,user_params)
289 # this will be depricated, we will show the success msg in same page
290 # Redirect to same page with success message
291 messages.success(request, 'Sucess: First Name and Last Name Updated.')
292 return HttpResponseRedirect("/portal/account/")
294 elif 'submit_pass' in request.POST:
295 edited_password = request.POST['password']
297 for user_pass in user_details:
298 user_pass['password'] = edited_password
299 #updating password in local:user
300 user_params = { 'password': user_pass['password']}
301 manifold_update_user(request,user_params)
302 # return HttpResponse('Success: Password Changed!!')
303 messages.success(request, 'Sucess: Password Updated.')
304 return HttpResponseRedirect("/portal/account/")
306 # XXX TODO: Factorize with portal/registrationview.py
308 elif 'generate' in request.POST:
309 for account_detail in account_details:
310 for platform_detail in platform_details:
311 if platform_detail['platform_id'] == account_detail['platform_id']:
312 if 'myslice' in platform_detail['platform']:
313 from Crypto.PublicKey import RSA
314 private = RSA.generate(1024)
315 private_key = json.dumps(private.exportKey())
316 public = private.publickey()
317 public_key = json.dumps(public.exportKey(format='OpenSSH'))
318 # updating maniolf local:account table
319 account_config = json.loads(account_detail['config'])
320 # preserving user_hrn
321 user_hrn = account_config.get('user_hrn','N/A')
322 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
323 updated_config = json.dumps(account_config)
325 user_params = { 'config': keypair, 'auth_type':'managed'}
326 manifold_update_account(request,user_params)
327 messages.success(request, 'Sucess: New Keypair Generated!')
328 return HttpResponseRedirect("/portal/account/")
330 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
331 return HttpResponseRedirect("/portal/account/")
333 elif 'upload_key' in request.POST:
334 for account_detail in account_details:
335 for platform_detail in platform_details:
336 if platform_detail['platform_id'] == account_detail['platform_id']:
337 if 'myslice' in platform_detail['platform']:
338 up_file = request.FILES['pubkey']
339 file_content = up_file.read()
340 file_name = up_file.name
341 file_extension = os.path.splitext(file_name)[1]
342 allowed_extension = ['.pub','.txt']
343 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
344 account_config = json.loads(account_detail['config'])
345 # preserving user_hrn
346 user_hrn = account_config.get('user_hrn','N/A')
347 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
348 #file_content = re.sub("\r", "", file_content)
349 #file_content = re.sub("\n", "\\n",file_content)
350 file_content = ''.join(file_content.split())
351 #update manifold local:account table
352 user_params = { 'config': file_content, 'auth_type':'user'}
353 manifold_update_account(request,user_params)
354 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
355 return HttpResponseRedirect("/portal/account/")
357 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
358 return HttpResponseRedirect("/portal/account/")
360 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
361 return HttpResponseRedirect("/portal/account/")
363 elif 'dl_pubkey' in request.POST:
364 for account_detail in account_details:
365 for platform_detail in platform_details:
366 if platform_detail['platform_id'] == account_detail['platform_id']:
367 if 'myslice' in platform_detail['platform']:
368 account_config = json.loads(account_detail['config'])
369 public_key = account_config['user_public_key']
370 response = HttpResponse(public_key, content_type='text/plain')
371 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
375 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
376 return HttpResponseRedirect("/portal/account/")
378 elif 'dl_pkey' in request.POST:
379 for account_detail in account_details:
380 for platform_detail in platform_details:
381 if platform_detail['platform_id'] == account_detail['platform_id']:
382 if 'myslice' in platform_detail['platform']:
383 account_config = json.loads(account_detail['config'])
384 if 'user_private_key' in account_config:
385 private_key = account_config['user_private_key']
386 response = HttpResponse(private_key, content_type='text/plain')
387 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
390 messages.error(request, 'Download error: Private key is not stored in the server')
391 return HttpResponseRedirect("/portal/account/")
394 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
395 return HttpResponseRedirect("/portal/account/")
397 elif 'delete' in request.POST:
398 for account_detail in account_details:
399 for platform_detail in platform_details:
400 if platform_detail['platform_id'] == account_detail['platform_id']:
401 if 'myslice' in platform_detail['platform']:
402 account_config = json.loads(account_detail['config'])
403 if 'user_private_key' in account_config:
404 for key in account_config.keys():
405 if key == 'user_private_key':
406 del account_config[key]
408 updated_config = json.dumps(account_config)
409 user_params = { 'config': updated_config, 'auth_type':'user'}
410 manifold_update_account(request,user_params)
411 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
412 return HttpResponseRedirect("/portal/account/")
414 messages.error(request, 'Delete error: Private key is not stored in the server')
415 return HttpResponseRedirect("/portal/account/")
418 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
419 return HttpResponseRedirect("/portal/account/")
422 elif 'clear_cred' in request.POST:
423 for account_detail in account_details:
424 for platform_detail in platform_details:
425 if platform_detail['platform_id'] == account_detail['platform_id']:
426 if 'myslice' in platform_detail['platform']:
427 account_config = json.loads(account_detail['config'])
428 user_cred = account_config.get('delegated_user_credential','N/A')
429 if 'N/A' not in user_cred:
430 user_hrn = account_config.get('user_hrn','N/A')
431 user_pub_key = account_config.get('user_public_key','N/A')
432 user_priv_key = account_config.get('user_private_key','N/A')
433 updated_config = '{"user_public_key":"'+ user_pub_key + '", "user_private_key":"'+ user_priv_key + '", "user_hrn":"'+ user_hrn + '"}'
434 updated_config = ''.join(updated_config.split())
435 user_params = { 'config': updated_config}
436 manifold_update_account(request,user_params)
437 messages.success(request, 'All Credentials cleared')
438 return HttpResponseRedirect("/portal/account/")
440 messages.error(request, 'Delete error: Credentials are not stored in the server')
441 return HttpResponseRedirect("/portal/account/")
443 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
444 return HttpResponseRedirect("/portal/account/")
447 # Download delegated_user_cred
448 elif 'dl_user_cred' in request.POST:
449 if 'delegated_user_credential' in account_config:
450 user_cred = account_config['delegated_user_credential']
451 response = HttpResponse(user_cred, content_type='text/plain')
452 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
455 messages.error(request, 'Download error: User credential is not stored in the server')
456 return HttpResponseRedirect("/portal/account/")
459 messages.info(request, 'Under Construction. Please try again later!')
460 return HttpResponseRedirect("/portal/account/")