From 1c77c8d0783d52ffb16e45679ccc08a02b2aecb3 Mon Sep 17 00:00:00 2001 From: Ivan Maslov Date: Tue, 6 Sep 2022 00:45:02 +0300 Subject: [PATCH] orc fixes --- Sources/pyOpenRPA/Orchestrator/Server.py | 85 +++++++++++++++++-- .../pyOpenRPA/Orchestrator/ServerSettings.py | 82 ++---------------- .../Orchestrator/__Orchestrator__.py | 2 +- 3 files changed, 87 insertions(+), 82 deletions(-) diff --git a/Sources/pyOpenRPA/Orchestrator/Server.py b/Sources/pyOpenRPA/Orchestrator/Server.py index 85ab3b15..a78e84d0 100755 --- a/Sources/pyOpenRPA/Orchestrator/Server.py +++ b/Sources/pyOpenRPA/Orchestrator/Server.py @@ -27,6 +27,10 @@ from starlette.responses import StreamingResponse from typing import Union from pyOpenRPA import __version__ +import base64 +import uuid +import datetime + # ИНИЦИАЛИЗАЦИЯ FASTAPI! app = FastAPI( title = "pyOpenRPA (ORPA) Orchestrator", @@ -36,7 +40,75 @@ app = FastAPI( docs_url = "/orpa/fastapi/docs", redoc_url = "/orpa/fastapi/redoc", swagger_ui_oauth2_redirect_url = "/orpa/fastapi/docs/oauth2-redirect", - ) + ) + +def IdentifyAuthorize(inRequest:Request, inResponse:Response, + inCookiesStr: Union[str, None] = Header(default=None,alias="Cookie"), + inAuthorizationStr: Union[str, None] = Header(default="",alias="Authorization")): + if __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False)==True: + lResult={"Domain": "", "User": ""} + ###################################### + #Way 1 - try to find AuthToken + lCookies = cookies.SimpleCookie(inCookiesStr) # inRequest.headers.get("Cookie", "") + __Orchestrator__.GSettingsGet() + lHeaderAuthorization = inAuthorizationStr.split(" ") + if "AuthToken" in lCookies: + lCookieAuthToken = lCookies.get("AuthToken", "").value + if lCookieAuthToken: + #Find AuthToken in GlobalDict + if lCookieAuthToken in __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}): + #Auth Token Has Been Founded + lResult["Domain"] = __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["Domain"] + lResult["User"] = __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["User"] + #Set auth token + mOpenRPA={} + mOpenRPA["AuthToken"] = lCookieAuthToken + mOpenRPA["Domain"] = lResult["Domain"] + mOpenRPA["User"] = lResult["User"] + mOpenRPA["IsSuperToken"] = __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False) + return lCookieAuthToken + ###################################### + #Way 2 - try to logon + if len(lHeaderAuthorization) == 2: + llHeaderAuthorizationDecodedUserPasswordList = base64.b64decode(lHeaderAuthorization[1]).decode("utf-8").split( + ":") + lUser = llHeaderAuthorizationDecodedUserPasswordList[0] + lPassword = llHeaderAuthorizationDecodedUserPasswordList[1] + lDomain = "" + if "\\" in lUser: + lDomain = lUser.split("\\")[0] + lUser = lUser.split("\\")[1] + lLogonBool = __Orchestrator__.OSCredentialsVerify(inUserStr=lUser, inPasswordStr=lPassword, inDomainStr=lDomain) + #Check result + if lLogonBool: + lResult["Domain"] = lDomain + lResult["User"] = lUser + #Create token + lAuthToken=str(uuid.uuid1()) + __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken] = {} + __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["Domain"] = lResult["Domain"] + __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["User"] = lResult["User"] + __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["FlagDoNotExpire"] = False + __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["TokenDatetime"] = datetime.datetime.now() + #Set-cookie + inResponse.set_cookie(key="AuthToken",value=lAuthToken) + mOpenRPA={} + mOpenRPA["AuthToken"] = lAuthToken + mOpenRPA["Domain"] = lResult["Domain"] + mOpenRPA["User"] = lResult["User"] + mOpenRPA["IsSuperToken"] = __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False) + return lAuthToken + #inRequest.OpenRPASetCookie = {} + #New engine of server + #inRequest.OpenRPAResponseDict["SetCookies"]["AuthToken"] = lAuthToken + else: + raise HTTPException(status_code=401, detail="Попытка авторизации не прошла успешно (неверная пара логин / пароль)", headers={}) + ###################################### + else: + raise HTTPException(status_code=401, detail="Попытка авторизации не прошла успешно (неполная пара логин / пароль)", headers={'Content-type':'text/html', 'WWW-Authenticate':'Basic'}) + else: return None # Credentials are not required - return none + + lRouteList =[] for lItem in app.router.routes: @@ -47,10 +119,13 @@ for lItem in lRouteList: path=lItem.path, endpoint=lItem.endpoint, methods=["GET"], - dependencies=[Depends(ServerSettings.IdentifyAuthorize)], + dependencies=[Depends(IdentifyAuthorize)], tags=["FastAPI"] ) + +from . import ServerSettings + def BackwardCompatibility(inRequest:Request, inResponse:Response, inBodyStr:str = Body(""), inAuthTokenStr = None): lHTTPRequest = ServerBC.HTTPRequestOld(inRequest=inRequest, inResponse=inResponse, inAuthTokenStr=inAuthTokenStr) lHTTPRequest.path = inRequest.url.path @@ -68,15 +143,15 @@ def BackwardCompatibityWrapperAuth(inRequest:Request, inResponse:Response, inBod inAuthTokenStr:str=Depends(ServerSettings.IdentifyAuthorize)): # Old from v1.3.1 (updated to FastAPI) return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthTokenStr=inAuthTokenStr) def BackwardCompatibityWrapperNoAuth(inRequest:Request, inResponse:Response, inBodyStr:str = Body("")): # Old from v1.3.1 (updated to FastAPI) - return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthDict=None) + return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthTokenStr=None) def BackwardCompatibityBeginWrapperAuth(inBeginTokenStr, inRequest:Request, inResponse:Response, inBodyStr:str = Body(""), inAuthTokenStr:str=Depends(ServerSettings.IdentifyAuthorize)): # Old from v1.3.1 (updated to FastAPI) return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthTokenStr=inAuthTokenStr) def BackwardCompatibityBeginWrapperNoAuth(inBeginTokenStr, inRequest:Request, inResponse:Response, inBodyStr:str = Body("")): # Old from v1.3.1 (updated to FastAPI) - return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthDict=None) + return BackwardCompatibility(inRequest = inRequest, inResponse = inResponse, inBodyStr = inBodyStr, inAuthTokenStr=None) + -from . import ServerSettings from . import __Orchestrator__ import mimetypes mimetypes.add_type("font/woff2",".woff2") diff --git a/Sources/pyOpenRPA/Orchestrator/ServerSettings.py b/Sources/pyOpenRPA/Orchestrator/ServerSettings.py index 4d69bf20..892eaad1 100755 --- a/Sources/pyOpenRPA/Orchestrator/ServerSettings.py +++ b/Sources/pyOpenRPA/Orchestrator/ServerSettings.py @@ -1,7 +1,7 @@ import json, os import copy from . import __Orchestrator__ -from .Server import app # FAST API SERVER +from .Server import app,IdentifyAuthorize # FAST API SERVER #ControlPanelDict from pyOpenRPA.Tools import CrossOS if CrossOS.IS_WINDOWS_BOOL: #CrossOS @@ -30,76 +30,6 @@ import io from starlette.responses import StreamingResponse from typing import Union from fastapi.responses import JSONResponse -import base64 -import uuid -import datetime - -def IdentifyAuthorize(inRequest:Request, inResponse:Response, - inCookiesStr: Union[str, None] = Header(default=None,alias="Cookie"), - inAuthorizationStr: Union[str, None] = Header(default="",alias="Authorization")): - if __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("FlagCredentialsAsk", False): - lResult={"Domain": "", "User": ""} - #print("IdentifyAuthorize") - ###################################### - #Way 1 - try to find AuthToken - lCookies = cookies.SimpleCookie(inCookiesStr) # inRequest.headers.get("Cookie", "") - __Orchestrator__.GSettingsGet() - lHeaderAuthorization = inAuthorizationStr.split(" ") - if "AuthToken" in lCookies: - lCookieAuthToken = lCookies.get("AuthToken", "").value - if lCookieAuthToken: - #Find AuthToken in GlobalDict - if lCookieAuthToken in __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}): - #Auth Token Has Been Founded - lResult["Domain"] = __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["Domain"] - lResult["User"] = __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lCookieAuthToken]["User"] - #Set auth token - mOpenRPA={} - mOpenRPA["AuthToken"] = lCookieAuthToken - mOpenRPA["Domain"] = lResult["Domain"] - mOpenRPA["User"] = lResult["User"] - mOpenRPA["IsSuperToken"] = __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False) - return lAuthToken - ###################################### - #Way 2 - try to logon - if len(lHeaderAuthorization) == 2: - llHeaderAuthorizationDecodedUserPasswordList = base64.b64decode(lHeaderAuthorization[1]).decode("utf-8").split( - ":") - lUser = llHeaderAuthorizationDecodedUserPasswordList[0] - lPassword = llHeaderAuthorizationDecodedUserPasswordList[1] - lDomain = "" - if "\\" in lUser: - lDomain = lUser.split("\\")[0] - lUser = lUser.split("\\")[1] - lLogonBool = __Orchestrator__.OSCredentialsVerify(inUserStr=lUser, inPasswordStr=lPassword, inDomainStr=lDomain) - #Check result - if lLogonBool: - lResult["Domain"] = lDomain - lResult["User"] = lUser - #Create token - lAuthToken=str(uuid.uuid1()) - __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken] = {} - __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["Domain"] = lResult["Domain"] - __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["User"] = lResult["User"] - __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["FlagDoNotExpire"] = False - __Orchestrator__.GSettingsGet()["ServerDict"]["AccessUsers"]["AuthTokensDict"][lAuthToken]["TokenDatetime"] = datetime.datetime.now() - #Set-cookie - inResponse.set_cookie(key="AuthToken",value=lAuthToken) - mOpenRPA={} - mOpenRPA["AuthToken"] = lAuthToken - mOpenRPA["Domain"] = lResult["Domain"] - mOpenRPA["User"] = lResult["User"] - mOpenRPA["IsSuperToken"] = __Orchestrator__.GSettingsGet().get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(mOpenRPA["AuthToken"], {}).get("FlagDoNotExpire", False) - return lAuthToken - #inRequest.OpenRPASetCookie = {} - #New engine of server - #inRequest.OpenRPAResponseDict["SetCookies"]["AuthToken"] = lAuthToken - else: - raise HTTPException(status_code=401, detail="Попытка авторизации не прошла успешно (неверная пара логин / пароль)", headers={}) - ###################################### - else: - raise HTTPException(status_code=401, detail="Попытка авторизации не прошла успешно (неполная пара логин / пароль)", headers={'Content-type':'text/html', 'WWW-Authenticate':'Basic'}) - else: return None # Credentials are not required - return none # # # # # # # # # # # # @@ -339,7 +269,7 @@ def pyOpenRPA_Processor(inRequest:Request, inAuthTokenStr:str = Depends(Identify except Exception as e: lActivityTypeListStr = "Ошибка чтения типа активности" lHostStr = __Orchestrator__.WebRequestHostGet(inRequest=inRequest) - lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inRequest=inRequest, inHostStr = lHostStr, inOperationCodeStr=lActivityTypeListStr, inMessageStr="pyOpenRPA_Processor") + lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inAuthTokenStr=inAuthTokenStr, inHostStr = lHostStr, inOperationCodeStr=lActivityTypeListStr, inMessageStr="pyOpenRPA_Processor") if lL: lL.info(lWebAuditMessageStr) if lInput.get("ThreadBool",False) == False: # Append in list @@ -356,7 +286,7 @@ def pyOpenRPA_ActivityListExecute(inRequest:Request, inAuthTokenStr:str = Depend # Recieve the data inGSettings = __Orchestrator__.GSettingsGet() lL = __Orchestrator__.OrchestratorLoggerGet() - lValueStr = inRequest.body + lValueStr = inBodyStr # Превращение массива байт в объект lInput = json.loads(lValueStr) # If list - operator plus @@ -370,7 +300,7 @@ def pyOpenRPA_ActivityListExecute(inRequest:Request, inAuthTokenStr:str = Depend except Exception as e: lActivityTypeListStr = "Ошибка чтения типа активности" lHostStr = __Orchestrator__.WebRequestHostGet(inRequest=inRequest) - lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inRequest=inRequest, inHostStr = lHostStr,inOperationCodeStr=lActivityTypeListStr, inMessageStr="pyOpenRPA_ActivityListExecute") + lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inAuthTokenStr=inAuthTokenStr, inHostStr = lHostStr,inOperationCodeStr=lActivityTypeListStr, inMessageStr="pyOpenRPA_ActivityListExecute") if lL: lL.info(lWebAuditMessageStr) # Execution lResultList = Processor.ActivityListExecute(inGSettings = inGSettings, inActivityList = lInput) @@ -385,7 +315,7 @@ def pyOpenRPA_ActivityListExecute(inRequest:Request, inAuthTokenStr:str = Depend except Exception as e: lActivityTypeListStr = "Ошибка чтения типа активности" lHostStr = __Orchestrator__.WebRequestHostGet(inRequest=inRequest) - lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inRequest=inRequest, inHostStr = lHostStr, + lWebAuditMessageStr = __Orchestrator__.WebAuditMessageCreate(inAuthTokenStr=inAuthTokenStr, inHostStr = lHostStr, inOperationCodeStr=lActivityTypeListStr, inMessageStr="pyOpenRPA_ActivityListExecute") if lL: lL.info(lWebAuditMessageStr) @@ -584,7 +514,7 @@ def SettingsUpdate(): #{"Method": "POST", "URL": "/orpa/api/processor-queue-add", "MatchType": "Equal","ResponseDefRequestGlobal": pyOpenRPA_Processor, "ResponseContentType": "application/json"}, #{"Method": "POST", "URL": "/orpa/api/activity-list-execute", "MatchType": "Equal","ResponseDefRequestGlobal": pyOpenRPA_ActivityListExecute, "ResponseContentType": "application/json"}, {"Method": "GET", "URL": "/orpa/api/helper-def-list/", "MatchType": "BeginWith","ResponseDefRequestGlobal": pyOpenRPA_Debugging_HelperDefList, "ResponseContentType": "application/json"}, - {"Method": "GET", "URL": "/orpa/api/helper-autofill/", "MatchType": "BeginWith","ResponseDefRequestGlobal": pyOpenRPA_Debugging_HelperDefAutofill, "ResponseContentType": "application/json"}, + {"Method": "GET", "URL": "/orpa/api/helper-def-autofill/", "MatchType": "BeginWith","ResponseDefRequestGlobal": pyOpenRPA_Debugging_HelperDefAutofill, "ResponseContentType": "application/json"}, # AGENT {"Method": "POST", "URL": "/orpa/agent/o2a", "MatchType": "Equal","ResponseDefRequestGlobal": pyOpenRPA_Agent_O2A, "ResponseContentType": "application/json"}, {"Method": "POST", "URL": "/orpa/agent/a2o", "MatchType": "Equal","ResponseDefRequestGlobal": pyOpenRPA_Agent_A2O, "ResponseContentType": "application/json"} diff --git a/Sources/pyOpenRPA/Orchestrator/__Orchestrator__.py b/Sources/pyOpenRPA/Orchestrator/__Orchestrator__.py index 757b2a76..e2f69a35 100755 --- a/Sources/pyOpenRPA/Orchestrator/__Orchestrator__.py +++ b/Sources/pyOpenRPA/Orchestrator/__Orchestrator__.py @@ -1202,7 +1202,7 @@ def WebUserIsSuperToken(inAuthTokenStr: str=None): :return: True - является супертокеном; False - не является супертокеном; None - авторизация не производилась """ if inAuthTokenStr is None: return None - inGSettings = GSettingsGet(inGSettings=inGSettings) # Get the global settings + inGSettings = GSettingsGet() # Get the global settings lIsSuperTokenBool = False # Get Flag is supertoken (True|False) lIsSuperTokenBool = inGSettings.get("ServerDict", {}).get("AccessUsers", {}).get("AuthTokensDict", {}).get(inAuthTokenStr, {}).get("FlagDoNotExpire", False)