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