Пример #1
0
        public bool PerformGetRequestToGetGloballySharedModelIds(out List <string> _Result, Action <string> _ErrorMessageAction)
        {
            _Result = new List <string>();

            //Get cad file service endpoint from internal set state
            if (!InternalSetState.GetValueFromMemoryService(
                    out string CADFileServiceEndpoint,
                    InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY,
                    MemoryService,
                    (string _Message) =>
            {
                _ErrorMessageAction?.Invoke("PerformGetRequestToGetGloballySharedModelIds: " + _Message);
            }))
            {
                return(false);
            }

            var ListGloballySharedModelIdsEndpoint = CADFileServiceEndpoint + "/3d/models/internal/globally_shared_models?secret=" + CommonData.INTERNAL_CALL_PRIVATE_KEY;

            var Result = BWebServiceExtraUtilities.InterServicesRequest(new BWebServiceExtraUtilities.InterServicesRequestRequest()
            {
                DestinationServiceUrl = ListGloballySharedModelIdsEndpoint,
                RequestMethod         = "GET",
                bWithAuthToken        = true
                                        //UseContext not needed since it's a call to an internal endpoint
            },
                                                                        false,
                                                                        _ErrorMessageAction);

            string  ResponseContentAsString = "";
            JObject ResponseContentAsJson   = null;

            try
            {
                ResponseContentAsString = Result.Content.String;
                ResponseContentAsJson   = JObject.Parse(ResponseContentAsString);

                var ArrayTmp = (JArray)ResponseContentAsJson["sharedModelIds"];
                foreach (var Tmp in ArrayTmp)
                {
                    _Result.Add((string)Tmp);
                }
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("PerformGetRequestToGetGloballySharedModelIds: Error occured during reading response/parsing json: " + e.Message + ", trace: " + e.StackTrace + ", response content: " + ResponseContentAsString + ", response code: " + Result.ResponseCode);
                return(false);
            }
            if (Result.ResponseCode >= 400)
            {
                _ErrorMessageAction?.Invoke("PerformGetRequestToGetGloballySharedModelIds: Request did not end up with success. Response content: " + ResponseContentAsString + ", response code: " + Result.ResponseCode);
                return(false);
            }
            return(true);
        }
Пример #2
0
        protected override BWebServiceResponse OnRequestPP(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (MaintenanceChecker.Get().IsMaintenanceModeOn())
            {
                return(BWebResponse.ServiceUnavailable("The system is in maintenance."));
            }

            var Response = BWebServiceExtraUtilities.RequestRedirection(
                _Context,
                ApiGatewayServiceEndpoint + "/" + _Context.Request.RawUrl.TrimStart('/'),
                _ErrorMessageAction,
                false,
                false);

            return(MaintenanceChecker.Get().IsMaintenanceModeOn() ? BWebResponse.ServiceUnavailable("The system is in maintenance.") : Response);
        }
Пример #3
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (!AccessCheck(
                    out BWebServiceResponse AuthFailureResponse,
                    out bool bSSOTokenRefreshed,
                    out string NewSSOTokenAfterRefresh,
                    _Context,
                    _ErrorMessageAction))
            {
                return(AuthFailureResponse);
            }

            GetTracingService()?.On_FromGatewayToService_Sent(_Context, _ErrorMessageAction);
            var Result = BWebServiceExtraUtilities.RequestRedirection(
                _Context,
                DestinationBaseUrl + _Context.Request.RawUrl,
                _ErrorMessageAction,
                true,
                false,
                new string[] { "do-not-get-db-clearance", "internal-call-secret" });

            GetTracingService()?.On_FromServiceToGateway_Received(_Context, _ErrorMessageAction);

            if (bSSOTokenRefreshed)
            {
                Result.Headers.Remove("x-bkio-sso-token-refreshed");
                Result.Headers.Add("x-bkio-sso-token-refreshed", new List <string>()
                {
                    "true"
                });

                Result.Headers.Remove("x-bkio-sso-token-after-refresh");
                Result.Headers.Add("x-bkio-sso-token-after-refresh", new List <string>()
                {
                    NewSSOTokenAfterRefresh
                });
            }

            return(Result);
        }
Пример #4
0
            private void Cleanup_UserModels(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (!DatabaseService.ScanTable(
                        UserDBEntry.DBSERVICE_USERS_TABLE(),
                        out List <JObject> UserEntries,
                        _ErrorMessageAction))
                {
                    _ErrorMessageAction?.Invoke("Cleanup_UserModels: Table does not exist or ScanTable operation has failed.");
                    return;
                }
                if (UserEntries.Count == 0)
                {
                    return;
                }

                //Get cad file service endpoint from internal set state
                if (!InternalSetState.GetValueFromMemoryService(
                        out string CADFileServiceEndpoint,
                        InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY,
                        MemoryService,
                        (string _Message) =>
                {
                    _ErrorMessageAction?.Invoke("Cleanup_UserModels: Unable to get CadFileServiceEndpoint: " + _Message);
                }))
                {
                    return;
                }

                foreach (var UserJObject in UserEntries)
                {
                    var UserID = (string)UserJObject[UserDBEntry.KEY_NAME_USER_ID];
                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), UserID, _ErrorMessageAction))
                    {
                        continue;
                    }
                    try
                    {
                        var UserID_Primitive = new BPrimitiveType(UserID);

                        var UserDeserialized = JsonConvert.DeserializeObject <UserDBEntry>(UserJObject.ToString());

                        var UserModelIDsJArray       = new JArray();
                        var UserSharedModelIDsJArray = new JArray();

                        foreach (var CurrentModel in UserDeserialized.UserModels)
                        {
                            UserModelIDsJArray.Add(CurrentModel);
                        }

                        foreach (var CurrentSharedModel in UserDeserialized.UserSharedModels)
                        {
                            UserSharedModelIDsJArray.Add(CurrentSharedModel);
                        }

                        var RequestObject = new JObject()
                        {
                            ["userModelIds"]       = UserModelIDsJArray,
                            ["userSharedModelIds"] = UserSharedModelIDsJArray
                        };

                        // 3d/models/internal/check_models_exist will return CheckedUserModelIDs and CheckedUserSharedModelIDs list
                        List <string> CheckedUserModelIDs       = new List <string>();
                        List <string> CheckedUserSharedModelIDs = new List <string>();

                        GetTracingService()?.On_FromServiceToService_Sent(_Context, _ErrorMessageAction);

                        var Result = BWebServiceExtraUtilities.InterServicesRequest(new BWebServiceExtraUtilities.InterServicesRequestRequest()
                        {
                            DestinationServiceUrl = CADFileServiceEndpoint + "/3d/models/internal/check_models_exist?secret=" + InternalCallPrivateKey,
                            RequestMethod         = "POST",
                            bWithAuthToken        = true,
                            UseContextHeaders     = _Context,
                            ContentType           = "application/json",
                            Content = new BStringOrStream(RequestObject.ToString()),
                            ExcludeHeaderKeysForRequest = null
                        },
                                                                                    false,
                                                                                    _ErrorMessageAction);

                        GetTracingService()?.On_FromServiceToService_Received(_Context, _ErrorMessageAction);

                        string  ResponseContentAsString = "";
                        JObject ResponseContentAsJson   = null;
                        try
                        {
                            ResponseContentAsString = Result.Content.String;
                            ResponseContentAsJson   = JObject.Parse(ResponseContentAsString);

                            var ArrayUserModelsTmp = (JArray)ResponseContentAsJson["checkedUserModelIds"];
                            if (ArrayUserModelsTmp != null)
                            {
                                foreach (var Tmp in ArrayUserModelsTmp)
                                {
                                    CheckedUserModelIDs.Add((string)Tmp);
                                }
                            }

                            var ArraySharedUserModelsTmp = (JArray)ResponseContentAsJson["checkedUserSharedModelIds"];
                            if (ArraySharedUserModelsTmp != null)
                            {
                                foreach (var Tmp in ArraySharedUserModelsTmp)
                                {
                                    CheckedUserSharedModelIDs.Add((string)Tmp);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("Cleanup_UserModels: Error occurred during reading response/parsing json: " + e.Message + ", trace: " + e.StackTrace + ", response content: " + ResponseContentAsString + ", response code: " + Result.ResponseCode);
                            continue;
                        }

                        if (!Result.bSuccess || Result.ResponseCode >= 400)
                        {
                            _ErrorMessageAction?.Invoke("Cleanup_UserModels: Request did not end up with success. Response content: " + ResponseContentAsString + ", response code: " + Result.ResponseCode);
                            continue;
                        }

                        UserDeserialized.UserModels       = new List <string>(CheckedUserModelIDs);
                        UserDeserialized.UserSharedModels = new List <string>(CheckedUserSharedModelIDs);

                        if (!DatabaseService.UpdateItem(//Fire and forget is not suitable here since there are following calls after DB update which will change the DB structure
                                UserDBEntry.DBSERVICE_USERS_TABLE(),
                                UserDBEntry.KEY_NAME_USER_ID,
                                UserID_Primitive,
                                JObject.Parse(JsonConvert.SerializeObject(UserDeserialized)),
                                out JObject _, EBReturnItemBehaviour.DoNotReturn, null,
                                _ErrorMessageAction))
                        {
                            continue;
                        }
                    }
                    finally
                    {
                        Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), UserID, _ErrorMessageAction);
                    }
                }
            }
Пример #5
0
        private BWebServiceResponse ProcessRequestLocked(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

            if (!CommonMethods.TryGettingModelID(
                    DatabaseService,
                    RequestedModelName,
                    out RequestedModelID,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            string  RequestPayload = null;
            JObject ParsedBody;

            using (var InputStream = _Context.Request.InputStream)
            {
                using var ResponseReader = new StreamReader(InputStream);
                try
                {
                    RequestPayload = ResponseReader.ReadToEnd();
                    ParsedBody     = JObject.Parse(RequestPayload);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("Model_ChangeSharingWithUsers-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }
            }

            var bShareWithAllExists = ParsedBody.ContainsKey("shareWithAll");
            var bEmailsExist        = ParsedBody.ContainsKey("emails");
            var bUserIdsExist       = ParsedBody.ContainsKey("userIds");

            var FinalUserIds = new List <string>();

            bool bShareWithAll = false;

            if (bShareWithAllExists /*Exist*/)
            {
                if (ParsedBody["shareWithAll"].Type != JTokenType.Boolean)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                bShareWithAll = (bool)ParsedBody["shareWithAll"];

                if (bShareWithAll)
                {
                    if (bEmailsExist || bUserIdsExist)
                    {
                        return(BWebResponse.BadRequest("Request has shareWithAll field; therefore cannot have emails or userIds."));
                    }

                    FinalUserIds.Add("*");
                }
            }

            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!bShareWithAll)
            {
                var EmailAddresses = new List <string>();

                if (bEmailsExist)
                {
                    if (ParsedBody["emails"].Type != JTokenType.Array)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }
                    var AsJArray = (JArray)ParsedBody["emails"];

                    foreach (var Token in AsJArray)
                    {
                        if (Token.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request is invalid."));
                        }

                        var Lowered = ((string)Token).ToLower();
                        if (!EmailAddresses.Contains(Lowered))
                        {
                            EmailAddresses.Add(Lowered);
                        }
                    }
                }
                if (bUserIdsExist)
                {
                    if (ParsedBody["userIds"].Type != JTokenType.Array)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }
                    var AsJArray = (JArray)ParsedBody["userIds"];

                    foreach (var Token in AsJArray)
                    {
                        if (Token.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request is invalid."));
                        }

                        var Lowered = ((string)Token).ToLower();
                        if (!FinalUserIds.Contains(Lowered))
                        {
                            FinalUserIds.Add(Lowered);
                        }
                    }
                }

                if (EmailAddresses.Count > 0)
                {
                    GetTracingService()?.On_FromServiceToService_Sent(_Context, _ErrorMessageAction);

                    var EmailsJArray = new JArray();

                    foreach (var CurEmail in EmailAddresses)
                    {
                        EmailsJArray.Add(CurEmail);
                    }

                    var RequestObject = new JObject()
                    {
                        ["emailAddresses"] = EmailsJArray
                    };

                    var Result = BWebServiceExtraUtilities.InterServicesRequest(new BWebServiceExtraUtilities.InterServicesRequestRequest()
                    {
                        DestinationServiceUrl = AuthServiceEndpoint + "/auth/internal/fetch_user_ids_from_emails?secret=" + InternalCallPrivateKey,
                        RequestMethod         = "POST",
                        bWithAuthToken        = true,
                        UseContextHeaders     = _Context,
                        ContentType           = "application/json",
                        Content = new BStringOrStream(RequestObject.ToString()),
                        ExcludeHeaderKeysForRequest = null
                    },
                                                                                false,
                                                                                _ErrorMessageAction);

                    GetTracingService()?.On_FromServiceToService_Received(_Context, _ErrorMessageAction);

                    if (!Result.bSuccess || Result.ResponseCode >= 400)
                    {
                        return(new BWebServiceResponse(Result.ResponseCode, Result.Content, Result.ContentType));
                    }

                    string InterServicesRequestStringResponse = null;

                    JObject Map;
                    try
                    {
                        InterServicesRequestStringResponse = Result.Content.String;

                        var Json = JObject.Parse(InterServicesRequestStringResponse);
                        Map = (JObject)Json["map"];
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Model_ChangeSharingWithUsers-> Malformed request body has been returned from auth service. Body content: " + InterServicesRequestStringResponse + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.InternalError("Malformed request body has been returned from auth service."));
                    }

                    foreach (var UserIdToken in Map.Values())
                    {
                        if (UserIdToken.Type == JTokenType.String)
                        {
                            var UserId = (string)UserIdToken;
                            if (!FinalUserIds.Contains(UserId))
                            {
                                FinalUserIds.Add(UserId);
                            }
                        }
                    }
                }
            }

            if (Model.ModelSharedWithUserIDs.OrderBy(t => t).SequenceEqual(FinalUserIds.OrderBy(t => t)))
            {
                return(BWebResponse.StatusOK("No change has been done."));
            }

            var OldSharedList = new List <string>(Model.ModelSharedWithUserIDs);

            Model.ModelSharedWithUserIDs = FinalUserIds;

            Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                _Context,
                ModelDBEntry.DBSERVICE_MODELS_TABLE(),
                ModelDBEntry.KEY_NAME_MODEL_ID,
                new BPrimitiveType(RequestedModelID),
                JObject.Parse(JsonConvert.SerializeObject(Model)));

            var bOldHasStar = OldSharedList.Contains("*");
            var bNewHasStar = FinalUserIds.Contains("*");

            if (bOldHasStar && !bNewHasStar)
            {
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    GloballySharedModelIDsDBEntry.DBSERVICE_GLOBALLY_SHARED_MODEL_IDS_TABLE(),
                    GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID,
                    new BPrimitiveType(RequestedModelID));
            }
            else if (!bOldHasStar && bNewHasStar)
            {
                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    GloballySharedModelIDsDBEntry.DBSERVICE_GLOBALLY_SHARED_MODEL_IDS_TABLE(),
                    GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID,
                    new BPrimitiveType(RequestedModelID),
                    JObject.Parse(JsonConvert.SerializeObject(new GloballySharedModelIDsDBEntry())));
            }

            Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelSharedWithUserIdsChanged
                                                               (
                                                                   RequestedModelID,
                                                                   Model.ModelOwnerUserID,
                                                                   FinalUserIds,
                                                                   OldSharedList,
                                                                   AuthorizedUser.UserID
                                                               ),
                                                               _ErrorMessageAction);

            return(BWebResponse.StatusOK("Operation has been completed."));
        }
Пример #6
0
        private bool AccessCheck(out BWebServiceResponse _FailureResponse, out bool _bSSOTokenRefreshed, out string _NewSSOTokenAfterRefresh, HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            _FailureResponse = new BWebServiceResponse();

            _bSSOTokenRefreshed      = false;
            _NewSSOTokenAfterRefresh = "";

            if (bAuthCheck)
            {
                //Check for authorization header
                if (!BWebUtilities.DoesContextContainHeader(out List <string> Authorization, out string _, _Context, "authorization"))
                {
                    _FailureResponse = BWebResponse.Unauthorized("Authorization header must be set.");
                    return(false);
                }

                var RequestObject = new JObject()
                {
                    ["forUrlPath"]    = _Context.Request.RawUrl,
                    ["requestMethod"] = _Context.Request.HttpMethod
                };
                if (BUtility.CheckAndGetFirstStringFromList(Authorization, out string _Authorization))
                {
                    RequestObject["authorization"] = _Authorization;
                }
                else //Zero length
                {
                    _FailureResponse = BWebResponse.Unauthorized("Authorization header must be set.");
                    return(false);
                }

                GetTracingService()?.On_FromGatewayToService_Sent(_Context, _ErrorMessageAction);
                var Result = BWebServiceExtraUtilities.InterServicesRequest(new BWebServiceExtraUtilities.InterServicesRequestRequest()
                {
                    DestinationServiceUrl = AuthServiceBaseUrl + "/auth/access_check",
                    RequestMethod         = "POST",
                    ContentType           = "application/json",
                    Content           = new BStringOrStream(RequestObject.ToString()),
                    bWithAuthToken    = true,
                    UseContextHeaders = _Context,
                },
                                                                            false,
                                                                            _ErrorMessageAction);
                GetTracingService()?.On_FromServiceToGateway_Received(_Context, _ErrorMessageAction);

                if (!Result.bSuccess || Result.ResponseCode >= 400)
                {
                    if (Result.ResponseCode == BWebResponse.Error_Unauthorized_Code ||
                        Result.ResponseCode == BWebResponse.Error_Forbidden_Code)
                    {
                        _FailureResponse = new BWebServiceResponse(Result.ResponseCode, Result.Content, Result.ContentType);
                        return(false);
                    }

                    _ErrorMessageAction?.Invoke("Access check internal call has failed: Response: " + Result.ResponseCode + " -> " + Result.Content.String + ", Request: " + RequestObject.ToString());
                    _FailureResponse = BWebResponse.InternalError("Internal access check call has failed.");
                    return(false);
                }

                var ResponseContent = Result.Content.ToString();
                try
                {
                    var Parsed = JObject.Parse(ResponseContent);
                    Authenticated_UserID        = (string)Parsed["userId"];
                    Authenticated_UserName      = (string)Parsed["userName"];
                    Authenticated_UserEmail     = (string)Parsed["userEmail"];
                    Authenticated_AuthMethodKey = (string)Parsed["authMethodKey"];
                    _bSSOTokenRefreshed         = (bool)Parsed["ssoTokenRefreshed"];
                    _NewSSOTokenAfterRefresh    = (string)Parsed["newSSOTokenAfterRefresh"];
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("HandleRequest->AccessCheck: Error during content parse: " + ResponseContent + ", Message: " + e.Message + ", Trace: " + e.StackTrace);
                    _FailureResponse = BWebResponse.InternalError("Request has failed due to an internal api gateway error.");
                    return(false);
                }

                _Context.Request.Headers.Set("authorized-u-id", Authenticated_UserID);
                _Context.Request.Headers.Set("authorized-u-name", Authenticated_UserName);
                _Context.Request.Headers.Set("authorized-u-email", Authenticated_UserEmail);
                _Context.Request.Headers.Set("authorized-u-auth-key", Authenticated_AuthMethodKey);
            }
            return(true);
        }