1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from manifold.core.query import Query
4 from manifold.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 django.core.mail import send_mail
16 import json, os, re, itertools
19 class UserView(LoginRequiredAutoLogoutView):
20 template_name = "manageuserview.html"
21 def dispatch(self, *args, **kwargs):
22 return super(UserView, 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" ] )
31 for key, value in kwargs.iteritems():
32 #print "%s = %s" % (key, value)
36 user_query = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','config','email','status')
37 user_details = execute_admin_query(self.request, user_query)
39 # not always found in user_details...
41 for user_detail in user_details:
42 user_id = user_detail['user_id']
43 user_email = user_detail['email']
46 # different significations of user_status
47 if user_detail['status'] == 0:
48 user_status = 'Disabled'
49 elif user_detail['status'] == 1:
50 user_status = 'Validation Pending'
51 elif user_detail['status'] == 2:
52 user_status = 'Enabled'
55 #email = user_detail['email']
56 if user_detail['config']:
57 config = json.loads(user_detail['config'])
59 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
60 account_query = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
61 platform_details = execute_query(self.request, platform_query)
62 account_details = execute_admin_query(self.request, account_query)
64 # initial assignment needed for users having account.config = {}
70 account_reference = ''
75 principal_acc_list = ''
77 platform_name_list = []
78 platform_name_secondary_list = []
79 platform_access_list = []
80 platform_no_access_list = []
81 total_platform_list = []
82 account_type_list = []
83 account_type_secondary_list = []
84 account_reference_list = []
85 delegation_type_list = []
86 user_cred_exp_list = []
89 slice_cred_exp_list = []
90 auth_cred_exp_list = []
94 for platform_detail in platform_details:
95 if 'sfa' in platform_detail['gateway_type']:
96 total_platform = platform_detail['platform']
97 total_platform_list.append(total_platform)
99 for account_detail in account_details:
100 if platform_detail['platform_id'] == account_detail['platform_id']:
101 platform_name = platform_detail['platform']
102 account_config = json.loads(account_detail['config'])
103 account_usr_hrn = account_config.get('user_hrn','N/A')
104 account_pub_key = account_config.get('user_public_key','N/A')
105 account_reference = account_config.get ('reference_platform','N/A')
106 # credentials of myslice platform
107 if 'myslice' in platform_detail['platform']:
108 acc_user_cred = account_config.get('delegated_user_credential','N/A')
109 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
110 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
112 if 'N/A' not in acc_user_cred:
113 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
115 user_exp_date = exp_date.group(1)
116 user_cred_exp_list.append(user_exp_date)
118 my_users = [{'cred_exp': t[0]}
119 for t in zip(user_cred_exp_list)]
122 if 'N/A' not in acc_slice_cred:
123 for key, value in acc_slice_cred.iteritems():
124 slice_list.append(key)
126 exp_date = re.search('<expires>(.*)</expires>', value)
128 exp_date = exp_date.group(1)
129 slice_cred_exp_list.append(exp_date)
131 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
132 for t in zip(slice_list, slice_cred_exp_list)]
134 if 'N/A' not in acc_auth_cred:
135 for key, value in acc_auth_cred.iteritems():
136 auth_list.append(key)
138 exp_date = re.search('<expires>(.*)</expires>', value)
140 exp_date = exp_date.group(1)
141 auth_cred_exp_list.append(exp_date)
143 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
144 for t in zip(auth_list, auth_cred_exp_list)]
147 # for reference accounts
148 if 'reference' in account_detail['auth_type']:
149 account_type = 'Reference'
151 platform_name_secondary_list.append(platform_name)
152 account_type_secondary_list.append(account_type)
153 account_reference_list.append(account_reference)
154 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
155 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
157 elif 'managed' in account_detail['auth_type']:
158 account_type = 'Principal'
159 delegation = 'Automatic'
161 account_type = 'Principal'
162 delegation = 'Manual'
163 # for principal (auth_type=user/managed) accounts
164 if 'reference' not in account_detail['auth_type']:
165 platform_name_list.append(platform_name)
166 account_type_list.append(account_type)
167 delegation_type_list.append(delegation)
168 usr_hrn_list.append(account_usr_hrn)
169 pub_key_list.append(account_pub_key)
170 user_status_list.append(user_status)
171 # combining 5 lists into 1 [to render in the template]
172 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],}
173 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
174 # to hide private key row if it doesn't exist
175 if 'myslice' in platform_detail['platform']:
176 account_config = json.loads(account_detail['config'])
177 account_priv_key = account_config.get('user_private_key','N/A')
178 if 'sfa' in platform_detail['gateway_type']:
179 platform_access = platform_detail['platform']
180 platform_access_list.append(platform_access)
182 # Removing the platform which already has access
183 for platform in platform_access_list:
184 total_platform_list.remove(platform)
185 # we could use zip. this one is used if columns have unequal rows
186 platform_list = [{'platform_no_access': t[0]}
187 for t in itertools.izip_longest(total_platform_list)]
189 context = super(UserView, self).get_context_data(**kwargs)
190 context['principal_acc'] = principal_acc_list
191 context['ref_acc'] = ref_acc_list
192 context['platform_list'] = platform_list
193 context['my_users'] = my_users
194 context['my_slices'] = my_slices
195 context['my_auths'] = my_auths
196 context['user_status'] = user_status
197 context['user_email'] = user_email
198 context['firstname'] = config.get('firstname',"?")
199 context['lastname'] = config.get('lastname',"?")
200 context['fullname'] = context['firstname'] +' '+ context['lastname']
201 context['authority'] = config.get('authority',"Unknown Authority")
202 context['user_private_key'] = account_priv_key
204 # XXX This is repeated in all pages
205 # more general variables expected in the template
206 context['title'] = 'Platforms connected to MySlice'
207 # the menu items on the top
208 context['topmenu_items'] = topmenu_items_live('My Account', page)
209 # so we can sho who is logged
210 context['username'] = the_user(self.request)
211 # context ['firstname'] = config['firstname']
212 prelude_env = page.prelude_env()
213 context.update(prelude_env)
218 #my_acc form value processing
219 def user_process(request):
220 user_query = Query().get('local:user').select('user_id','email','password','config')
221 user_details = execute_query(request, user_query)
223 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
224 account_details = execute_query(request, account_query)
226 platform_query = Query().get('local:platform').select('platform_id','platform')
227 platform_details = execute_query(request, platform_query)
229 # getting the user_id from the session
230 for user_detail in user_details:
231 user_id = user_detail['user_id']
233 for account_detail in account_details:
234 for platform_detail in platform_details:
235 # Add reference account to the platforms
236 if 'add_'+platform_detail['platform'] in request.POST:
237 platform_id = platform_detail['platform_id']
238 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
239 manifold_add_account(request,user_params)
240 messages.info(request, 'Reference Account is added to the selected platform successfully!')
241 return HttpResponseRedirect("/portal/account/")
243 # Delete reference account from the platforms
244 if 'delete_'+platform_detail['platform'] in request.POST:
245 platform_id = platform_detail['platform_id']
246 user_params = {'user_id':user_id}
247 manifold_delete_account(request,platform_id,user_params)
248 messages.info(request, 'Reference Account is removed from the selected platform')
249 return HttpResponseRedirect("/portal/account/")
251 if platform_detail['platform_id'] == account_detail['platform_id']:
252 if 'myslice' in platform_detail['platform']:
253 account_config = json.loads(account_detail['config'])
254 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
255 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
260 # adding the slices and corresponding credentials to list
261 if 'N/A' not in acc_slice_cred:
264 for key, value in acc_slice_cred.iteritems():
265 slice_list.append(key)
266 slice_cred.append(value)
267 # special case: download each slice credentials separately
268 for i in range(0, len(slice_list)):
269 if 'dl_'+slice_list[i] in request.POST:
270 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
271 response = HttpResponse(slice_detail, content_type='text/plain')
272 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
275 # adding the authority and corresponding credentials to list
276 if 'N/A' not in acc_auth_cred:
279 for key, value in acc_auth_cred.iteritems():
280 auth_list.append(key)
281 auth_cred.append(value)
282 # special case: download each slice credentials separately
283 for i in range(0, len(auth_list)):
284 if 'dl_'+auth_list[i] in request.POST:
285 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
286 response = HttpResponse(auth_detail, content_type='text/plain')
287 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
292 if 'submit_name' in request.POST:
293 edited_first_name = request.POST['fname']
294 edited_last_name = request.POST['lname']
297 for user_config in user_details:
298 if user_config['config']:
299 config = json.loads(user_config['config'])
300 config['firstname'] = edited_first_name
301 config['lastname'] = edited_last_name
302 config['authority'] = config.get('authority','Unknown Authority')
303 updated_config = json.dumps(config)
304 user_params = {'config': updated_config}
305 else: # it's needed if the config is empty
306 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
307 user_params = {'config': user_config['config']}
308 # updating config local:user in manifold
309 manifold_update_user(request, request.user.email,user_params)
310 # this will be depricated, we will show the success msg in same page
311 # Redirect to same page with success message
312 messages.success(request, 'Sucess: First Name and Last Name Updated.')
313 return HttpResponseRedirect("/portal/account/")
315 elif 'submit_pass' in request.POST:
316 edited_password = request.POST['password']
318 for user_pass in user_details:
319 user_pass['password'] = edited_password
320 #updating password in local:user
321 user_params = { 'password': user_pass['password']}
322 manifold_update_user(request,request.user.email,user_params)
323 # return HttpResponse('Success: Password Changed!!')
324 messages.success(request, 'Sucess: Password Updated.')
325 return HttpResponseRedirect("/portal/account/")
327 # XXX TODO: Factorize with portal/registrationview.py
329 elif 'generate' in request.POST:
330 for account_detail in account_details:
331 for platform_detail in platform_details:
332 if platform_detail['platform_id'] == account_detail['platform_id']:
333 if 'myslice' in platform_detail['platform']:
334 from Crypto.PublicKey import RSA
335 private = RSA.generate(1024)
336 private_key = json.dumps(private.exportKey())
337 public = private.publickey()
338 public_key = json.dumps(public.exportKey(format='OpenSSH'))
339 # updating manifold local:account table
340 account_config = json.loads(account_detail['config'])
341 # preserving user_hrn
342 user_hrn = account_config.get('user_hrn','N/A')
343 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
344 updated_config = json.dumps(account_config)
346 user_params = { 'config': keypair, 'auth_type':'managed'}
347 manifold_update_account(request,user_params)
349 public_key = public_key.replace('"', '');
350 user_pub_key = {'keys': public_key}
351 sfa_update_user(request, user_hrn, user_pub_key)
352 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
353 return HttpResponseRedirect("/portal/account/")
355 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
356 return HttpResponseRedirect("/portal/account/")
358 elif 'upload_key' in request.POST:
359 for account_detail in account_details:
360 for platform_detail in platform_details:
361 if platform_detail['platform_id'] == account_detail['platform_id']:
362 if 'myslice' in platform_detail['platform']:
363 up_file = request.FILES['pubkey']
364 file_content = up_file.read()
365 file_name = up_file.name
366 file_extension = os.path.splitext(file_name)[1]
367 allowed_extension = ['.pub','.txt']
368 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
369 account_config = json.loads(account_detail['config'])
370 # preserving user_hrn
371 user_hrn = account_config.get('user_hrn','N/A')
372 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
373 #file_content = re.sub("\r", "", file_content)
374 #file_content = re.sub("\n", "\\n",file_content)
375 file_content = ''.join(file_content.split())
376 #update manifold local:account table
377 user_params = { 'config': file_content, 'auth_type':'user'}
378 manifold_update_account(request,user_params)
380 user_pub_key = {'keys': file_content}
381 sfa_update_user(request, user_hrn, user_pub_key)
382 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
383 return HttpResponseRedirect("/portal/account/")
385 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
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 'dl_pubkey' 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 account_config = json.loads(account_detail['config'])
397 public_key = account_config['user_public_key']
398 response = HttpResponse(public_key, content_type='text/plain')
399 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
403 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
404 return HttpResponseRedirect("/portal/account/")
406 elif 'dl_pkey' in request.POST:
407 for account_detail in account_details:
408 for platform_detail in platform_details:
409 if platform_detail['platform_id'] == account_detail['platform_id']:
410 if 'myslice' in platform_detail['platform']:
411 account_config = json.loads(account_detail['config'])
412 if 'user_private_key' in account_config:
413 private_key = account_config['user_private_key']
414 response = HttpResponse(private_key, content_type='text/plain')
415 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
418 messages.error(request, 'Download error: Private key is not stored in the server')
419 return HttpResponseRedirect("/portal/account/")
422 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
423 return HttpResponseRedirect("/portal/account/")
425 elif 'delete' in request.POST:
426 for account_detail in account_details:
427 for platform_detail in platform_details:
428 if platform_detail['platform_id'] == account_detail['platform_id']:
429 if 'myslice' in platform_detail['platform']:
430 account_config = json.loads(account_detail['config'])
431 if 'user_private_key' in account_config:
432 for key in account_config.keys():
433 if key == 'user_private_key':
434 del account_config[key]
436 updated_config = json.dumps(account_config)
437 user_params = { 'config': updated_config, 'auth_type':'user'}
438 manifold_update_account(request,user_params)
439 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
440 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
441 return HttpResponseRedirect("/portal/account/")
443 messages.error(request, 'Delete error: Private key is not stored in the server')
444 return HttpResponseRedirect("/portal/account/")
447 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
448 return HttpResponseRedirect("/portal/account/")
451 elif 'clear_cred' in request.POST:
452 for account_detail in account_details:
453 for platform_detail in platform_details:
454 if platform_detail['platform_id'] == account_detail['platform_id']:
455 if 'myslice' in platform_detail['platform']:
456 account_config = json.loads(account_detail['config'])
457 user_cred = account_config.get('delegated_user_credential','N/A')
458 if 'N/A' not in user_cred:
459 user_hrn = account_config.get('user_hrn','N/A')
460 user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
461 user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
462 updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
463 user_params = { 'config': updated_config}
464 manifold_update_account(request,user_params)
465 messages.success(request, 'All Credentials cleared')
466 return HttpResponseRedirect("/portal/account/")
468 messages.error(request, 'Delete error: Credentials are not stored in the server')
469 return HttpResponseRedirect("/portal/account/")
471 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
472 return HttpResponseRedirect("/portal/account/")
475 # Download delegated_user_cred
476 elif 'dl_user_cred' in request.POST:
477 if 'delegated_user_credential' in account_config:
478 user_cred = account_config['delegated_user_credential']
479 response = HttpResponse(user_cred, content_type='text/plain')
480 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
483 messages.error(request, 'Download error: User credential is not stored in the server')
484 return HttpResponseRedirect("/portal/account/")
487 messages.info(request, 'Under Construction. Please try again later!')
488 return HttpResponseRedirect("/portal/account/")