def checkstatic(self, serverConfig): staticPath = serverConfig['STATIC_PATH'] from os.path import exists from os import mkdir if exists(staticPath): from utils.showMessage import showGood showGood( goodRule="Static Found", Message= f"The static path your provided '{staticPath}' has been found") else: from utils.showMessage import showError, askForInput, showGood showError( exceptionRule="Path Error", Message= "We couldn't validate the static path you provided. make sure you're running it from the home dir." ) userInput = askForInput( userMessage= "If you're sure you did run this tool from the home dir, would you like to create the static folder? " ) if userInput.lower() == "y" or userInput.lower() == "yes": mkdir(staticPath) showGood( goodRule="Folder Created", Message=f"The static folder '{staticPath}' has been created" ) else: pass
def detectFunctions(self, lineOfCode, templateVariables={}): detectPattern = r"\{\{.*\}\}\," templateSyntaxDetected = re.search(detectPattern, lineOfCode) if templateSyntaxDetected != None: codeSyntax = templateSyntaxDetected.group() if "," not in codeSyntax: showError(exceptionRule="Template Error", Message="There's no comma's seprating your template syntax can result in parsing issues, please use ',' after every syntax") return False else: tempList = codeSyntax.split(',') syntaxList = [] duplicateList = [] for singleItem in tempList: singleItem = singleItem.strip() if singleItem not in duplicateList and singleItem != '': syntaxList.append(singleItem) duplicateList.append(singleItem) return syntaxList else: return []
def readLogs(): if exists(LOGS_PATH): fileContent = open(f"{LOGS_PATH}/server.log", 'r').read() return fileContent else: showError( exceptionRule="Paths Error", Message= "WEngine couldn't find the LOGS_PATH, please double check it")
def cleanServerLogs(): if exists(LOGS_PATH): with open(f"{LOGS_PATH}/server.log", 'w') as logsFile: logsFile.write('') logsFile.close() return True else: showError( exceptionRule="Paths Error", Message= "WEngine couldn't find the LOGS_PATH, please double check it") return False
def returnRenderedTemplate(filePath, responseHeaders={}, responseCode=200, templateVariables={}): global detectedStrings, detectedFunctions, replacedFileContent filePath = f"{TEMPLATES_PATH}/{filePath}" requestFileContent = readFileByLines(filePath) realFileContent = readFile(filePath) if not requestFileContent: return '500 Internal Server Error', {}, 500 else: Parser = templatesParser() for singleLine in requestFileContent: detectedStrings += Parser.detectStrings(lineOfCode=singleLine) detectedFunctions += Parser.detectFunctions(lineOfCode=singleLine) if len(detectedStrings) != 0: for dString in detectedStrings: dRealString = dString[2:][:-2].strip() try: userString = templateVariables[dRealString] replacedFileContent = realFileContent.replace(f"{dString},", str(userString)) realFileContent = replacedFileContent except Exception: showError(exceptionRule="Template Error", Message=f"You're using an undefined variable '{dRealString}' on your template") exit() if len(detectedFunctions) != 0: for dFunction in detectedFunctions: dRealFunction = dFunction[2:][:-2].strip() charactersList = [] for singleCharacter in dRealFunction: if singleCharacter != "(": charactersList.append(singleCharacter) else: break functionName = ''.join(charactersList) if functionName in __FUNCTIONS__: parserFunction = getattr(Parser, functionName) responseContent = parserFunction(dRealFunction, templateVariables) replacedFileContent = realFileContent.replace(f"{dFunction},", responseContent) realFileContent = replacedFileContent else: showError(exceptionRule="Template Error", Message=f"You're using a template function '{dRealFunction}' that doesn't exists") exit() return replacedFileContent, responseHeaders, responseCode
def writeLogs(clientIP, userAgent, endpointVisited, responseCode, requestMethod): if exists(LOGS_PATH): currentDate = datetime.now() dateString = f"{currentDate.year}/{currentDate.month}/{currentDate.day}" writtenMessage = f"[{dateString}] [{clientIP}] - [{userAgent}]: {requestMethod} {endpointVisited} - {responseCode}\n" with open(f"{LOGS_PATH}/server.log", 'a') as logsFile: logsFile.write(writtenMessage) logsFile.close() else: showError( exceptionRule="Paths Error", Message= "WEngine couldn't find the LOGS_PATH, please double check it")
def removeqoutes(self, templateSyntax, templateVariables={}): syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) if Mode == "variable": try: variableValue = templateVariables[syntaxArguments[1]] variableValue = variableValue.replace('"', '').replace("'", '') return variableValue except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined") return "" else: replaceString = syntaxArguments[1] replaceString = replaceString.replace('"', '').replace("'", '') return replaceString
def urlencode(self, templateSyntax, templateVariables={}): syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) if Mode == "variable": try: variableValue = templateVariables[syntaxArguments[1]] variableValue = quote(variableValue) return variableValue except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined") return "" else: replaceString = syntaxArguments[1] replaceString = urlencode(replaceString) return replaceString
def mainFunction(Options): ''' the mode should be checked before everything. if there's no mood the tool should run the server but if there's a mode. it should check it. then use modules with it if modules is used but i's still on development process ''' try: userMode = Options.mode modeClass = globals()[userMode]() modeFunction = getattr(modeClass , userMode) applicationConfig = buildConfig() modeFunction(applicationConfig) except Exception as e: showError(exceptionRule="Mode Error" , Message=f"The mode {userMode} doesn't exists on the classes")
def time(self, templateSyntax, templateVariables={}): syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) currentTime = strftime(f"%H,%M,%S", gmtime()) if Mode == "variable": try: variableValue = templateVariables[syntaxArguments[1]] variableValue = currentTime.replace(',', variableValue) return variableValue except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined") return "" else: replaceString = syntaxArguments[1] replaceString = currentTime.replace(',', replaceString) return replaceString
def system(self, templateSyntax, templateVariables={}): if ALLLOW_TEMPLATE_SYSTEM: syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) if Mode == "variable": try: execValue = templateVariables[syntaxArguments[1]] cmdResults = popen(execValue).read() return cmdResults except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined") return "" else: cmdResults = poepn(syntaxArguments[1]).read() return cmdResults else: return ""
def exec(self, templateSyntax, templateVariables={}): if ALLOW_TEMPLATE_EXEC: syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) if Mode == "variable": try: execValue = templateVariables[syntaxArguments[1]] exec(execValue) return "" except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined.") return "" else: exec(syntaxArguments[1]) return "" else: return ""
def date(self, templateSyntax, templateVariables={}): syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) currentDate = datetime.now() dateString = f"{currentDate.year},{currentDate.month},{currentDate.day}" if Mode == "variable": try: variableValue = templateVariables[syntaxArguments[1]] variableValue = dateString.replace(',', variableValue) return variableValue except Exception: showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined") return "" else: replaceString = syntaxArguments[1] replaceString = dateString.replace(',', replaceString) return replaceString
def securemarkdown(self, templateSyntax, templateVariables={}): detectPattern = r"securemarkdown\((.*|)\)" detectFunction = re.search(detectPattern, templateSyntax) if detectFunction != None: functionsArgument = detectFunction.group()[14:][1:][:-1] functionsArgument = functionsArgument.replace('"', '').replace( "'", '').strip() try: replaceString = templateVariables[functionsArgument] rString = secureMarkdown(mdSyntax=replaceString) return rString except Exception as e: showError( exceptionRule="Template Error", Message= "You're using a template variable that doesn't exists") return "" else: return ""
def removetags(self, templateSyntax, templateVariables={}): detectPattern = r"removetags\((.*|)\)" detectFunction = re.search(detectPattern, templateSyntax) if detectFunction != None: functionsArgument = detectFunction.group()[10:][1:][:-1] functionsArgument = functionsArgument.replace('"', '').replace( "'", '').strip() try: replaceString = templateVariables[functionsArgument] rString = replaceString.replace('<', '').replace('>', '') return rString except Exception: showError( exceptionRule="Template Error", Message= "You're using a template variable that doesn't exists") return "" else: return ""
def callHanlder(handlerName, requestHeaders): modulePath = f"handlers.{handlerName}".replace('.py', '') handlerFunction = importlib.import_module(modulePath) responseContent, responseHeaders, responseCode = handlerFunction.Handler( requestHeaders) if type(responseContent) != str: showError( exceptionRule="Handler Error", Message= f"The response content the {handlerName} is returning isn't a valid string" ) exit() if type(responseHeaders) != dict: showError( exceptionRule="Handler Error", Message= f"The response headers the {handlerName} is returning isn't a valid dict" ) exit() if type(responseCode) != int: showError( exceptionRule="Handler Error", Message= f"The response code the {handlerName} is returning isn't a valid integar" ) exit() return responseContent, responseHeaders, responseCode
def migrate(self, serverConfig): from utils.dbConnections import createDB, createTable from utils.showMessage import showGood, showError from config.db import __DEFAULT_DB_NAME__, __DEFAULT_DB_TABLE__, __DEFAULT_DB_CONFIG__ try: createDB(dbname=__DEFAULT_DB_NAME__) showGood( goodRule="DB created", Message=f"{__DEFAULT_DB_NAME__} has been created successfully") except Exception as e: showError(exceptionRule="DB error", Message=f"{str(e)}") try: createTable(dbname=__DEFAULT_DB_NAME__, tablename=__DEFAULT_DB_TABLE__, dbConfig=__DEFAULT_DB_CONFIG__) showGood( goodRule="DB updated", Message=f"{__DEFAULT_DB_NAME__} has been updated successfully") except Exception as e: showError(exceptionRule="DB error", Message=f"{str(e)}")
def createuser(self, serverConfig): from utils.dbConnections import appendData, getdbname, search from utils.showMessage import showGood, askForInput, coloredMessage, showError from config.db import __DEFAULT_DB_NAME__, __DEFAULT_DB_TABLE__ from getpass import getpass from hashlib import sha256 from os.path import exists if exists(getdbname(__DEFAULT_DB_NAME__)): FIRST_NAME = askForInput("First name: ") SECOND_NAME = askForInput("Second name: ") EMAIL = askForInput("Email: ") PHONE = askForInput("Phone: ") __DEFAULT_DB_USERNAME__ = askForInput("Username: "******"DB error", Message="The username you selected already exists") exit() DB_PASSWORD = getpass(coloredMessage('Password: '******'blue')) DB_PASSWORD_AGAIN = getpass( coloredMessage('Password Confirmation: ', 'blue')) if DB_PASSWORD == DB_PASSWORD_AGAIN: pass else: showError(exceptionRule="Password Error", Message="The passwords you entered doesn't match") exit() PASSWORD_BYTES = DB_PASSWORD.encode('UTF-8') PASSWORD_HASH = sha256(PASSWORD_BYTES).hexdigest() PASSWORD_HASH = str(PASSWORD_HASH) appendData(dbname=__DEFAULT_DB_NAME__, tablename=__DEFAULT_DB_TABLE__, dbConfig=[ FIRST_NAME, SECOND_NAME, __DEFAULT_DB_USERNAME__, PASSWORD_HASH, EMAIL, PHONE, None ]) showGood( goodRule="\nUser created", Message= f"{__DEFAULT_DB_USERNAME__} has been added into the database: {__DEFAULT_DB_NAME__}" ) else: showError( exceptionRule="Path Error", Message= "The database hasn't been created, please run migrate to create it." )
def readFileByLines(filePath): try: filePath = filePath.replace('../', '') if not ALLOW_SYMLINKS: if islink(filePath): showError(exceptionRule="File Error", Message="Symlink is disabled while the user is trying to read a symlink file") return False else: fileContent = open(filePath, 'r') fileContent = fileContent.readlines() return fileContent else: fileContent = open(filePath, 'r') fileContent = fileContent.readlines() return fileContent except Exception: if isdir(filePath): return True else: showError(exceptionRule="File Error", Message=f"There's an error trying to open {filePath}") return False
def base32(self, templateSyntax, templateVariables={}): detectPattern = r"base32\((.*|)\)" detectFunction = re.search(detectPattern, templateSyntax) if detectFunction != None: functionsArgument = detectFunction.group()[6:][1:][:-1] functionsArgument = functionsArgument.replace('"', '').replace( "'", '').strip() try: replaceString = templateVariables[functionsArgument] rString = base32Encode(encodeString=replaceString) if not rString: return "" else: return rString except Exception as e: showError( exceptionRule="Template Error", Message= "You're using a template variable that doesn't exists") return "" else: return ""
def url_to(self, templateSyntax, templateVariables={}): syntaxArguments = self.parseArguments(templateSyntax) Mode = self.detectMode(syntaxArguments[0]) if Mode == "variable": try: variableValue = templateVariables[syntaxArguments[2]] basePath = urlModes[syntaxArguments[1]] basePath += f"{variableValue}" except Exception: showError(exceptionRule="Mode/Variable Error", Message="There's an error with the mode or the variable, check both of them.") return "" else: try: basePath = urlModes[syntaxArguments[1]] basePath += f"{syntaxArguments[2]}" except Exception: showError(exceptionRule="Mode Error", Message="There's an error with your mode, double check it.") return "" basePath = basePath.replace('//', '/') return basePath
def corsOrigin(requestHeaders): if type(CORS_ORIGIN) == str: try: originHeader = requestHeaders['origin'] if not originHeader.strip().startswith( 'http://') and not originHeader.strip().startswith( 'https://'): if validateCors(originHeader, CORS_ORIGIN): originHeader = f"http://{originHeader.strip()}/" return originHeader else: originHeader = f"http://{CORS_ORIGIN.strip()}/" return originHeader else: if validateCors(originHeader, CORS_ORIGIN): originHeader = originHeader.strip() return originHeader else: originHeader = CORS_ORIGIN.strip() return originHeader except Exception: # there's no origin header. default one is the one on the server # so we need to use the config from here if not CORS_ORIGIN.strip().startswith( 'http://') and not CORS_ORIGIN.strip().startswith( 'https://'): originHeader = f"http://{CORS_ORIGIN.strip()}/" return originHeader else: originHeader = originHeader.strip() return originHeader elif type(CORS_ORIGIN) == list: # there's a full list of cors in thus case # two validations are required here, can't use the old method # string validation then validateCors function. try: originHeader = requestHeaders['origin'] for singleOrigin in CORS_ORIGIN: if validateCors(originHeader, singleOrigin): if not originHeader.strip().startswith( 'http://') and not originHeader.strip().startswith( 'https://'): originHeader = originHeader.strip() originHeader = f"http://{originHeader}/" return originHeader else: originHeader = originHeader.strip() return originHeader else: pass originHeader = CORS_ORIGIN[0].strip() if not originHeader.startswith( 'http://') and not originHeader.startswith('https://'): originHeader = f"http://{originHeader}/" return originHeader else: originHeader = originHeader return originHeader except Exception: originHeader = CORS_ORIGIN[0].strip() if not originHeader.startswith( 'http://') and not originHeader.startswith('https://'): originHeader = f"http://{originHeader}/" return originHeader else: originHeader = originHeader return originHeader else: showError( exceptionRule="Config Error", Message= "Invalid Cors origin on the settings, it can't be bool/int/float only str and list" )