Пример #1
0
 def __init__(self):
     Plugin.__init__(self)
     self.libplugin = LibAuth()
Пример #2
0
class Cmd_auth(Plugin, cmd.Cmd):
    '''
    pyrax shell POC - Authenticate module
    '''

    prompt = "RS auth>"  # default prompt

    def __init__(self):
        Plugin.__init__(self)
        self.libplugin = LibAuth()

    def do_EOF(self, line):
        '''
        just press CTRL-D to quit this menu
        '''
        print
        return True

    def emptyline(self):
        """Called when an empty line is entered in response to the prompt.

        If this method is not overridden, it repeats the last nonempty
        command entered.

        """
        if self.lastcmd:
            self.lastcmd = ""
            return self.onecmd('\n')

    def preloop(self):
        cmd.Cmd.preloop(self)
        logging.debug("preloop")
        import plugins.libauth
        if not plugins.libauth.LibAuth().is_authenticated():
            logging.warn('please, authenticate yourself before continuing')

    # ########################################
    # CLOUD AUTHENTICATION

#     def do_change_password(self, line):
#         '''
#         change user\'s password
#         '''
# #TODO --
#         logging.info('NOT IMPLEMENTED YET')

    def do_account(self, line):
        '''
        authenticate using ACCOUNT_FILE
        
        @param alias    account alias (i.e.: name of stanza in ACCOUNT_FILE)
        '''
        try:
            self.libplugin.authenticate_login(
                **self.libplugin.get_account(self.arg))
#                 identity_type = ,
#                 username = None,
#                 apikey = None,
#                 region = pyrax.default_region)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)

    def complete_account(self, text, line, begidx, endidx):
        params = self.libplugin.list_accounts()
        if not text:
            completions = params[:]
        else:
            completions = [f for f in params if f.startswith(text)]
        return completions

    def do_credentials(self, line):
        '''
        authentication with credentials file
        
        @param file    credential file (pyrax format)
        
        i.e.: credentials file:~/.pyrax
        '''
        # check and set defaults
        retcode, retmsg = self.kvargcheck({'name': 'file', 'default': ''})
        if not retcode:  # something bad happened
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)  # everything's ok
        # additional checks
        _file = self.kvarg['file']
        if _file.find('~') == 0:
            _file = os.path.expanduser(_file)
        if _file != '' and not os.path.isfile(_file):
            cmd_out = 'cannot find file \'%s\'' % _file
            self.r(1, cmd_out, ERROR)
            return False
        # authenticating with credentials file
        if _file != None and _file != '':
            errcode = (self.libplugin.authenticate_credentials_file(_file))
        else:
            errcode = self.libplugin.authenticate_credentials_file()
        if errcode:
            cmd_out = "token: %s" % self.libplugin.get_token()
            self.r(0, cmd_out, INFO)
        else:
            cmd_out = ("cannot authenticate using credentials file")
            self.r(1, cmd_out, ERROR)
            return False

    def complete_credentials(self, text, line, begidx, endidx):
        params = ['file:']
        if not text:
            completions = params[:]
        else:
            completions = [f for f in params if f.startswith(text)]
        return completions

    def do_exit(self, *args):
        return True

    def do_is_authenticated(self, line):
        '''
        show Whether or not the user is authenticated
        '''
        retcode = 1
        if self.libplugin.is_authenticated():
            retcode = 0
        self.r(retcode, 'authenticated', INFO)

    def do_list(self, line):
        '''
        list accounts defined in ACCOUNTS_FILE
        '''
        cmd_out = '\n'.join([a for a in self.libplugin.list_accounts()])
        self.r(0, cmd_out, INFO)

    def do_login(self, line):
        '''
        authenticate using username and api-key and authenticate
        
        Parameters:
        
        apikey
        username
        identity_type    (default: rackspace)
        region           (default: pyrax.default_region)
        '''
        # check and set defaults
        retcode, retmsg = self.kvargcheck(
            {
                'name': 'apikey',
                'required': True
            }, {
                'name': 'username',
                'required': True
            }, {
                'name': 'identity_type',
                'default': 'rackspace'
            }, {
                'name': 'region',
                'default': self.libplugin.default_region()
            })
        if not retcode:  # something bad happened
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)  # everything's ok

        try:
            self.libplugin.authenticate_login(
                apikey=self.kvarg['apikey'],
                username=self.kvarg['username'],
                identity_type=self.kvarg['identity_type'],
                region=self.kvarg['region'],
            )
            cmd_out = ('login - indentity_type:%s, username=%s, apikey=%s, '
                       'region=%s' %
                       (self.kvarg['identity_type'], self.kvarg['username'],
                        self.kvarg['apikey'], self.kvarg['region']))
            self.r(0, cmd_out, INFO)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)

    def complete_login(self, text, line, begidx, endidx):
        params = ['identity_type:', 'username:'******'apikey:', 'region:']
        if not text:
            completions = params[:]
        else:
            completions = [f for f in params if f.startswith(text)]
        return completions

    def do_print_identity(self, line):
        '''
        print current identity information
        '''
        self.libplugin.print_pt_identity_info()

    def do_print_token(self, line):
        '''
        print token for current session
        '''
        if self.libplugin.is_authenticated():
            cmd_out = "token: %s" % self.libplugin.get_token()
            self.r(0, cmd_out, INFO)

    def do_token(self, line):
        '''
        authenticate using token and tenantId
        
        Parameters:
        
        identity_type    (default: rackspace)
        region           (default: LON)
        tenantId
        token
        '''
        retcode, retmsg = self.kvargcheck(
            {
                'name': 'identity_type',
                'default': 'rackspace'
            }, {
                'name': 'region',
                'default': 'LON'
            }, {
                'name': 'tenantId',
                'required': True
            }, {
                'name': 'token',
                'required': True
            })
        if not retcode:
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)
        try:
            self.libplugin.authenticate_token(
                identity_type=self.kvarg['identity_type'],
                region=self.kvarg['region'],
                tenantId=self.kvarg['tenantId'],
                token=self.kvarg['token'],
            )
            cmd_out = ('login - tenantId=%s, token=%s' %
                       (self.kvarg['tenantId'], self.kvarg['token']))
            self.r(0, cmd_out, INFO)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)

    def complete_token(self, text, line, begidx, endidx):
        params = ['identity_type', 'region', 'tenantId', 'token']
        if not text:
            completions = params[:]
        else:
            completions = [f for f in params if f.startswith(text)]
        return completions
Пример #3
0
class Cmd_auth(Plugin, cmd.Cmd):
    '''
    pyrax shell POC - Authenticate module
    '''
    
    prompt = "RS auth>"    # default prompt
    
    def __init__(self):
        Plugin.__init__(self)
        self.libplugin = LibAuth()

    def do_EOF(self, line):
        '''
        just press CTRL-D to quit this menu
        '''
        print
        return True
    
    def emptyline(self):
        """Called when an empty line is entered in response to the prompt.

        If this method is not overridden, it repeats the last nonempty
        command entered.

        """
        if self.lastcmd:
            self.lastcmd = ""
            return self.onecmd('\n')

    def preloop(self):
        cmd.Cmd.preloop(self)
        logging.debug("preloop")
        import plugins.libauth
        if not plugins.libauth.LibAuth().is_authenticated():
            logging.warn('please, authenticate yourself before continuing')
    
    # ########################################
    # CLOUD AUTHENTICATION
    
#     def do_change_password(self, line):
#         '''
#         change user\'s password
#         '''
# #TODO --
#         logging.info('NOT IMPLEMENTED YET')

    def do_account(self, line):
        '''
        authenticate using ACCOUNT_FILE
        
        @param alias    account alias (i.e.: name of stanza in ACCOUNT_FILE)
        '''
        try:
            self.libplugin.authenticate_login(
                **self.libplugin.get_account(self.arg))
#                 identity_type = ,
#                 username = None,
#                 apikey = None,
#                 region = pyrax.default_region)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)
    
    def complete_account(self, text, line, begidx, endidx):
        params = self.libplugin.list_accounts()
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions
    
    def do_credentials(self, line):
        '''
        authentication with credentials file
        
        @param file    credential file (pyrax format)
        
        i.e.: credentials file:~/.pyrax
        '''
        # check and set defaults
        retcode, retmsg = self.kvargcheck(
            {'name':'file', 'default':''}
        )
        if not retcode:             # something bad happened
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)     # everything's ok
        # additional checks
        _file = self.kvarg['file']
        if _file.find('~') == 0:
            _file = os.path.expanduser(_file)
        if _file != '' and not os.path.isfile(_file):
            cmd_out = 'cannot find file \'%s\'' % _file
            self.r(1, cmd_out, ERROR)
            return False
        # authenticating with credentials file
        if _file != None and _file != '':
            errcode = (self.libplugin.authenticate_credentials_file(_file))
        else:
            errcode = self.libplugin.authenticate_credentials_file()
        if errcode:
            cmd_out = "token: %s" % self.libplugin.get_token()
            self.r(0, cmd_out, INFO)
        else:
            cmd_out = ("cannot authenticate using credentials file")
            self.r(1, cmd_out, ERROR)
            return False
    
    def complete_credentials(self, text, line, begidx, endidx):
        params = ['file:']
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions

    def do_exit(self,*args):
        return True
    
    def do_is_authenticated(self, line):
        '''
        show Whether or not the user is authenticated
        '''
        retcode = 1
        if self.libplugin.is_authenticated():
            retcode = 0
        self.r(retcode, 'authenticated', INFO)
    
    def do_list(self, line):
        '''
        list accounts defined in ACCOUNTS_FILE
        '''
        cmd_out = '\n'.join([a for a in self.libplugin.list_accounts()])
        self.r(0, cmd_out, INFO)
    
    def do_login(self, line):
        '''
        authenticate using username and api-key and authenticate
        
        Parameters:
        
        apikey
        username
        identity_type    (default: rackspace)
        region           (default: pyrax.default_region)
        '''
        # check and set defaults
        retcode, retmsg = self.kvargcheck(
            {'name':'apikey', 'required':True},
            {'name':'username', 'required':True},
            {'name':'identity_type', 'default':'rackspace'},
            {'name':'region', 'default':self.libplugin.default_region()}
        )
        if not retcode:             # something bad happened
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)     # everything's ok
        
        try:
            self.libplugin.authenticate_login(
                apikey = self.kvarg['apikey'],
                username = self.kvarg['username'],
                identity_type = self.kvarg['identity_type'],
                region = self.kvarg['region'],
            )
            cmd_out  = ('login - indentity_type:%s, username=%s, apikey=%s, '
                        'region=%s' % 
                        (self.kvarg['identity_type'], self.kvarg['username'],
                         self.kvarg['apikey'], self.kvarg['region']))
            self.r(0, cmd_out, INFO)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)
    
    def complete_login(self, text, line, begidx, endidx):
        params = ['identity_type:', 'username:'******'apikey:', 'region:']
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions

    def do_print_identity(self, line):
        '''
        print current identity information
        '''
        self.libplugin.print_pt_identity_info()
    
    def do_print_token(self, line):
        '''
        print token for current session
        '''
        if self.libplugin.is_authenticated():
            cmd_out = "token: %s" % self.libplugin.get_token()
            self.r(0, cmd_out, INFO)
    
    def do_token(self, line):
        '''
        authenticate using token and tenantId
        
        Parameters:
        
        identity_type    (default: rackspace)
        region           (default: LON)
        tenantId
        token
        '''
        retcode, retmsg = self.kvargcheck(
              {'name':'identity_type', 'default':'rackspace'},
              {'name':'region', 'default':'LON'},
              {'name':'tenantId', 'required':True},
              {'name':'token', 'required':True}
        )
        if not retcode:
            self.r(1, retmsg, ERROR)
            return False
        self.r(0, retmsg, INFO)
        try:
            self.libplugin.authenticate_token(
                identity_type=self.kvarg['identity_type'],
                region=self.kvarg['region'],
                tenantId=self.kvarg['tenantId'],
                token=self.kvarg['token'],
            )
            cmd_out = ('login - tenantId=%s, token=%s' %
                       (self.kvarg['tenantId'], self.kvarg['token']))
            self.r(0, cmd_out, INFO)
        except:
            tb = traceback.format_exc()
            self.r(1, tb, ERROR)
    
    def complete_token(self, text, line, begidx, endidx):
        params = ['identity_type', 'region', 'tenantId', 'token']
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions
Пример #4
0
 def __init__(self):
     Plugin.__init__(self)
     self.libplugin = LibAuth()
Пример #5
0
class Cmd_auth(cmd.Cmd):
    '''
    pyrax shell POC - Authenticate module
    '''
    
    prompt = "RS auth>"    # default prompt
    
    def __init__(self):
        Plugin.__init__(self)
        self.libplugin = LibAuth()

    def do_EOF(self, line):
        '''
        just press CTRL-D to quit this menu
        '''
        print
        return True
    
    def emptyline(self):
        """Called when an empty line is entered in response to the prompt.

        If this method is not overridden, it repeats the last nonempty
        command entered.

        """
        if self.lastcmd:
            self.lastcmd = ""
            return self.onecmd('\n')

    def preloop(self):
        cmd.Cmd.preloop(self)
        logging.debug("preloop")
        import plugins.libauth
        if not plugins.libauth.LibAuth().is_authenticated():
            logging.warn('please, authenticate yourself before continuing')
    
    # ########################################
    # CLOUD AUTHENTICATION
    
    def do_change_password(self, line):
        '''
        change user\'s password
        '''
#TODO --
        logging.info('NOT IMPLEMENTED YET')
    
    def do_credentials(self, line):
        '''
        authenticate using credentials file
        '''
        logging.info("authenticating using credentials file")
        logging.debug("line: %s" % line)
        if self.libplugin.authenticate_credentials_file():
            logging.info("token: %s" % self.libplugin.get_token())
        else:
            logging.warn("cannot authenticate using pyrax credentials file")

    def do_exit(self,*args):
        return True
    
    def do_is_authenticated(self, line):
        '''
        show Whether or not the user is authenticated
        '''
        logging.info(self.libplugin.is_authenticated())
        logging.debug("line: %s" % line)
    
    def do_login(self, line):
        '''
        authenticate using username and api-key and authenticate
        
        Parameters:
        
        identity_type = 'rackspace'    (default)
        username
        apikey
        region                         (default: pyrax.default_region)
        '''
        logging.debug("line: %s" % line)
        d_kv = kvstring_to_dict(line)
        logging.debug("kvs: %s" % d_kv)
        # default values
        _identity_type = 'rackspace'
        _username = None
        _apikey = None
        _region = self.libplugin.default_region()
        # parsing parameters
        if 'identity_type' in d_kv.keys():
            _identity_type = d_kv['identity_type']
        else:
            logging.info("identity_type: %s (default)" % _identity_type)
        if 'username' in d_kv.keys():
            _username = d_kv['username']
        else:
            logging.error("missing username")
            return False
        if 'apikey' in d_kv.keys():
            _apikey = d_kv['apikey']
        else:
            logging.error("missing apikey")
            return False
        if 'region' in d_kv.keys():
            _region = d_kv['region']
        
        logging.info('login - indentity_type:%s, username=%s, apikey=%s, '
                     'region=%s' %
                     (_identity_type, _username, _apikey, _region))
        try:
            self.libplugin.authenticate_login(identity_type = _identity_type,
                                                  username = _username,
                                                  apikey = _apikey,
                                                  region = _region)
        except Exception as inst:
            print type(inst)     # the exception instance
            print inst.args      # arguments stored in .args
            print inst           # __str__ allows args to printed directly
    
    def complete_login(self, text, line, begidx, endidx):
        params = ['identity_type:', 'username:'******'apikey:', 'region:']
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions

    def do_print_identity(self, line):
        '''
        print current identity information
        '''
        self.libplugin.print_pt_identity_info()
    
    def do_print_token(self, line):
        '''
        print token for current session
        '''
        if self.libplugin.is_authenticated():
            logging.info("token: %s" % self.libplugin.get_token())
    
    def do_token(self, line):
        '''
        authenticate using token and tenantId
        
        Parameters:
        
        identity_type
        region
        tenantId
        token
        '''
        logging.debug("line: %s" % line)
        d_kv = kvstring_to_dict(line)
        logging.debug("kvs: %s" % d_kv)
        # default values
        _identity_type = None
        _region = None
        _tenantId = None
        _token = None
        if 'identity_type' in d_kv.keys():
            _identity_type = d_kv['identity_type']
        else:
            logging.error("missing identity_type")
            return False
        if 'region' in d_kv.keys():
            _region = d_kv['region']
        else:
            logging.error("missing region")
            return False
        # parsing parameters
        if 'tenantId' in d_kv.keys():
            _tenantId = d_kv['tenantId']
        else:
            logging.error("missing tenantId")
            return False
        if 'token' in d_kv.keys():
            _token = d_kv['token']
        else:
            logging.error("missing token")
            return False
        #
        print "-" * 10
        print _tenantId, _token
        logging.info('login - tenantId=%s, token=%s' %
                     (_tenantId, _token))
        try:
            self.libplugin.authenticate_token(token=_token, tenantId=_tenantId,
                                              region=_region,
                                              identity_type=_identity_type)
        except Exception as inst:
            print type(inst)     # the exception instance
            print inst.args      # arguments stored in .args
            print inst           # __str__ allows args to printed directly
    
    def complete_token(self, text, line, begidx, endidx):
        params = ['identity_type', 'region', 'tenantId', 'token']
        if not text:
            completions = params[:]
        else:
            completions = [ f
                           for f in params
                            if f.startswith(text)
                            ]
        return completions