Esempio n. 1
0
def get_access_token_util(auth_code):
    """
    Given an auth code, retrieve and return the access token from BaseSpace
    """            
    app = current.db(current.db.app_data.id > 0).select().first()    
    bs_api = BaseSpaceAPI(app.client_id,app.client_secret,app.baseSpaceUrl,app.version,current.session.app_session_num)
    
    bs_api.updatePrivileges(auth_code)      
    access_token =  bs_api.getAccessToken()   
    
    # set token in session var
    current.session.token = access_token                  
    return access_token
class TestSDK(object):
    '''
    Compares objects from BaseSpace REST API to SDK objects, including pickled objects
    '''
    def __init__(self):                                        
        
        self.qp = {}
        self.rest_method = 'GET'
        self.postData = None
        self.headerParams=None
        self.list_request = False
        
        # TODO change to unit_tests, but need to add projects/run to account?
        self.myAPI = BaseSpaceAPI(profile="ps_native_hoth")        
        self.api = APIClient(self.myAPI.getAccessToken(), self.myAPI.apiServer)        

    def compare_dict_to_obj(self, rest_dict, p_obj):
        """ 
        Compare a dictionary from a REST API response and a SDK object for identity.
        """
        for r_key, r_val in rest_dict.iteritems():
            # confirm that the key from REST api exists in stored object
            try:
                p_val = getattr(p_obj, r_key)                                      
            except AttributeError:
                print "REST API attribute '" + r_key + "' doesn't exist in object"                            
            else:
                self.classify_rest_item(r_val, p_val, r_key)                    

    def compare_list_to_obj(self, rest_list, p_obj, r_key):
        """ 
        Compare a list from a REST API response and an SDK object for identity.
        """                   
        if type(p_obj) != list:
            print "Attribute '" + r_key + "' is a list in the REST API but not in the object"
        elif len(p_obj) != len(rest_list):
            print "Attribute '" + r_key + "' has different list length between REST API and object"
        else:
            for r_val, p_val in map(None, rest_list, p_obj):
                self.classify_rest_item(r_val, p_val, r_key)
                                                                        
    def compare_builtin_to_obj(self, rest_val, p_obj, r_key):
        """ 
        Compare a built-in type from a REST API response and an SDK object for identity.
        """                   
        # convert unicode to ascii for comparisons
        if isinstance(rest_val, unicode):
            rest_val = rest_val.encode('ascii','ignore')
        # don't compare values for datetimes
        if r_key in ['DateCreated', 'DateModified', 'DateUploadCompleted', 'DateUploadStarted']:
            pass
        elif rest_val != p_obj:                                
            print "REST API attribute '" + r_key + "' has value '" + str(rest_val) + "' doesn't match object value '" + str(p_obj) + "'"                            

    def classify_rest_item(self, r_val, p_val, r_key):
        """
        Determine the input REST item's type and call method to compare to input object
        """                                        
        if type(r_val) in [ int, str, bool, float, unicode]:                            
            self.compare_builtin_to_obj(r_val, p_val, r_key)
        elif type(r_val) == dict:            
            self.compare_dict_to_obj(r_val, p_val)
        elif type(r_val) == list:                                    
            self.compare_list_to_obj(r_val, p_val, r_key)
        else:
            print "REST API attribute'" + r_key + "' has an unrecognized attribute type"                            
        
    def test_rest_vs_sdk(self):
        """
        Compares REST API response and python SDK object for identify, for an API method
        """        
        sdk_obj = self.call_sdk()
        rest_obj = self.call_rest_api()                                                        
        # TODO passing Response here, SDK doesn't currently capture other items at this level (e.g. Notifications)
        if self.list_request:
            self.compare_list_to_obj(rest_obj['Response']['Items'], sdk_obj, "BASE")
        else:
            self.compare_dict_to_obj(rest_obj['Response'], sdk_obj)

    def call_rest_api(self):
        """
        Call the REST API for this object
        """
        return self.api.callAPI(self.rest_path, self.rest_method, queryParams=self.qp, postData=self.postData, headerParams=self.headerParams)

    def create_pickle_from_sdk(self, pickle_path):
        """
        Stores a pickled object in the provided path (include file name) for the object returned for this SDK method
        """
        sdk_obj = self.call_sdk()        
        with open(pickle_path, 'w') as f:
            Pickle.dump(sdk_obj, f)
            
    def get_pickle(self, pickle_path):
        """
        Retrieves a pickled object from the provided path (include file name), for this API test
        """        
        with open(pickle_path, 'r') as f:
            sdk_obj = Pickle.load(f)
        return sdk_obj        
        
    def test_rest_vs_pickle(self, pickle_path):
        """
        Compares REST API response and a stored object for identify, for an API method
        """
        p_obj = self.get_pickle(pickle_path)
        rest_obj = self.call_rest_api()
        self.compare_dict_to_obj(rest_obj['Response'], p_obj)
# Have the user visit the verification uri to grant us access
print "\nPlease visit the uri within 15 seconds and grant access"
print deviceInfo['verification_with_code_uri']
webbrowser.open_new(deviceInfo['verification_with_code_uri'])
time.sleep(15)
## PAUSE HERE

# Once the user has granted us access to objects we requested, we can
# get the basespace access token and start browsing simply by calling updatePriviliges
# on the baseSpaceApi instance.
code = deviceInfo['device_code']
myAPI.updatePrivileges(code)

# As a reference the provided access-token can be obtained from the BaseSpaceApi object
print "\nMy Access-token:"
print myAPI.getAccessToken()

# Let's try and grab all available genomes with our new api!
allGenomes = myAPI.getAvailableGenomes()
print "\nGenomes \n" + str(allGenomes)

# If at a later stage we wish to initialize a BaseSpaceAPI object when we already have
# an access-token from a previous sessions, this may simply be done by initializing the BaseSpaceAPI
# object using the key-word AccessToken.
myToken = myAPI.getAccessToken()
myAPI.setAccessToken(myToken)
print "\nA BaseSpaceAPI instance was updated with an access-token: "
print myAPI

#################### Web-based verification #################################
# The scenario where the authentication is done through a web-browser
Esempio n. 4
0
class TestSDK(object):
    '''
    Compares objects from BaseSpace REST API to SDK objects, including pickled objects
    '''
    def __init__(self):

        self.qp = {}
        self.rest_method = 'GET'
        self.postData = None
        self.headerParams = None
        self.list_request = False

        # TODO change to unit_tests, but need to add projects/run to account?
        self.myAPI = BaseSpaceAPI(profile="ps_native_hoth")
        self.api = APIClient(self.myAPI.getAccessToken(), self.myAPI.apiServer)

    def compare_dict_to_obj(self, rest_dict, p_obj):
        """
        Compare a dictionary from a REST API response and a SDK object for identity.
        """
        for r_key, r_val in six.iteritems(rest_dict):
            # confirm that the key from REST api exists in stored object
            try:
                p_val = getattr(p_obj, r_key)
            except AttributeError:
                print("REST API attribute '" + r_key +
                      "' doesn't exist in object")
            else:
                self.classify_rest_item(r_val, p_val, r_key)

    def compare_list_to_obj(self, rest_list, p_obj, r_key):
        """
        Compare a list from a REST API response and an SDK object for identity.
        """
        if type(p_obj) != list:
            print("Attribute '" + r_key +
                  "' is a list in the REST API but not in the object")
        elif len(p_obj) != len(rest_list):
            print("Attribute '" + r_key +
                  "' has different list length between REST API and object")
        else:
            for r_val, p_val in map(None, rest_list, p_obj):
                self.classify_rest_item(r_val, p_val, r_key)

    def compare_builtin_to_obj(self, rest_val, p_obj, r_key):
        """
        Compare a built-in type from a REST API response and an SDK object for identity.
        """
        # convert unicode to ascii for comparisons
        if isinstance(rest_val, six.text_type):
            rest_val = rest_val.encode('ascii', 'ignore')
        # don't compare values for datetimes
        if r_key in [
                'DateCreated', 'DateModified', 'DateUploadCompleted',
                'DateUploadStarted'
        ]:
            pass
        elif rest_val != p_obj:
            print("REST API attribute '" + r_key + "' has value '" +
                  str(rest_val) + "' doesn't match object value '" +
                  str(p_obj) + "'")

    def classify_rest_item(self, r_val, p_val, r_key):
        """
        Determine the input REST item's type and call method to compare to input object
        """
        if type(r_val) in [int, str, bool, float, six.text_type]:
            self.compare_builtin_to_obj(r_val, p_val, r_key)
        elif type(r_val) == dict:
            self.compare_dict_to_obj(r_val, p_val)
        elif type(r_val) == list:
            self.compare_list_to_obj(r_val, p_val, r_key)
        else:
            print("REST API attribute'" + r_key +
                  "' has an unrecognized attribute type")

    def test_rest_vs_sdk(self):
        """
        Compares REST API response and python SDK object for identify, for an API method
        """
        sdk_obj = self.call_sdk()
        rest_obj = self.call_rest_api()
        # TODO passing Response here, SDK doesn't currently capture other items at this level (e.g. Notifications)
        if self.list_request:
            self.compare_list_to_obj(rest_obj['Response']['Items'], sdk_obj,
                                     "BASE")
        else:
            self.compare_dict_to_obj(rest_obj['Response'], sdk_obj)

    def call_rest_api(self):
        """
        Call the REST API for this object
        """
        return self.api.callAPI(self.rest_path,
                                self.rest_method,
                                queryParams=self.qp,
                                postData=self.postData,
                                headerParams=self.headerParams)

    def create_pickle_from_sdk(self, pickle_path):
        """
        Stores a pickled object in the provided path (include file name) for the object returned for this SDK method
        """
        sdk_obj = self.call_sdk()
        with open(pickle_path, 'w') as f:
            Pickle.dump(sdk_obj, f)

    def get_pickle(self, pickle_path):
        """
        Retrieves a pickled object from the provided path (include file name), for this API test
        """
        with open(pickle_path, 'r') as f:
            sdk_obj = Pickle.load(f)
        return sdk_obj

    def test_rest_vs_pickle(self, pickle_path):
        """
        Compares REST API response and a stored object for identify, for an API method
        """
        p_obj = self.get_pickle(pickle_path)
        rest_obj = self.call_rest_api()
        self.compare_dict_to_obj(rest_obj['Response'], p_obj)
# Have the user visit the verification uri to grant us access
print "\nPlease visit the uri within 15 seconds and grant access"
print deviceInfo['verification_with_code_uri']
webbrowser.open_new(deviceInfo['verification_with_code_uri'])
time.sleep(15)
## PAUSE HERE

# Once the user has granted us access to objects we requested, we can
# get the basespace access token and start browsing simply by calling updatePriviliges
# on the baseSpaceApi instance.
code = deviceInfo['device_code']
BSapi.updatePrivileges(code)

# As a reference the provided access-token can be obtained from the BaseSpaceApi object
print "\nMy Access-token:"
print BSapi.getAccessToken()


# Let's try and grab all available genomes with our new api! 
allGenomes  = BSapi.getAvailableGenomes()
print "\nGenomes \n" + str(allGenomes)


# If at a later stage we wish to initialize a BaseSpaceAPI object when we already have
# an access-token from a previous sessions, this may simply be done by initializing the BaseSpaceAPI
# object using the key-word AccessToken.
myToken = BSapi.getAccessToken()
BSapi = BaseSpaceAPI(client_key, client_secret, BaseSpaceUrl, version, AppSessionId, AccessToken=myToken)
print "\nA BaseSpaceAPI instance initialized with an access-token: "
print BSapi 
Esempio n. 6
0
# Have the user visit the verification uri to grant us access
print("\nPlease visit the uri within 15 seconds and grant access")
print(deviceInfo['verification_with_code_uri'])
webbrowser.open_new(deviceInfo['verification_with_code_uri'])
time.sleep(15)
## PAUSE HERE

# Once the user has granted us access to objects we requested, we can
# get the basespace access token and start browsing simply by calling updatePriviliges
# on the baseSpaceApi instance.
code = deviceInfo['device_code']
myAPI.updatePrivileges(code)

# As a reference the provided access-token can be obtained from the BaseSpaceApi object
print("\nMy Access-token:")
print(myAPI.getAccessToken())

# Let's try and grab all available genomes with our new api!
allGenomes = myAPI.getAvailableGenomes()
print("\nGenomes \n" + str(allGenomes))

# If at a later stage we wish to initialize a BaseSpaceAPI object when we already have
# an access-token from a previous sessions, this may simply be done by initializing the BaseSpaceAPI
# object using the key-word AccessToken.
myToken = myAPI.getAccessToken()
myAPI.setAccessToken(myToken)
print("\nA BaseSpaceAPI instance was updated with an access-token: ")
print(myAPI)

#################### Web-based verification #################################
# The scenario where the authentication is done through a web-browser
# Have the user visit the verification uri to grant us access
print "\nPlease visit the uri within 15 seconds and grant access"
print deviceInfo['verification_with_code_uri']
webbrowser.open_new(deviceInfo['verification_with_code_uri'])
time.sleep(15)
## PAUSE HERE

# Once the user has granted us access to objects we requested, we can
# get the basespace access token and start browsing simply by calling updatePriviliges
# on the baseSpaceApi instance.
code = deviceInfo['device_code']
myAPI.updatePrivileges(code)

# As a reference the provided access-token can be obtained from the BaseSpaceApi object
print "\nMy Access-token:"
print myAPI.getAccessToken()


# Let's try and grab all available genomes with our new api! 
allGenomes  = myAPI.getAvailableGenomes()
print "\nGenomes \n" + str(allGenomes)


# If at a later stage we wish to initialize a BaseSpaceAPI object when we already have
# an access-token from a previous sessions, this may simply be done by initializing the BaseSpaceAPI
# object using the key-word AccessToken.
myToken = myAPI.getAccessToken()
myAPI.setAccessToken(myToken)
print "\nA BaseSpaceAPI instance was updated with an access-token: "
print myAPI