Merge branch 'fibre' of ssh://git.onelab.eu/git/myslice into fibre
[unfold.git] / portal / accountview.py
index ce504ac..5048383 100644 (file)
@@ -1,8 +1,11 @@
 from unfold.loginrequired               import LoginRequiredAutoLogoutView
 #
+from sfa.trust.credential               import Credential
+from sfa.trust.certificate              import Keypair
+#
 from manifold.core.query                import Query
-from manifold.manifoldapi               import execute_query
-from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user
+from manifoldapi.manifoldapi            import execute_query
+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
 #
 from unfold.page                        import Page    
 from ui.topmenu                         import topmenu_items_live, the_user
@@ -10,12 +13,13 @@ from ui.topmenu                         import topmenu_items_live, the_user
 from django.http                        import HttpResponse, HttpResponseRedirect
 from django.contrib                     import messages
 from django.contrib.auth.decorators     import login_required
-from django.core.mail                   import send_mail
 
-from theme import ThemeView
+from myslice.theme import ThemeView
 
 #
 import json, os, re, itertools
+from OpenSSL import crypto
+from Crypto.PublicKey import RSA
 
 # requires login
 class AccountView(LoginRequiredAutoLogoutView, ThemeView):
@@ -25,11 +29,13 @@ class AccountView(LoginRequiredAutoLogoutView, ThemeView):
 
 
     def get_context_data(self, **kwargs):
-
+        self.template_name = self.template
         page = Page(self.request)
-        page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
-        page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
+        metadata = page.get_metadata()
+        page.expose_js_metadata()
 
+        page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js","js/jquery-ui.js" ] )
+        page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
 
         user_query  = Query().get('local:user').select('config','email','status')
         user_details = execute_query(self.request, user_query)
@@ -93,10 +99,11 @@ class AccountView(LoginRequiredAutoLogoutView, ThemeView):
             for account_detail in account_details:
                 if platform_detail['platform_id'] == account_detail['platform_id']:
                     platform_name = platform_detail['platform']
-                    account_config = json.loads(account_detail['config'])
-                    account_usr_hrn = account_config.get('user_hrn','N/A')
-                    account_pub_key = account_config.get('user_public_key','N/A')
-                    account_reference = account_config.get ('reference_platform','N/A')
+                    if 'config' in account_detail and account_detail['config'] is not '':
+                        account_config = json.loads(account_detail['config'])
+                        account_usr_hrn = account_config.get('user_hrn','N/A')
+                        account_pub_key = account_config.get('user_public_key','N/A')
+                        account_reference = account_config.get ('reference_platform','N/A')
                     # credentials of myslice platform
                     if 'myslice' in platform_detail['platform']:
                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
@@ -180,11 +187,38 @@ class AccountView(LoginRequiredAutoLogoutView, ThemeView):
         platform_list = [{'platform_no_access': t[0]}
             for t in itertools.izip_longest(total_platform_list)]
 
+
+        ## check user is pi or not
+      #  platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
+      #  account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
+      #  platform_details = execute_query(self.request, platform_query)
+      #  account_details = execute_query(self.request, account_query)
+      #  for platform_detail in platform_details:
+      #      for account_detail in account_details:
+      #          if platform_detail['platform_id'] == account_detail['platform_id']:
+      #              if 'config' in account_detail and account_detail['config'] is not '':
+      #                  account_config = json.loads(account_detail['config'])
+      #                  if 'myslice' in platform_detail['platform']:
+      #                      acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
+        # assigning values
+        if acc_auth_cred == {} or acc_auth_cred == 'N/A':
+            pi = "is_not_pi"
+        else:
+            pi = "is_pi"
+
+        # check if the user has creds or not
+        if acc_user_cred == {} or acc_user_cred == 'N/A':
+            user_cred = 'no_creds'
+        else:
+            user_cred = 'has_creds'
+
         context = super(AccountView, self).get_context_data(**kwargs)
         context['principal_acc'] = principal_acc_list
         context['ref_acc'] = ref_acc_list
         context['platform_list'] = platform_list
         context['my_users'] = my_users
+        context['pi'] = pi
+        context['user_cred'] = user_cred
         context['my_slices'] = my_slices
         context['my_auths'] = my_auths
         context['user_status'] = user_status
@@ -203,6 +237,7 @@ class AccountView(LoginRequiredAutoLogoutView, ThemeView):
         # so we can sho who is logged
         context['username'] = the_user(self.request)
         context['theme'] = self.theme
+        context['section'] = "User account"
 #        context ['firstname'] = config['firstname']
         prelude_env = page.prelude_env()
         context.update(prelude_env)
@@ -224,6 +259,7 @@ def account_process(request):
     # getting the user_id from the session
     for user_detail in user_details:
             user_id = user_detail['user_id']
+            user_email = user_detail['email']
 
     for account_detail in account_details:
         for platform_detail in platform_details:
@@ -320,13 +356,14 @@ def account_process(request):
         return HttpResponseRedirect("/portal/account/")
 
 # XXX TODO: Factorize with portal/registrationview.py
+# XXX TODO: Factorize with portal/registrationview.py
+# XXX TODO: Factorize with portal/joinview.py
 
     elif 'generate' in request.POST:
         for account_detail in account_details:
             for platform_detail in platform_details:
                 if platform_detail['platform_id'] == account_detail['platform_id']:
                     if 'myslice' in platform_detail['platform']:
-                        from Crypto.PublicKey import RSA
                         private = RSA.generate(1024)
                         private_key = json.dumps(private.exportKey())
                         public  = private.publickey()
@@ -336,15 +373,28 @@ def account_process(request):
                         # preserving user_hrn
                         user_hrn = account_config.get('user_hrn','N/A')
                         keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
-                        updated_config = json.dumps(account_config) 
+                        #updated_config = json.dumps(account_config) 
                         # updating manifold
-                        user_params = { 'config': keypair, 'auth_type':'managed'}
-                        manifold_update_account(request, user_id, user_params)
+                        #user_params = { 'config': keypair, 'auth_type':'managed'}
+                        #manifold_update_account(request, user_id, user_params)
                         # updating sfa
                         public_key = public_key.replace('"', '');
                         user_pub_key = {'keys': public_key}
+                        #sfa_update_user(request, user_hrn, user_pub_key)
                         sfa_update_user(request, user_hrn, user_pub_key)
-                        messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
+                        result_sfa_user = sfa_get_user(request, user_hrn, public_key)
+                        try:
+                            result_sfa_user = result_sfa_user[0]
+                            if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
+                                # updating manifold
+                                updated_config = json.dumps(account_config) 
+                                user_params = { 'config': keypair, 'auth_type':'managed'}
+                                manifold_update_account(request, user_id, user_params)
+                                messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
+                            else:
+                                raise Exception,"Keys are not matching"
+                        except Exception,e:
+                            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.')
                         return HttpResponseRedirect("/portal/account/")
         else:
             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
@@ -441,31 +491,42 @@ def account_process(request):
         else:
             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
             return HttpResponseRedirect("/portal/account/")
-
-    #clear all creds
-    elif 'clear_cred' in request.POST:
+    
+    # download identity for jfed
+    elif 'dl_identity' in request.POST:
         for account_detail in account_details:
             for platform_detail in platform_details:
                 if platform_detail['platform_id'] == account_detail['platform_id']:
                     if 'myslice' in platform_detail['platform']:
                         account_config = json.loads(account_detail['config'])
-                        user_cred = account_config.get('delegated_user_credential','N/A')
-                        if 'N/A' not in user_cred:
+                        if 'user_private_key' in account_config:
+                            private_key = account_config['user_private_key']
                             user_hrn = account_config.get('user_hrn','N/A')
-                            user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
-                            user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
-                            updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
-                            user_params = { 'config': updated_config}
-                            manifold_update_account(request,user_id, user_params)
-                            messages.success(request, 'All Credentials cleared')
-                            return HttpResponseRedirect("/portal/account/")
+                            registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
+                            jfed_identity = user_hrn + '\n' + registry + '\n' + private_key 
+                            response = HttpResponse(jfed_identity, content_type='text/plain')
+                            response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
+                            return response
                         else:
-                            messages.error(request, 'Delete error: Credentials are not stored in the server')
+                            messages.error(request, 'Download error: Private key is not stored in the server')
                             return HttpResponseRedirect("/portal/account/")
+
         else:
             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
             return HttpResponseRedirect("/portal/account/")
 
+    #clear all creds
+    elif 'clear_cred' in request.POST:
+        try:
+            result = clear_user_creds(request, user_email)
+            if result is not None: 
+                messages.success(request, 'All Credentials cleared')
+            else:
+                messages.error(request, 'Delete error: Credentials are not stored in the server')
+        except Exception,e:
+            print "Exception in accountview.py in clear_user_creds %s" % e
+            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
+        return HttpResponseRedirect("/portal/account/")
 
     # Download delegated_user_cred
     elif 'dl_user_cred' in request.POST:
@@ -475,9 +536,77 @@ def account_process(request):
             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
             return response
         else:
-            messages.error(request, 'Download error: User credential  is not stored in the server')
+            messages.error(request, 'Download error: User credential is not stored in the server')
             return HttpResponseRedirect("/portal/account/")
-        
+
+    # Download user_cert
+    elif 'dl_user_cert' in request.POST:
+        if 'user_credential' in account_config:
+            user_cred = account_config['user_credential']
+            obj_cred = Credential(string=user_cred)
+            obj_gid = obj_cred.get_gid_object()
+            str_cert = obj_gid.save_to_string()
+            response = HttpResponse(str_cert, content_type='text/plain')
+            response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
+            return response
+
+        elif 'delegated_user_credential' in account_config:
+            user_cred = account_config['delegated_user_credential']
+            obj_cred = Credential(string=user_cred)
+            obj_gid = obj_cred.get_gid_object()
+            str_cert = obj_gid.save_to_string()
+            response = HttpResponse(str_cert, content_type='text/plain')
+            response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
+            return response
+        else:
+            messages.error(request, 'Download error: User credential is not stored in the server')
+            return HttpResponseRedirect("/portal/account/")
+
+    # Download user p12 = private_key + Certificate
+    elif 'dl_user_p12' in request.POST:
+        if 'user_credential' in account_config and 'user_private_key' in account_config:
+            user_cred = account_config['user_credential']
+            obj_cred = Credential(string=user_cred)
+            obj_gid = obj_cred.get_gid_object()
+            str_cert = obj_gid.save_to_string()
+            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
+
+            user_private_key = account_config['user_private_key'].encode('ascii')
+            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
+
+            p12 = crypto.PKCS12()
+            p12.set_privatekey(pkey)
+            p12.set_certificate(cert)       
+            pkcs12 = p12.export()
+
+            response = HttpResponse(pkcs12, content_type='text/plain')
+            response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
+            return response
+
+        elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
+            user_cred = account_config['delegated_user_credential']
+            obj_cred = Credential(string=user_cred)
+            obj_gid = obj_cred.get_gid_object()
+            str_cert = obj_gid.save_to_string()
+            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
+
+            user_private_key = account_config['user_private_key'].encode('ascii')
+            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
+
+            p12 = crypto.PKCS12()
+            p12.set_privatekey(pkey)
+            p12.set_certificate(cert)       
+            pkcs12 = p12.export()
+
+            response = HttpResponse(pkcs12, content_type='text/plain')
+            response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
+            return response
+        else:
+            messages.error(request, 'Download error: User private key or credential is not stored in the server')
+            return HttpResponseRedirect("/portal/account/")
+
+
+
     else:
         messages.info(request, 'Under Construction. Please try again later!')
         return HttpResponseRedirect("/portal/account/")