Beispiel #1
0
    def delegate_cred(self, object_cred, hrn, type='authority'):

        # the gid and hrn of the object we are delegating
        if isinstance(object_cred, str):  # XXX Yes here we give a string...
            object_cred = Credential(string=object_cred)
        object_gid = object_cred.get_gid_object()
        object_hrn = object_gid.get_hrn()

        if not object_cred.get_privileges().get_all_delegate():
            self.logger.error(
                "Object credential %s does not have delegate bit set" %
                object_hrn)
            return

        # the delegating user's gid # XXX done in bootstrap
        caller_gidfile = self.my_gid  # already a string # XXX ERROR tell thierry

        # the gid of the user who will be delegated to
        delegee_gid = self.bootstrap.gid(
            hrn, 'user')  # XXX bootstrap ERROR tell thierry
        delegee_hrn = GID(delegee_gid).get_hrn()
        # XXX pkey done in bootstrap
        dcred = object_cred.delegate(delegee_gid, self.private_key,
                                     caller_gidfile)
        return dcred.save_to_string(save_parents=True)
Beispiel #2
0
    def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
        """
        sign a delegation credential to someone else

        original_credential : typically one's user- or slice- credential to be delegated to s/b else
        to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
        to_type : goes with to_hrn, usually 'user' or 'authority'

        returns a string with the delegated credential

        this internally uses self.my_gid()
        it also retrieves the gid for to_hrn/to_type
        and uses Credential.delegate()"""

        # the gid and hrn of the object we are delegating
        if isinstance (original_credential, str):
            original_credential = Credential (string=original_credential)
        original_gid = original_credential.get_gid_object()
        original_hrn = original_gid.get_hrn()

        if not original_credential.get_privileges().get_all_delegate():
            self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
            return

        # the delegating user's gid
        my_gid = self.my_gid()

        # retrieve the GID for the entity that we're delegating to
        to_gidfile = self.gid (to_hrn,to_type)
#        to_gid = GID ( to_gidfile )
#        to_hrn = delegee_gid.get_hrn()
#        print 'to_hrn',to_hrn
        delegated_credential = original_credential.delegate(to_gidfile, self.private_key(), my_gid)
        return delegated_credential.save_to_string(save_parents=True)
Beispiel #3
0
    def delegate_cred(self, object_cred, hrn):
        # the gid and hrn of the object we are delegating
        if isinstance(object_cred, str):
            object_cred = Credential(string=object_cred) 
        object_gid = object_cred.get_gid_object()
        object_hrn = object_gid.get_hrn()
    
        if not object_cred.get_privileges().get_all_delegate():
            self.logger.error("Object credential %s does not have delegate bit set"%object_hrn)
            return

        # the delegating user's gid
        caller_gid = self._get_gid(self.user)
        caller_gidfile = os.path.join(self.options.sfi_dir, self.user + ".gid")
  
        # the gid of the user who will be delegated to
        delegee_gid = self._get_gid(hrn)
        delegee_hrn = delegee_gid.get_hrn()
        delegee_gidfile = os.path.join(self.options.sfi_dir, delegee_hrn + ".gid")
        delegee_gid.save_to_file(filename=delegee_gidfile)
        dcred = object_cred.delegate(delegee_gidfile, self.get_key_file(), caller_gidfile)
        return dcred.save_to_string(save_parents=True)
    def delegate_credential_string(self,
                                   original_credential,
                                   to_hrn,
                                   to_type='authority'):
        """
        sign a delegation credential to someone else

        original_credential : typically one's user- or slice- credential to be delegated to s/b else
        to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
        to_type : goes with to_hrn, usually 'user' or 'authority'

        returns a string with the delegated credential

        this internally uses self.my_gid()
        it also retrieves the gid for to_hrn/to_type
        and uses Credential.delegate()"""

        # the gid and hrn of the object we are delegating
        if isinstance(original_credential, str):
            original_credential = Credential(string=original_credential)
        original_gid = original_credential.get_gid_object()
        original_hrn = original_gid.get_hrn()

        if not original_credential.get_privileges().get_all_delegate():
            #self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
            return

        # the delegating user's gid
        my_gid = self.my_gid()

        # retrieve the GID for the entity that we're delegating to
        to_gidfile = self.gid(to_hrn, to_type)
        #        to_gid = GID ( to_gidfile )
        #        to_hrn = delegee_gid.get_hrn()
        #        print 'to_hrn',to_hrn
        delegated_credential = original_credential.delegate(
            to_gidfile, self.private_key(), my_gid)
        return delegated_credential.save_to_string(save_parents=True)
Beispiel #5
0
    def delegate(self, opts, args):

        delegee_hrn = args[0]
        if opts.delegate_user:
            user_cred = self.get_user_cred()
            cred = self.delegate_cred(user_cred, delegee_hrn)
        elif opts.delegate_slice:
            slice_cred = self.get_slice_cred(opts.delegate_slice)
            cred = self.delegate_cred(slice_cred, delegee_hrn)
        else:
            self.logger.warning("Must specify either --user or --slice <hrn>")
            return
        delegated_cred = Credential(string=cred)
        object_hrn = delegated_cred.get_gid_object().get_hrn()
        if opts.delegate_user:
            dest_fn = os.path.join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_"
                                  + get_leaf(object_hrn) + ".cred")
        elif opts.delegate_slice:
            dest_fn = os.path.join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_slice_"
                                  + get_leaf(object_hrn) + ".cred")

        delegated_cred.save_to_file(dest_fn, save_parents=True)

        self.logger.info("delegated credential for %s to %s and wrote to %s"%(object_hrn, delegee_hrn,dest_fn))
Beispiel #6
0
    def process_params(params, filters, user):

        # PARAMS
        # added by Loic, based on the process_filters functions
        user_params = params.get('user')
        if user_params:
            del params['user']
            #print "user_params=",user_params
            ret = db.query(User.user_id)
            ret = ret.filter(User.email == user_params)
            ret = ret.one()
            params['user_id'] = ret[0]

        platform_params = params.get('platform')
        if platform_params:
            del params['platform']
            #print "platform_params=", platform_params
            ret = db.query(Platform.platform_id)
            ret = ret.filter(Platform.platform == platform_params)
            ret = ret.one()
            params['platform_id'] = ret[0]

        # JSON ENCODED FIELDS are constructed into the json_fields variable
        given = set(params.keys())
        accepted = set([c.name for c in Account.__table__.columns])
        given_json_fields = given - accepted

        if given_json_fields:
            if 'config' in given_json_fields:
                raise Exception, "Cannot mix full JSON specification & JSON encoded fields"

            r = db.query(Account.config)
            for filter in filters:
                r = r.filter(filter)
            if user:
                r = r.filter(Account.user_id == user['user_id'])
            #r = r.filter(filters) #Account.platform_id == platform_id)
            r = r.one()
            try:
                json_fields = json.loads(r.config)
            except Exception, e:
                json_fields = {}

            # We First look at convenience fields
            for field in given_json_fields:
                if field == 'credential':
                    # We'll determine the type of credential
                    # XXX NOTE This is SFA specific... it should be hooked by gateways
                    # @loic modified according to the SFA Gateway, to handle delegation
                    # XXX TODO need to be improved...
                    c = Credential(string=params[field])
                    c_type = c.get_gid_object().get_type()
                    if c_type == 'user':
                        new_field = 'delegated_%s_credential' % c_type
                        json_fields[new_field] = params[field]
                    else:
                        cred_name = 'delegated_%s_credentials' % c_type
                        if not cred_name in json_fields:
                            json_fields[cred_name] = {}
                        c_target = c.get_gid_object().get_hrn()
                        json_fields[cred_name][c_target] = params[field]
                else:
                    json_fields[field] = params[field]
                del params[field]

            params['config'] = json.dumps(json_fields)
Beispiel #7
0
Datei: auth.py Projekt: tubav/sfa
class Auth:
    """
    Credential based authentication
    """

    def __init__(self, peer_cert = None, config = None ):
        self.peer_cert = peer_cert
        self.hierarchy = Hierarchy()
        if not config:
            self.config = Config()
        self.load_trusted_certs()

    def load_trusted_certs(self):
        self.trusted_cert_list = TrustedRoots(self.config.get_trustedroots_dir()).get_list()
        self.trusted_cert_file_list = TrustedRoots(self.config.get_trustedroots_dir()).get_file_list()

        
        
    def checkCredentials(self, creds, operation, hrn = None):
        valid = []
        if not isinstance(creds, list):
            creds = [creds]
        logger.debug("Auth.checkCredentials with %d creds"%len(creds))
        for cred in creds:
            try:
                self.check(cred, operation, hrn)
                valid.append(cred)
            except:
                cred_obj=Credential(string=cred)
                logger.debug("failed to validate credential - dump=%s"%cred_obj.dump_string(dump_parents=True))
                error = sys.exc_info()[:2]
                continue
            
        if not len(valid):
            raise InsufficientRights('Access denied: %s -- %s' % (error[0],error[1]))
        
        return valid
        
        
    def check(self, cred, operation, hrn = None):
        """
        Check the credential against the peer cert (callerGID included 
        in the credential matches the caller that is connected to the 
        HTTPS connection, check if the credential was signed by a 
        trusted cert and check if the credential is allowed to perform 
        the specified operation.    
        """
        self.client_cred = Credential(string = cred)
        self.client_gid = self.client_cred.get_gid_caller()
        self.object_gid = self.client_cred.get_gid_object()
        
        # make sure the client_gid is not blank
        if not self.client_gid:
            raise MissingCallerGID(self.client_cred.get_subject())
       
        # validate the client cert if it exists
        if self.peer_cert:
            self.verifyPeerCert(self.peer_cert, self.client_gid)                   

        # make sure the client is allowed to perform the operation
        if operation:
            if not self.client_cred.can_perform(operation):
                raise InsufficientRights(operation)

        if self.trusted_cert_list:
            self.client_cred.verify(self.trusted_cert_file_list, self.config.SFA_CREDENTIAL_SCHEMA)
        else:
           raise MissingTrustedRoots(self.config.get_trustedroots_dir())
       
        # Make sure the credential's target matches the specified hrn. 
        # This check does not apply to trusted peers 
        trusted_peers = [gid.get_hrn() for gid in self.trusted_cert_list]
        if hrn and self.client_gid.get_hrn() not in trusted_peers:
            target_hrn = self.object_gid.get_hrn()
            if not hrn == target_hrn:
                raise PermissionError("Target hrn: %s doesn't match specified hrn: %s " % \
                                       (target_hrn, hrn) )       
        return True

    def check_ticket(self, ticket):
        """
        Check if the tickt was signed by a trusted cert
        """
        if self.trusted_cert_list:
            client_ticket = SfaTicket(string=ticket)
            client_ticket.verify_chain(self.trusted_cert_list)
        else:
           raise MissingTrustedRoots(self.config.get_trustedroots_dir())

        return True 

    def verifyPeerCert(self, cert, gid):
        # make sure the client_gid matches client's certificate
        if not cert.is_pubkey(gid.get_pubkey()):
            raise ConnectionKeyGIDMismatch(gid.get_subject()+":"+cert.get_subject())            

    def verifyGidRequestHash(self, gid, hash, arglist):
        key = gid.get_pubkey()
        if not key.verify_string(str(arglist), hash):
            raise BadRequestHash(hash)

    def verifyCredRequestHash(self, cred, hash, arglist):
        gid = cred.get_gid_caller()
        self.verifyGidRequestHash(gid, hash, arglist)

    def validateGid(self, gid):
        if self.trusted_cert_list:
            gid.verify_chain(self.trusted_cert_list)

    def validateCred(self, cred):
        if self.trusted_cert_list:
            cred.verify(self.trusted_cert_file_list)

    def authenticateGid(self, gidStr, argList, requestHash=None):
        gid = GID(string = gidStr)
        self.validateGid(gid)
        # request_hash is optional
        if requestHash:
            self.verifyGidRequestHash(gid, requestHash, argList)
        return gid

    def authenticateCred(self, credStr, argList, requestHash=None):
        cred = Credential(string = credStr)
        self.validateCred(cred)
        # request hash is optional
        if requestHash:
            self.verifyCredRequestHash(cred, requestHash, argList)
        return cred

    def authenticateCert(self, certStr, requestHash):
        cert = Certificate(string=certStr)
        # xxx should be validateCred ??
        self.validateCred(cert)   

    def gidNoop(self, gidStr, value, requestHash):
        self.authenticateGid(gidStr, [gidStr, value], requestHash)
        return value

    def credNoop(self, credStr, value, requestHash):
        self.authenticateCred(credStr, [credStr, value], requestHash)
        return value

    def verify_cred_is_me(self, credential):
        is_me = False 
        cred = Credential(string=credential)
        caller_gid = cred.get_gid_caller()
        caller_hrn = caller_gid.get_hrn()
        if caller_hrn != self.config.SFA_INTERFACE_HRN:
            raise SfaPermissionDenied(self.config.SFA_INTEFACE_HRN)

        return   
        
    def get_auth_info(self, auth_hrn):
        """
        Given an authority name, return the information for that authority.
        This is basically a stub that calls the hierarchy module.
        
        @param auth_hrn human readable name of authority  
        """

        return self.hierarchy.get_auth_info(auth_hrn)


    def veriry_auth_belongs_to_me(self, name):
        """
        Verify that an authority belongs to our hierarchy. 
        This is basically left up to the implementation of the hierarchy
        module. If the specified name does not belong, ane exception is 
        thrown indicating the caller should contact someone else.

        @param auth_name human readable name of authority
        """

        # get auth info will throw an exception if the authority doesnt exist
        self.get_auth_info(name)


    def verify_object_belongs_to_me(self, name):
        """
        Verify that an object belongs to our hierarchy. By extension,
        this implies that the authority that owns the object belongs
        to our hierarchy. If it does not an exception is thrown.
    
        @param name human readable name of object        
        """
        auth_name = self.get_authority(name)
        if not auth_name:
            auth_name = name 
        if name == self.config.SFA_INTERFACE_HRN:
            return
        self.verify_auth_belongs_to_me(auth_name) 
             
    def verify_auth_belongs_to_me(self, name):
        # get auth info will throw an exception if the authority doesnt exist
        self.get_auth_info(name) 


    def verify_object_permission(self, name):
        """
        Verify that the object gid that was specified in the credential
        allows permission to the object 'name'. This is done by a simple
        prefix test. For example, an object_gid for plc.arizona would 
        match the objects plc.arizona.slice1 and plc.arizona.
    
        @param name human readable name to test  
        """
        object_hrn = self.object_gid.get_hrn()
        if object_hrn == name:
            return
        if name.startswith(object_hrn + "."):
            return
        #if name.startswith(get_authority(name)):
            #return
    
        raise PermissionError(name)

    def determine_user_rights(self, caller_hrn, reg_record):
        """
        Given a user credential and a record, determine what set of rights the
        user should have to that record.
        
        This is intended to replace determine_user_rights() and
        verify_cancreate_credential()
        """

        rl = Rights()
        type = reg_record.type

        logger.debug("entering determine_user_rights with record %s and caller_hrn %s"%(reg_record, caller_hrn))

        if type == 'slice':
            # researchers in the slice are in the DB as-is
            researcher_hrns = [ user.hrn for user in reg_record.reg_researchers ]
            # locating PIs attached to that slice
            slice_pis=reg_record.get_pis()
            pi_hrns = [ user.hrn for user in slice_pis ]
            if (caller_hrn in researcher_hrns + pi_hrns):
                rl.add('refresh')
                rl.add('embed')
                rl.add('bind')
                rl.add('control')
                rl.add('info')

        elif type == 'authority':
            pi_hrns = [ user.hrn for user in reg_record.reg_pis ]
            if (caller_hrn == self.config.SFA_INTERFACE_HRN):
                rl.add('authority')
                rl.add('sa')
                rl.add('ma')
            if (caller_hrn in pi_hrns):
                rl.add('authority')
                rl.add('sa')
            # NOTE: for the PL implementation, this 'operators' list 
            # amounted to users with 'tech' role in that site 
            # it seems like this is not needed any longer, so for now I just drop that
            # operator_hrns = reg_record.get('operator',[])
            # if (caller_hrn in operator_hrns):
            #    rl.add('authority')
            #    rl.add('ma')

        elif type == 'user':
            rl.add('refresh')
            rl.add('resolve')
            rl.add('info')

        elif type == 'node':
            rl.add('operator')

        return rl

    def get_authority(self, hrn):
        return get_authority(hrn)

    def filter_creds_by_caller(self, creds, caller_hrn_list):
        """
        Returns a list of creds who's gid caller matches the 
        specified caller hrn
        """
        if not isinstance(creds, list):
            creds = [creds]
        creds = []
        if not isinstance(caller_hrn_list, list):
            caller_hrn_list = [caller_hrn_list]
        for cred in creds:
            try:
                tmp_cred = Credential(string=cred)
                if tmp_cred.get_gid_caller().get_hrn() in [caller_hrn_list]:
                    creds.append(cred)
            except: pass
        return creds
Beispiel #8
0
def account_process(request):
    from sfa.trust.credential               import Credential
    from sfa.trust.certificate              import Keypair

    user_query  = Query().get('local:user').select('user_id','email','password','config')
    user_details = execute_query(request, user_query)
    
    account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
    account_details = execute_query(request, account_query)

    platform_query  = Query().get('local:platform').select('platform_id','platform')
    platform_details = execute_query(request, platform_query)
    
    # getting the user_id from the session                                            
    for user_detail in user_details:                                                  
        user_id = user_detail['user_id']                                              
        user_email = user_detail['email']                                             
        try:
            if user_email == request.user.email:                                          
                authorize_query = True                                                    
            else:                                                                         
                logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
                messages.error(request, 'You are not authorized to modify another user.') 
                return HttpResponseRedirect("/portal/account/")                               
        except Exception as e:
            logger.error("exception in account_process {}".format(e))

    for account_detail in account_details:
        for platform_detail in platform_details:
            # Add reference account to the platforms
            if 'add_'+platform_detail['platform'] in request.POST\
               or request.POST['button_value'] == 'add_'+platform_detail['platform']:
                platform_id = platform_detail['platform_id']
                user_params = {'platform_id': platform_id, 'user_id': user_id,
                               'auth_type': "reference",
                               'config': '{"reference_platform": "myslice"}'}
                manifold_add_account(request,user_params)
                messages.info(request, 'Reference Account is added to the selected platform successfully!')
                return HttpResponseRedirect("/portal/account/")

            # Delete reference account from the platforms
            if 'delete_'+platform_detail['platform'] in request.POST\
               or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
                platform_id = platform_detail['platform_id']
                user_params = {'user_id':user_id}
                manifold_delete_account(request,platform_id, user_id, user_params)
                messages.info(request, 'Reference Account is removed from the selected platform')
                return HttpResponseRedirect("/portal/account/")

            if platform_detail['platform_id'] == account_detail['platform_id']:
                if 'myslice' in platform_detail['platform']:
                    account_config = json.loads(account_detail['config'])
                    acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
                    acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
                

                    
    
    # adding the slices and corresponding credentials to list
    if 'N/A' not in acc_slice_cred:
        slice_list = []
        slice_cred = [] 
        for key, value in acc_slice_cred.iteritems():
            slice_list.append(key)       
            slice_cred.append(value)
        # special case: download each slice credentials separately 
        for i in range(0, len(slice_list)):
            if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
                slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
                response = HttpResponse(slice_detail, content_type='text/plain')
                response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
                return response

    # adding the authority and corresponding credentials to list
    if 'N/A' not in acc_auth_cred:
        auth_list = []
        auth_cred = [] 
        for key, value in acc_auth_cred.iteritems():
            auth_list.append(key)       
            auth_cred.append(value)
        # special case: download each slice credentials separately
        for i in range(0, len(auth_list)):
            if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
                auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
                response = HttpResponse(auth_detail, content_type='text/plain')
                response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
                return response

    account_detail = get_myslice_account(request)
             
    if 'submit_name' in request.POST:
        edited_first_name =  request.POST['fname']
        edited_last_name =  request.POST['lname']
        
        config={}
        for user_config in user_details:
            if user_config['config']:
                config = json.loads(user_config['config'])
                config['firstname'] = edited_first_name
                config['lastname'] = edited_last_name
                config['authority'] = config.get('authority','Unknown Authority')
                updated_config = json.dumps(config)
                user_params = {'config': updated_config}
            else: # it's needed if the config is empty 
                user_config['config'] = '{{"firstname":"{}", "lastname":"{}", "authority": "Unknown Authority"}}'\
                                        .format(edited_first_name, edited_last_name)
                user_params = {'config': user_config['config']} 
        # updating config local:user in manifold       
        manifold_update_user(request, request.user.email,user_params)
        # this will be depricated, we will show the success msg in same page
        # Redirect to same page with success message
        messages.success(request, 'Sucess: First Name and Last Name Updated.')
        return HttpResponseRedirect("/portal/account/")       
    
    elif 'submit_pass' in request.POST:
        edited_password = request.POST['password']
        
        for user_pass in user_details:
            user_pass['password'] = edited_password
        #updating password in local:user
        user_params = { 'password' : user_pass['password']}
        manifold_update_user(request, request.user.email, user_params)
#        return HttpResponse('Success: Password Changed!!')
        messages.success(request, 'Success: Password Updated.')
        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:
        try:
            private = RSA.generate(1024)
            private_key = json.dumps(private.exportKey())
            public  = private.publickey()
            public_key = json.dumps(public.exportKey(format='OpenSSH'))
            # updating manifold local:account table
            account_config = json.loads(account_detail['config'])
            # 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) 
            # updating manifold
            #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)
            result_sfa_user = sfa_get_user(request, user_hrn, public_key)
            try:
                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 as 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.')
                logger.error("Exception in accountview {}".format(e))
            return HttpResponseRedirect("/portal/account/")
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
                       
    elif 'upload_key' in request.POST:
        try:
            up_file = request.FILES['pubkey']
            file_content =  up_file.read()
            file_name = up_file.name
            file_extension = os.path.splitext(file_name)[1] 
            allowed_extension =  ['.pub','.txt']
            if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
                account_config = json.loads(account_detail['config'])
                # preserving user_hrn
                user_hrn = account_config.get('user_hrn','N/A')
                file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
                #file_content = re.sub("\r", "", file_content)
                #file_content = re.sub("\n", "\\n",file_content)
                file_content = ''.join(file_content.split())
                #update manifold local:account table
                user_params = { 'config': file_content, 'auth_type':'user'}
                manifold_update_account(request, user_id, user_params)
                # updating sfa
                user_pub_key = {'keys': file_content}
                sfa_update_user(request, user_hrn, user_pub_key)
                messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
                return HttpResponseRedirect("/portal/account/")
            else:
                messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
                return HttpResponseRedirect("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")

    elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
        try:
            account_config = json.loads(account_detail['config'])
            public_key = account_config['user_public_key'] 
            response = HttpResponse(public_key, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
            return response
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
               
    elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
        try:
            account_config = json.loads(account_detail['config'])
            if 'user_private_key' in account_config:
                private_key = account_config['user_private_key']
                response = HttpResponse(private_key, content_type='text/plain')
                response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
                return response
            else:
                messages.error(request, 'Download error: Private key is not stored in the server')
                return HttpResponseRedirect("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
    
    elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
        try:
            account_config = json.loads(account_detail['config'])
            if 'user_private_key' in account_config:
                for key in account_config.keys():
                    if key == 'user_private_key':    
                        del account_config[key]
                    
                updated_config = json.dumps(account_config)
                user_params = { 'config': updated_config, 'auth_type':'user'}
                manifold_update_account(request, user_id, user_params)
                messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
                messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
                return HttpResponseRedirect("/portal/account/")
            else:
                messages.error(request, 'Delete error: Private key is not stored in the server')
                return HttpResponseRedirect("/portal/account/")
                          
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
            return HttpResponseRedirect("/portal/account/")
    
    # download identity for jfed
    elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
        try:
            jfed_identity = get_jfed_identity(request)
            if jfed_identity is not None:
                response = HttpResponse(jfed_identity, content_type='text/plain')
                response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
                return response
            else:
                messages.error(request, 'Download error: Private key is not stored in the server')
                return HttpResponseRedirect("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")

    # Download sfi_config
    elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
        platform_detail = get_myslice_platform(request)
        platform_config = json.loads(platform_detail['config'])
        account_detail = get_myslice_account(request)
        account_config = json.loads(account_detail['config'])

        user_hrn = account_config.get('user_hrn','N/A')
        t_user_hrn = user_hrn.split('.')
        authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
        registry = get_registry_url(request)
        import socket
        hostname = socket.gethostbyaddr(socket.gethostname())[0]
        admin_user = platform_config.get('user','N/A')
        manifold_host = ConfigEngine().manifold_url()
        if 'localhost' in manifold_host:
            manifold_host = manifold_host.replace('localhost',hostname)
        sfi_config  = '[sfi]\n'
        sfi_config += 'auth = '+ authority_hrn +'\n'
        sfi_config += 'user = '******'\n'
        sfi_config += 'registry = '+ registry +'\n'
        sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
        sfi_config += '[myslice]\n'
        sfi_config += 'backend = '+ manifold_host +'\n'
        sfi_config += 'delegate  = '+ admin_user +'\n'
        sfi_config += 'platform  = myslice\n'
        sfi_config += 'username  = '******'\n'
        response = HttpResponse(sfi_config, content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="sfi_config"'
        return response

    #clear all creds
    elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
        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 as e:
            logger.error("Exception in accountview.py in clear_user_creds {}".format(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 or request.POST['button_value'] == 'dl_user_cred':
        if 'delegated_user_credential' in account_config:
            user_cred = account_config['delegated_user_credential']
            response = HttpResponse(user_cred, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
            return response
        else:
            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 or request.POST['button_value'] == 'dl_user_cert':
        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 or request.POST['button_value'] == 'dl_user_p12':
        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/")