def initialize(isToInitializeOAuth, config_dict=None): if (config_dict is None): raise ZohoOAuthException( "Configuration dictionary is mandatory to initialize RestClient" ) mandatory_keys = [ ZohoOAuthConstants.CLIENT_ID, ZohoOAuthConstants.CLIENT_SECRET, ZohoOAuthConstants.REDIRECT_URL, APIConstants.CURRENT_USER_EMAIL ] try: from .RestClient import ZCRMRestClient except ImportError: from RestClient import ZCRMRestClient for key in mandatory_keys: if (key not in config_dict): if (key != APIConstants.CURRENT_USER_EMAIL or ZCRMRestClient. get_instance().get_current_user_email_id() == None): raise ZohoOAuthException(key + ' is mandatory') elif (key in config_dict and (config_dict[key] is None or config_dict[key] == "")): if (key != APIConstants.CURRENT_USER_EMAIL or ZCRMRestClient. get_instance().get_current_user_email_id() == None): raise ZohoOAuthException(key + ' value is missing') ZCRMConfigUtil.set_config_values(config_dict) if (isToInitializeOAuth): ZohoOAuth.initialize(config_dict)
def generate_access_token(self, grantToken): if (grantToken == None): raise ZohoOAuthException("Grant token not provided!") try: connector = self.get_connector(ZohoOAuth.get_token_url()) connector.add_http_request_params( ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.GRANT_TYPE_AUTH_CODE) connector.add_http_request_params(ZohoOAuthConstants.CODE, grantToken) connector.set_http_request_method( ZohoOAuthConstants.REQUEST_METHOD_POST) response = connector.trigger_request() responseJSON = response.json() if (ZohoOAuthConstants.ACCESS_TOKEN in responseJSON): oAuthTokens = self.get_tokens_from_json(responseJSON) oAuthTokens.set_user_email( self.get_user_email_from_iam(oAuthTokens.accessToken)) ZohoOAuth.get_persistence_instance().save_oauthtokens( oAuthTokens) return oAuthTokens else: raise ZohoOAuthException( "Exception occured while fetching accesstoken from Grant Token;Response is:" + str(responseJSON)) except ZohoOAuthException as ex: OAuthLogger.add_log( "Exception occured while generating access token", logging.ERROR, ex) raise ex
def refresh_access_token(self, refreshToken, userEmail): if (refreshToken == None): raise ZohoOAuthException("Refresh token not provided!") try: connector = self.get_connector(ZohoOAuth.get_refresh_token_url()) connector.add_http_request_params( ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.GRANT_TYPE_REFRESH) connector.add_http_request_params(ZohoOAuthConstants.REFRESH_TOKEN, refreshToken) connector.set_http_request_method( ZohoOAuthConstants.REQUEST_METHOD_POST) response = connector.trigger_request() responseJSON = response.json() if (ZohoOAuthConstants.ACCESS_TOKEN in responseJSON): oAuthTokens = self.get_tokens_from_json(responseJSON) oAuthTokens.set_user_email(userEmail) oAuthTokens.refreshToken = refreshToken ZohoOAuth.get_persistence_instance().save_oauthtokens( oAuthTokens) return oAuthTokens except ZohoOAuthException as ex: OAuthLogger.add_log( "Exception occured while refreshing oauthtoken", logging.ERROR, ex) raise ex
def get_persistence_instance(): if((ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH]=="") and \ (ZohoOAuthConstants.CUSTOM_PERSISTENCE_HANDLER_PATH not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ZohoOAuthConstants.CUSTOM_PERSISTENCE_HANDLER_PATH] == "")): return ZohoOAuthPersistenceHandler() elif((ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH in ZohoOAuth.configProperties) and ZohoOAuth.configProperties[ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH] != ""): return ZohoOAuthPersistenceFileHandler() else: try: from sys import path import importlib custompersistence_handler = ZohoOAuth.configProperties[ZohoOAuthConstants.CUSTOM_PERSISTENCE_HANDLER_PATH] custompersistence_classname = ZohoOAuth.configProperties[ZohoOAuthConstants.CUSTOM_PERSISTENCE_HANDLER_CLASS] if custompersistence_classname == "": raise ZohoOAuthException("Token Persistence Class must be given.") splitter = "/" if "/" in custompersistence_handler else "\\" custompersistence_directory = custompersistence_handler.strip(custompersistence_handler.split(splitter)[-1]).rstrip(splitter) path.append(custompersistence_directory) custompersistence_modulename = custompersistence_handler.split(splitter)[-1].rstrip(".py") try: custompersistence_module = importlib.import_module(custompersistence_modulename) custompersistence_class = getattr(custompersistence_module, custompersistence_classname) custompersistence_instance = custompersistence_class() return custompersistence_instance except Exception as e: raise e except Exception as ex: OAuthLogger.add_log("Exception occured while fetching instance for Custom DB Persistence", logging.ERROR, ex) raise ex
def get_client_instance(): oauth_client_ins = ZohoOAuthClient.get_instance() if (oauth_client_ins is None): raise ZohoOAuthException( 'ZohoOAuth.initialize() must be called before this') return oauth_client_ins
def initialize(isToInitializeOAuth, config_dict=None): mandatory_keys = [ ZohoOAuthConstants.CLIENT_ID, ZohoOAuthConstants.CLIENT_SECRET, ZohoOAuthConstants.REDIRECT_URL, APIConstants.CURRENT_USER_EMAIL ] import os try: from .Path import PathIdentifier from .RestClient import ZCRMRestClient except ImportError: from Path import PathIdentifier from RestClient import ZCRMRestClient if (config_dict is None): resources_path = os.path.join( PathIdentifier.get_client_library_root(), 'resources', 'configuration.properties') filePointer = open(resources_path, "r") ZCRMConfigUtil.config_prop_dict = CommonUtil.get_file_content_as_dictionary( filePointer) else: for key in mandatory_keys: if (key not in config_dict): if (key != APIConstants.CURRENT_USER_EMAIL or ZCRMRestClient.get_instance(). get_current_user_email_id() is None): raise ZohoOAuthException(key + ' is mandatory') elif (key in config_dict and (config_dict[key] is None or config_dict[key] == "")): if (key != APIConstants.CURRENT_USER_EMAIL or ZCRMRestClient.get_instance(). get_current_user_email_id() is None): raise ZohoOAuthException(key + ' value is missing') ZCRMConfigUtil.set_config_values(config_dict) if (isToInitializeOAuth): ZohoOAuth.initialize(config_dict)
def get_user_email_from_iam(self, accessToken): header = { ZohoOAuthConstants.AUTHORIZATION: (ZohoOAuthConstants.OAUTH_HEADER_PREFIX + accessToken) } connector = ZohoOAuthHTTPConnector.get_instance( ZohoOAuth.get_user_info_url(), None, header, None, ZohoOAuthConstants.REQUEST_METHOD_GET) response = connector.trigger_request() try: response_json = response.json() if 'Email' in response_json: return response.json()['Email'] except ValueError as err: raise ZohoOAuthException( 'Exception while fetching User email from access token, Make sure AAAserver.profile.Read scope is included while generating the Grant token' )
def get_refresh_token_user_email(self, grant_token): """ :param code: :return: """ try: params = { 'code': grant_token, 'client_id': ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_ID], 'client_secret': ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_SECRET], 'redirect_uri': ZohoOAuth.configProperties[ZohoOAuthConstants.REDIRECT_URL], 'grant_type': 'authorization_code' } http_connector = ZohoOAuthHTTPConnector.get_instance( ZohoOAuth.get_token_url(), params=params, method=ZohoOAuthConstants.REQUEST_METHOD_POST) response = http_connector.trigger_request() responseJSON = response.json() if (ZohoOAuthConstants.ACCESS_TOKEN in responseJSON): oAuthTokens = self.get_tokens_from_json(responseJSON) oAuthTokens.set_user_email( self.get_user_email_from_iam(oAuthTokens.accessToken)) ZohoOAuth.get_persistence_instance().saveOAuthTokens( oAuthTokens) return oAuthTokens.refreshToken, oAuthTokens.userEmail else: raise ZohoOAuthException( "Exception occured while fetching refresh token from Grant Token; Response is:" + str(responseJSON)) except ZohoOAuthException as ex: OAuthLogger.add_log( "Exception occured while generating refresh token", logging.ERROR, ex) raise ex
def get_access_token(self): if (self.expiryTime - self.get_current_time_in_millis()) > 5000: return self.accessToken else: raise ZohoOAuthException("Access token got expired!")