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 delete_oauthtokens(self, userEmail): try: import pickle import os if not os.path.isfile(self.file_path): return objectsToPreserve = [] with open(self.file_path, 'rb') as fp: while True: try: oAuthObj = pickle.load(fp) if (userEmail != oAuthObj.userEmail): objectsToPreserve.append(oAuthObj) except EOFError: break with open(self.file_path, 'wb') as fp: for eachObj in objectsToPreserve: pickle.dump(eachObj, fp, pickle.HIGHEST_PROTOCOL) except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while deleting oauthtokens from File ", logging.ERROR, ex) raise ex
def initialize(config_dict=None): try: ZohoOAuth.set_config_values(config_dict) 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] == "")): if (ZohoOAuthConstants.DATABASE_PORT not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PORT] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PORT] = "3306" if (ZohoOAuthConstants.DATABASE_USERNAME not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_USERNAME] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_USERNAME] = "root" if (ZohoOAuthConstants.DATABASE_PASSWORD not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PASSWORD] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PASSWORD] = "" oAuthParams = ZohoOAuthParams.get_instance( ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_ID], ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_SECRET], ZohoOAuth.configProperties[ZohoOAuthConstants.REDIRECT_URL]) ZohoOAuthClient.get_instance(oAuthParams) except Exception as ex: OAuthLogger.add_log( 'Exception occured while reading oauth configurations', logging.ERROR, ex) raise ex
def initialize(): try: try: from .Path import PathIdentifier except ImportError: from Path import PathIdentifier import os #dirSplit=os.path.split(PathIdentifier.get_client_library_root()) #resources_path = os.path.join(dirSplit[0],'resources','oauth_configuration.properties') resources_path = os.path.join( PathIdentifier.get_client_library_root(), 'resources', 'oauth_configuration.properties') filePointer = open(resources_path, "r") ZohoOAuth.configProperties = ZohoOAuth.get_file_content_as_dictionary( filePointer) oAuthParams = ZohoOAuthParams.get_instance( ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_ID], ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_SECRET], ZohoOAuth.configProperties[ZohoOAuthConstants.REDIRECT_URL]) ZohoOAuthClient.get_instance(oAuthParams) except Exception as ex: OAuthLogger.add_log( 'Exception occured while reading oauth configurations', 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 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 deleteOAuthTokens(self, userEmail): try: import pickle try: from .OAuthClient import ZohoOAuth from .OAuthUtility import ZohoOAuthConstants except ImportError: from OAuthClient import ZohoOAuth from OAuthUtility import ZohoOAuthConstants import os os.chdir(ZohoOAuth.configProperties[ ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH]) if not os.path.isfile(ZohoOAuthConstants.PERSISTENCE_FILE_NAME): return objectsToPreserve = [] with open(ZohoOAuthConstants.PERSISTENCE_FILE_NAME, 'rb') as fp: while True: try: oAuthObj = pickle.load(fp) if (userEmail != oAuthObj.userEmail): objectsToPreserve.append(oAuthObj) except EOFError: break with open(ZohoOAuthConstants.PERSISTENCE_FILE_NAME, 'wb') as fp: for eachObj in objectsToPreserve: pickle.dump(eachObj, fp, pickle.HIGHEST_PROTOCOL) except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while deleting oauthtokens from File ", logging.ERROR, ex) raise ex
def getOAuthTokens(self, userEmail): try: connection = self.getDBConnection() cursor = connection.cursor() sqlQuery = "SELECT useridentifier,accesstoken,refreshtoken,expirytime FROM oauthtokens where useridentifier='" + userEmail + "'" cursor.execute(sqlQuery) row_count = 0 for (useridentifier, accesstoken, refreshtoken, expirytime) in cursor: row_count = row_count + 1 try: from .OAuthClient import ZohoOAuthTokens except ImportError: from OAuthClient import ZohoOAuthTokens return ZohoOAuthTokens(refreshtoken, accesstoken, expirytime, useridentifier) if row_count == 0: raise Exception('No rows found for the given user') except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while fetching oauthtokens from DB ", logging.ERROR, ex) raise ex finally: cursor.close() connection.close()
def saveOAuthTokens(self, oAuthTokens): try: self.deleteOAuthTokens(oAuthTokens.userEmail) try: from .OAuthClient import ZohoOAuth from .OAuthUtility import ZohoOAuthConstants except ImportError: from OAuthClient import ZohoOAuth from OAuthUtility import ZohoOAuthConstants import os os.chdir(ZohoOAuth.configProperties[ ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH]) import pickle if os.path.isfile(ZohoOAuthConstants.PERSISTENCE_FILE_NAME): with open(ZohoOAuthConstants.PERSISTENCE_FILE_NAME, 'ab') as fp: pickle.dump(oAuthTokens, fp, pickle.HIGHEST_PROTOCOL) else: with open(ZohoOAuthConstants.PERSISTENCE_FILE_NAME, 'wb') as fp: pickle.dump(oAuthTokens, fp, pickle.HIGHEST_PROTOCOL) except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while saving oauthtokens into File ", logging.ERROR, ex) raise ex
def getOAuthTokens(self, userEmail): try: import pickle try: from .OAuthClient import ZohoOAuth, ZohoOAuthTokens from .OAuthUtility import ZohoOAuthConstants except ImportError: from OAuthClient import ZohoOAuth, ZohoOAuthTokens from OAuthUtility import ZohoOAuthConstants import os os.chdir(ZohoOAuth.configProperties[ ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH]) responseObj = ZohoOAuthTokens(None, None, None, None) if not os.path.isfile(ZohoOAuthConstants.PERSISTENCE_FILE_NAME): return responseObj with open(ZohoOAuthConstants.PERSISTENCE_FILE_NAME, 'rb') as fp: while True: try: oAuthObj = pickle.load(fp) if (userEmail == oAuthObj.userEmail): responseObj = oAuthObj break except EOFError: break return responseObj except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while fetching oauthtokens from File ", logging.ERROR, ex) raise ex
def get_oauthtokens(self, userEmail): try: import os import pickle try: from .OAuthClient import ZohoOAuthTokens except ImportError: from OAuthClient import ZohoOAuthTokens responseObj = None if not os.path.isfile(self.file_path): raise Exception('Token Persistence File is not found') with open(self.file_path, 'rb') as fp: while True: try: oAuthObj = pickle.load(fp) if (userEmail == oAuthObj.userEmail): responseObj = ZohoOAuthTokens( oAuthObj.refreshToken, oAuthObj.accessToken, oAuthObj.expiryTime, oAuthObj.userEmail) break except EOFError: break if responseObj is None: raise Exception('No tokens found for the given user') return responseObj except Exception as ex: import logging OAuthLogger.add_log( "Exception occured while fetching oauthtokens from File ", logging.ERROR, ex) raise ex
def get_oauthtokens(self,userEmail): try: import os import pickle try: from .OAuthClient import ZohoOAuthTokens except ImportError: from OAuthClient import ZohoOAuthTokens responseObj=ZohoOAuthTokens(None,None,None,None) if not os.path.isfile(self.file_path): return responseObj with open(self.file_path, 'rb') as fp: while True: try: oAuthObj=pickle.load(fp) if(userEmail==oAuthObj.userEmail): responseObj=oAuthObj break except EOFError: break return responseObj except Exception as ex: import logging OAuthLogger.add_log("Exception occured while fetching oauthtokens from File ",logging.ERROR,ex) raise ex
def initialize(config_dict=None): try: try: from .Path import PathIdentifier except ImportError: from Path import PathIdentifier import os if (config_dict is None): #dirSplit=os.path.split(PathIdentifier.get_client_library_root()) #resources_path = os.path.join(dirSplit[0],'resources','oauth_configuration.properties') resources_path = os.path.join( PathIdentifier.get_client_library_root(), 'resources', 'oauth_configuration.properties') filePointer = open(resources_path, "r") ZohoOAuth.configProperties = ZohoOAuth.get_file_content_as_dictionary( filePointer) else: ZohoOAuth.set_config_values(config_dict) if (ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.TOKEN_PERSISTENCE_PATH] == ""): if (ZohoOAuthConstants.DATABASE_HOST not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_HOST] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_HOST] = "127.0.0.1" if (ZohoOAuthConstants.DATABASE_PORT not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PORT] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PORT] = "3306" if (ZohoOAuthConstants.DATABASE_USERNAME not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_USERNAME] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_USERNAME] = "root" if (ZohoOAuthConstants.DATABASE_PASSWORD not in ZohoOAuth.configProperties or ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PASSWORD] == ""): ZohoOAuth.configProperties[ ZohoOAuthConstants.DATABASE_PASSWORD] = "" oAuthParams = ZohoOAuthParams.get_instance( ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_ID], ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_SECRET], ZohoOAuth.configProperties[ZohoOAuthConstants.REDIRECT_URL]) ZohoOAuthClient.get_instance(oAuthParams) except Exception as ex: OAuthLogger.add_log( 'Exception occured while reading oauth configurations', logging.ERROR, ex) raise ex
def get_access_token(self,userEmail): try: handler=ZohoOAuth.get_persistence_instance() oAuthTokens=handler.get_oauthtokens(userEmail) try: return oAuthTokens.get_access_token() except Exception as e: OAuthLogger.add_log("Access token expired hence refreshing",logging.INFO,e) oAuthTokens=self.refresh_access_token(oAuthTokens.refreshToken,userEmail) return oAuthTokens.accessToken except Exception as ex: OAuthLogger.add_log("Exception occured while fetching oauthtoken from db",logging.ERROR,ex) raise ex
def delete_oauthtokens(self,userEmail): try: connection=self.getDBConnection() cursor=connection.cursor() #sqlQuery="DELETE FROM oauthtokens where useridentifier='"+userEmail+"'" sqlQuery="DELETE FROM oauthtokens where useridentifier=%s" cursor.execute(sqlQuery,(userEmail,)) connection.commit() except Exception as ex: import logging OAuthLogger.add_log("Exception occured while deleting oauthtokens from DB ",logging.ERROR,ex) raise ex finally: cursor.close() connection.close()
def save_oauthtokens(self,oAuthTokens): try: self.delete_oauthtokens(oAuthTokens.userEmail) import os import pickle if os.path.isfile(self.file_path): with open(self.file_path, 'ab') as fp: pickle.dump(oAuthTokens, fp, pickle.HIGHEST_PROTOCOL) else: with open(self.file_path, 'wb') as fp: pickle.dump(oAuthTokens, fp, pickle.HIGHEST_PROTOCOL) except Exception as ex: import logging OAuthLogger.add_log("Exception occured while saving oauthtokens into File ",logging.ERROR,ex) raise ex
def save_oauthtokens(self,oAuthTokens): try: self.delete_oauthtokens(oAuthTokens.userEmail) connection=self.getDBConnection() cursor=connection.cursor() #sqlQuery="INSERT INTO oauthtokens(useridentifier,accesstoken,refreshtoken,expirytime) VALUES('"+oAuthTokens.userEmail+"','"+oAuthTokens.accessToken+"','"+oAuthTokens.refreshToken+"',"+oAuthTokens.expiryTime+")"; sqlQuery="INSERT INTO oauthtokens(useridentifier,accesstoken,refreshtoken,expirytime) VALUES(%s,%s,%s,%s)"; data=(oAuthTokens.userEmail,oAuthTokens.accessToken,oAuthTokens.refreshToken,oAuthTokens.expiryTime) cursor.execute(sqlQuery,data) connection.commit() except Exception as ex: import logging OAuthLogger.add_log("Exception occured while saving oauthtokens into DB ",logging.ERROR,ex) raise ex finally: cursor.close() connection.close()
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 initialize(): try: ZohoOAuth.configProperties = { 'client_id': os.environ['CLIENT_ID'], 'client_secret': os.environ['CLIENT_SECRET'], 'redirect_uri': os.environ['REDIRECT_URI'], 'accounts_url': os.environ['ACCOUNTS_URL'], 'token_persistence_path': os.environ['TOKEN_PERSISTENCE_PATH'], 'access_type': os.environ['ACCESS_TYPE'] } oAuthParams = ZohoOAuthParams.get_instance( ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_ID], ZohoOAuth.configProperties[ZohoOAuthConstants.CLIENT_SECRET], ZohoOAuth.configProperties[ZohoOAuthConstants.REDIRECT_URL]) ZohoOAuthClient.get_instance(oAuthParams) except Exception as ex: OAuthLogger.add_log( 'Exception occured while reading oauth configurations', logging.ERROR, ex) raise ex