prototype in progress

merge-requests/1/merge
Ivan Maslov 2 years ago
parent 5ece90166f
commit 23b17e0d1f

@ -7,6 +7,7 @@
# self.OpenRPAResponseDict = lResponseDict # self.OpenRPAResponseDict = lResponseDict
#from http.client import HTTPException #from http.client import HTTPException
from email import header
from http.server import BaseHTTPRequestHandler, HTTPServer from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn from socketserver import ThreadingMixIn
import threading import threading
@ -48,6 +49,10 @@ from pydantic import BaseModel
import uvicorn import uvicorn
import io
from starlette.responses import StreamingResponse
gCacheDict = {} gCacheDict = {}
@ -111,8 +116,10 @@ def UserAccessCheckBefore(inMethod, inRequest):
lAuthToken = inRequest.OpenRPA["AuthToken"] lAuthToken = inRequest.OpenRPA["AuthToken"]
#go next if user is identified #go next if user is identified
lUserDict = None lUserDict = None
print(f"lAuthToken: {lAuthToken}")
if lAuthToken: if lAuthToken:
lUserDict = gSettingsDict["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken] lUserDict = gSettingsDict["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]
print(f"lUserDict: {lUserDict}")
#pdb.set_trace() #pdb.set_trace()
######################################## ########################################
######################################## ########################################
@ -189,6 +196,7 @@ class HTTPRequestOld():
mRequest:Request = None mRequest:Request = None
mResponse:Response = None mResponse:Response = None
OpenRPA: dict = {} OpenRPA: dict = {}
headers={}
def __init__(self,inRequest,inResponse,inAuthDict): def __init__(self,inRequest,inResponse,inAuthDict):
self.mRequest = inRequest self.mRequest = inRequest
@ -200,6 +208,7 @@ class HTTPRequestOld():
self.OpenRPA["Domain"] = None self.OpenRPA["Domain"] = None
self.OpenRPA["User"] = None self.OpenRPA["User"] = None
else: self.OpenRPA = inAuthDict else: self.OpenRPA = inAuthDict
self.headers=inRequest.headers
# Def to check User Role access grants # Def to check User Role access grants
def UACClientCheck(self, inRoleKeyList): # Alias def UACClientCheck(self, inRoleKeyList): # Alias
@ -387,16 +396,20 @@ class HTTPRequestOld():
def do_GET(self, inBodyStr): def do_GET(self, inBodyStr):
try: try:
gSettingsDict = __Orchestrator__.GSettingsGet() gSettingsDict = __Orchestrator__.GSettingsGet()
try:
self.OpenRPA["DefUserRoleAccessAsk"]=self.UserRoleAccessAsk # Alias for def self.OpenRPA["DefUserRoleAccessAsk"]=self.UserRoleAccessAsk # Alias for def
self.OpenRPA["DefUserRoleHierarchyGet"]=self.UserRoleHierarchyGet # Alias for def self.OpenRPA["DefUserRoleHierarchyGet"]=self.UserRoleHierarchyGet # Alias for def
except Exception as e:
pass
# Prepare result dict # Prepare result dict
lResponseDict = {"Headers": {}, "SetCookies": {}, "Body": b"", "StatusCode": None} lResponseDict = {"Headers": {}, "SetCookies": {}, "Body": b"", "StatusCode": None, "BodyIsText":True}
self.OpenRPAResponseDict = lResponseDict self.OpenRPAResponseDict = lResponseDict
#Check the user access (if flag, UAC) #Check the user access (if flag, UAC)
#################################### ####################################
lFlagUserAccess = True lFlagUserAccess = True
#If need user authentication #If need user authentication
if gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False): if gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False):
if self.OpenRPA["AuthToken"] != None:
lFlagUserAccess = UserAccessCheckBefore("GET", self) lFlagUserAccess = UserAccessCheckBefore("GET", self)
###################################### ######################################
if lFlagUserAccess: if lFlagUserAccess:
@ -431,17 +444,21 @@ class HTTPRequestOld():
try: try:
gSettingsDict = __Orchestrator__.GSettingsGet() gSettingsDict = __Orchestrator__.GSettingsGet()
lL = gSettingsDict["Logger"] lL = gSettingsDict["Logger"]
try:
self.OpenRPA["DefUserRoleAccessAsk"]=self.UserRoleAccessAsk # Alias for def self.OpenRPA["DefUserRoleAccessAsk"]=self.UserRoleAccessAsk # Alias for def
self.OpenRPA["DefUserRoleHierarchyGet"]=self.UserRoleHierarchyGet # Alias for def self.OpenRPA["DefUserRoleHierarchyGet"]=self.UserRoleHierarchyGet # Alias for def
except Exception as e:
pass
# Prepare result dict # Prepare result dict
#pdb.set_trace() #pdb.set_trace()
lResponseDict = {"Headers": {}, "SetCookies":{}, "Body": b"", "StatusCode": None} lResponseDict = {"Headers": {}, "SetCookies": {}, "Body": b"", "StatusCode": None, "BodyIsText":True}
self.OpenRPAResponseDict = lResponseDict self.OpenRPAResponseDict = lResponseDict
#Check the user access (if flag) #Check the user access (if flag)
#################################### ####################################
lFlagUserAccess = True lFlagUserAccess = True
#If need user authentication #If need user authentication
if gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False): if gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False):
if self.OpenRPA["AuthToken"] != None:
lFlagUserAccess = UserAccessCheckBefore("POST", self) lFlagUserAccess = UserAccessCheckBefore("POST", self)
###################################### ######################################
if lFlagUserAccess: if lFlagUserAccess:
@ -496,6 +513,7 @@ def IdentifyAuthorize(inRequest:Request, inResponse:Response,
inCookiesStr: Union[str, None] = Header(default=None,alias="Cookie"), inCookiesStr: Union[str, None] = Header(default=None,alias="Cookie"),
inAuthorizationStr: Union[str, None] = Header(default="",alias="Authorization")): inAuthorizationStr: Union[str, None] = Header(default="",alias="Authorization")):
lResult={"Domain": "", "User": ""} lResult={"Domain": "", "User": ""}
print("IdentifyAuthorize")
###################################### ######################################
#Way 1 - try to find AuthToken #Way 1 - try to find AuthToken
lCookies = cookies.SimpleCookie(inCookiesStr) # inRequest.headers.get("Cookie", "") lCookies = cookies.SimpleCookie(inCookiesStr) # inRequest.headers.get("Cookie", "")
@ -511,14 +529,14 @@ def IdentifyAuthorize(inRequest:Request, inResponse:Response,
lResult["User"] = gSettingsDict["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["User"] lResult["User"] = gSettingsDict["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["User"]
#Set auth token #Set auth token
mOpenRPA={} mOpenRPA={}
mOpenRPA["AuthToken"] = lAuthToken mOpenRPA["AuthToken"] = lCookieAuthToken
mOpenRPA["Domain"] = lResult["Domain"] mOpenRPA["Domain"] = lResult["Domain"]
mOpenRPA["User"] = lResult["User"] mOpenRPA["User"] = lResult["User"]
mOpenRPA["IsSuperToken"] = gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False) mOpenRPA["IsSuperToken"] = gSettingsDict.get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False)
return mOpenRPA return mOpenRPA
###################################### ######################################
#Way 2 - try to logon #Way 2 - try to logon
elif len(lHeaderAuthorization) == 2: if len(lHeaderAuthorization) == 2:
llHeaderAuthorizationDecodedUserPasswordList = base64.b64decode(lHeaderAuthorization[1]).decode("utf-8").split( llHeaderAuthorizationDecodedUserPasswordList = base64.b64decode(lHeaderAuthorization[1]).decode("utf-8").split(
":") ":")
lUser = llHeaderAuthorizationDecodedUserPasswordList[0] lUser = llHeaderAuthorizationDecodedUserPasswordList[0]
@ -555,32 +573,49 @@ def IdentifyAuthorize(inRequest:Request, inResponse:Response,
###################################### ######################################
else: else:
raise HTTPException(status_code=401, detail="here is the details", headers={'Content-type':'text/html', 'WWW-Authenticate':'Basic'}) raise HTTPException(status_code=401, detail="here is the details", headers={'Content-type':'text/html', 'WWW-Authenticate':'Basic'})
return True
def BackwardCompatibityWrapperAuth(inRequest:Request, inResponse:Response, inBodyStr:str = Body(...), def BackwardCompatibityWrapperAuth(inRequest:Request, inResponse:Response, inBodyStr:str = Body(""),
inAuthDict:bool=Depends(IdentifyAuthorize)): # Old from v1.3.1 (updated to FastAPI) inAuthDict:dict=Depends(IdentifyAuthorize)): # Old from v1.3.1 (updated to FastAPI)
print(f"{inRequest.url.path}, inAuthDict:{inAuthDict}")
lHTTPRequest = HTTPRequestOld(inRequest=inRequest, inResponse=inResponse, inAuthDict=inAuthDict) lHTTPRequest = HTTPRequestOld(inRequest=inRequest, inResponse=inResponse, inAuthDict=inAuthDict)
lHTTPRequest.path = inRequest.url.path
lHTTPRequest.body = inBodyStr
threading.current_thread().request = lHTTPRequest threading.current_thread().request = lHTTPRequest
lResult = lHTTPRequest.do_GET(inBodyStr=inBodyStr) lResult = lHTTPRequest.do_GET(inBodyStr=inBodyStr)
if lResult is None: if lResult is None:
lResult = lHTTPRequest.do_POST(inBodyStr=inBodyStr) lResult = lHTTPRequest.do_POST(inBodyStr=inBodyStr)
return lResult #if lHTTPRequest.OpenRPAResponseDict['BodyIsText']==True: return lResult.decode("utf8")
#else: return StreamingResponse(io.BytesIO(lResult), media_type="image/png")
if lHTTPRequest.OpenRPAResponseDict["Headers"]["Content-type"] != None:
return StreamingResponse(io.BytesIO(lResult), media_type=lHTTPRequest.OpenRPAResponseDict["Headers"]["Content-type"])
def BackwardCompatibityWrapperNoAuth(inRequest:Request, inResponse:Response, inBodyStr:str = Body(...)): # Old from v1.3.1 (updated to FastAPI) def BackwardCompatibityWrapperNoAuth(inRequest:Request, inResponse:Response, inBodyStr:str = Body("")): # Old from v1.3.1 (updated to FastAPI)
print(f"{inRequest.url.path}, BackwardCompatibityWrapperNoAuth")
lHTTPRequest = HTTPRequestOld(inRequest=inRequest, inResponse=inResponse, inAuthDict=None) lHTTPRequest = HTTPRequestOld(inRequest=inRequest, inResponse=inResponse, inAuthDict=None)
lHTTPRequest.path = inRequest.url.path
lHTTPRequest.body = inBodyStr
threading.current_thread().request = lHTTPRequest threading.current_thread().request = lHTTPRequest
lResult = lHTTPRequest.do_GET(inBodyStr=inBodyStr) lResult = lHTTPRequest.do_GET(inBodyStr=inBodyStr)
#print(f"RESULT VALUE: {lResult}")
if lResult is None: if lResult is None:
lResult = lHTTPRequest.do_POST(inBodyStr=inBodyStr) lResult = lHTTPRequest.do_POST(inBodyStr=inBodyStr)
return lResult.decode("utf8") #if lHTTPRequest.OpenRPAResponseDict['BodyIsText']==True: return lResult.decode("utf8")
#else: return StreamingResponse(io.BytesIO(lResult), media_type="image/png")
if lHTTPRequest.OpenRPAResponseDict["Headers"]["Content-type"] != None:
return StreamingResponse(io.BytesIO(lResult), media_type=lHTTPRequest.OpenRPAResponseDict["Headers"]["Content-type"])
def InitFastAPI(): def InitFastAPI():
global gSettingsDict global gSettingsDict
global app global app
ServerSettings.SettingsUpdate(gSettingsDict)
lL = gSettingsDict.get("Logger",None) lL = gSettingsDict.get("Logger",None)
gSettingsDict["ServerDict"]["ServerThread"] = app gSettingsDict["ServerDict"]["ServerThread"] = app
for lConnectItemDict in gSettingsDict["ServerDict"]["URLList"]: for lConnectItemDict in gSettingsDict["ServerDict"]["URLList"]:
if "ResponseFolderPath" in lConnectItemDict:
app.mount(lConnectItemDict["URL"],
StaticFiles(directory=CrossOS.PathStr(lConnectItemDict["ResponseFolderPath"])),
name=lConnectItemDict["URL"].replace('/',"_"))
else:
if lConnectItemDict.get("UACBool",True): if lConnectItemDict.get("UACBool",True):
app.add_api_route( app.add_api_route(
path=lConnectItemDict["URL"], path=lConnectItemDict["URL"],

@ -118,14 +118,8 @@ def HiddenAgentDictGenerate(inRequest, inGSettings):
# Client: mGlobal.pyOpenRPA.ServerDataHashStr # Client: mGlobal.pyOpenRPA.ServerDataHashStr
# Client: mGlobal.pyOpenRPA.ServerDataDict # Client: mGlobal.pyOpenRPA.ServerDataDict
def pyOpenRPA_ServerData(inRequest,inGSettings): def pyOpenRPA_ServerData(inRequest,inGSettings):
# Extract the hash value from request # Extract the hash value from request
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект
lValueStr = (lInputByteArray.decode('utf8'))
# Generate ServerDataDict # Generate ServerDataDict
lFlagDoGenerateBool = True lFlagDoGenerateBool = True
while lFlagDoGenerateBool: while lFlagDoGenerateBool:
@ -168,12 +162,7 @@ def pyOpenRPA_ServerJSInit(inRequest,inGSettings):
# Client: mGlobal.pyOpenRPA.ServerLogList # Client: mGlobal.pyOpenRPA.ServerLogList
def pyOpenRPA_ServerLog(inRequest,inGSDict): def pyOpenRPA_ServerLog(inRequest,inGSDict):
# Extract the hash value from request # Extract the hash value from request
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект
lValueStr = (lInputByteArray.decode('utf8'))
# Generate ServerDataDict # Generate ServerDataDict
lFlagDoGenerateBool = True lFlagDoGenerateBool = True
while lFlagDoGenerateBool: while lFlagDoGenerateBool:
@ -193,6 +182,7 @@ def pyOpenRPA_ServerLog(inRequest,inGSDict):
inResponseDict["Body"] = bytes(message, "utf8") inResponseDict["Body"] = bytes(message, "utf8")
return lResult return lResult
def pyOpenRPA_Screenshot(inRequest,inGlobalDict): def pyOpenRPA_Screenshot(inRequest,inGlobalDict):
# Get Screenshot # Get Screenshot
def SaveScreenshot(inFilePath): def SaveScreenshot(inFilePath):
@ -209,6 +199,7 @@ def pyOpenRPA_Screenshot(inRequest,inGlobalDict):
lFileObject = open("Screenshot.png", "rb") lFileObject = open("Screenshot.png", "rb")
# Write content as utf-8 data # Write content as utf-8 data
inRequest.OpenRPAResponseDict["Body"] = lFileObject.read() inRequest.OpenRPAResponseDict["Body"] = lFileObject.read()
inRequest.OpenRPAResponseDict['BodyIsText']=False
# Закрыть файловый объект # Закрыть файловый объект
lFileObject.close() lFileObject.close()
else: else:
@ -216,6 +207,7 @@ def pyOpenRPA_Screenshot(inRequest,inGlobalDict):
lFileObject = open("Screenshot.png", "rb") lFileObject = open("Screenshot.png", "rb")
# Write content as utf-8 data # Write content as utf-8 data
inRequest.OpenRPAResponseDict["Body"] = lFileObject.read() inRequest.OpenRPAResponseDict["Body"] = lFileObject.read()
inRequest.OpenRPAResponseDict['BodyIsText']=False
# Закрыть файловый объект # Закрыть файловый объект
lFileObject.close() lFileObject.close()
@ -224,12 +216,9 @@ def pyOpenRPA_Screenshot(inRequest,inGlobalDict):
def pyOpenRPA_Processor(inRequest, inGSettings): def pyOpenRPA_Processor(inRequest, inGSettings):
lL = inGSettings["Logger"] lL = inGSettings["Logger"]
# Recieve the data # Recieve the data
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект # Превращение массива байт в объект
lInput = json.loads(lInputByteArray.decode('utf8')) lInput = json.loads(lValueStr)
# If list - operator plus # If list - operator plus
if type(lInput) is list: if type(lInput) is list:
# Logging info about processor activity if not SuperToken () # Logging info about processor activity if not SuperToken ()
@ -279,12 +268,9 @@ def pyOpenRPA_Processor(inRequest, inGSettings):
def pyOpenRPA_ActivityListExecute(inRequest, inGSettings): def pyOpenRPA_ActivityListExecute(inRequest, inGSettings):
# Recieve the data # Recieve the data
lL = inGSettings["Logger"] lL = inGSettings["Logger"]
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект # Превращение массива байт в объект
lInput = json.loads(lInputByteArray.decode('utf8')) lInput = json.loads(lValueStr)
# If list - operator plus # If list - operator plus
if type(lInput) is list: if type(lInput) is list:
# Logging info about processor activity if not SuperToken () # Logging info about processor activity if not SuperToken ()
@ -324,10 +310,7 @@ def pyOpenRPA_Agent_O2A(inRequest, inGSettings):
lAgentLoopSleepSecFloat = inGSettings["ServerDict"]["AgentLoopSleepSecFloat"] lAgentLoopSleepSecFloat = inGSettings["ServerDict"]["AgentLoopSleepSecFloat"]
lTimeStartFloat = time.time() lTimeStartFloat = time.time()
# Recieve the data # Recieve the data
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект # Превращение массива байт в объект
lInput = json.loads(lInputByteArray.decode('utf8')) lInput = json.loads(lInputByteArray.decode('utf8'))
# Check if item is created # Check if item is created
@ -423,12 +406,9 @@ def pyOpenRPA_Debugging_HelperDefAutofill(inRequest, inGSettings):
def pyOpenRPA_Agent_A2O(inRequest, inGSettings): def pyOpenRPA_Agent_A2O(inRequest, inGSettings):
lL = inGSettings["Logger"] lL = inGSettings["Logger"]
# Recieve the data # Recieve the data
lValueStr = None lValueStr = inRequest.body
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray = inRequest.rfile.read(lInputByteArrayLength)
# Превращение массива байт в объект # Превращение массива байт в объект
lInput = json.loads(lInputByteArray.decode('utf8')) lInput = json.loads(lValueStr)
lAgentDictItemKeyTurple = (lInput["HostNameUpperStr"], lInput["UserUpperStr"]) lAgentDictItemKeyTurple = (lInput["HostNameUpperStr"], lInput["UserUpperStr"])
if "LogList" in lInput: if "LogList" in lInput:
for lLogItemStr in lInput["LogList"]: for lLogItemStr in lInput["LogList"]:

@ -2754,14 +2754,6 @@ def Orchestrator(inGSettings=None, inDumpRestoreBool = True, inRunAsAdministrato
#Инициализация настроечных параметров #Инициализация настроечных параметров
gSettingsDict["ServerDict"]["WorkingDirectoryPathStr"] = os.getcwd() # Set working directory in g settings gSettingsDict["ServerDict"]["WorkingDirectoryPathStr"] = os.getcwd() # Set working directory in g settings
#Инициализация сервера (инициализация всех интерфейсов)
lListenDict = gSettingsDict.get("ServerDict",{}).get("ListenDict",{})
for lItemKeyStr in lListenDict:
lItemDict = lListenDict[lItemKeyStr]
Server.InitFastAPI()
# Init the RobotScreenActive in another thread # Init the RobotScreenActive in another thread
lRobotScreenActiveThread = threading.Thread(target= Monitor.CheckScreen) lRobotScreenActiveThread = threading.Thread(target= Monitor.CheckScreen)
lRobotScreenActiveThread.daemon = True # Run the thread in daemon mode. lRobotScreenActiveThread.daemon = True # Run the thread in daemon mode.
@ -2820,9 +2812,17 @@ def Orchestrator(inGSettings=None, inDumpRestoreBool = True, inRunAsAdministrato
lThread = threading.Thread(target= lProcess.StatusRestore) lThread = threading.Thread(target= lProcess.StatusRestore)
lThread.start() lThread.start()
# Init debug thread (run if "init_dubug" file exists) # Init debug thread (run if "init_dubug" file exists)
Debugger.LiveDebugCheckThread(inGSettings=GSettingsGet()) Debugger.LiveDebugCheckThread(inGSettings=GSettingsGet())
#Инициализация сервера (инициализация всех интерфейсов)
lListenDict = gSettingsDict.get("ServerDict",{}).get("ListenDict",{})
for lItemKeyStr in lListenDict:
lItemDict = lListenDict[lItemKeyStr]
Server.InitFastAPI()
def __schedule_loop__(): def __schedule_loop__():
while True: while True:
schedule.run_pending() schedule.run_pending()

Loading…
Cancel
Save