Пример #1
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST" && _Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("User_UpdateDeleteBaseRight_ForUser: POST and DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST and DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            RequestedUserID                  = RestfulUrlParameters[RestfulUrlParameter_UsersKey];
            RequestedBaseRightWildcard       = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_BaseAccessRightsKey]);
            RequestedBaseRightWildcard_Regex = BUtility.WildCardToRegular(RequestedBaseRightWildcard);

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Atomic operation control has failed."));
            }

            BWebServiceResponse Result;

            if (_Context.Request.HttpMethod == "POST")
            {
                Result = UpdateBaseRightForUser(_Context, _ErrorMessageAction);
            }
            else
            {
                Result = DeleteBaseRightForUser(_Context, _ErrorMessageAction);
            }

            Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);

            return(Result);
        }
Пример #2
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("Model_RemoveModelShare: DELETE method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("DELETE method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Atomic operation control has failed."));
            }
            try
            {
                return(ProcessRequestLocked(_Context, _ErrorMessageAction));
            }
            finally
            {
                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction);
            }
        }
Пример #3
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("User_CreateListAccessMethods_ForUser: GET and PUT methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and PUT methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            RequestedUserID = RestfulUrlParameters[RestfulUrlParameter_UsersKey];

            if (_Context.Request.HttpMethod == "GET")
            {
                return(ListAccessMethodsForUser(_ErrorMessageAction));
            }
            //else
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                var Result = CreateAccessMethodForUser(_Context, out bool bSetClearanceForApiKey, out string ApiKey, _ErrorMessageAction);

                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);
                if (bSetClearanceForApiKey)
                {
                    Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + ApiKey, _ErrorMessageAction);
                }

                return(Result);
            }
        }
Пример #4
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext Context, Action <string> _ErrorMessageAction = null)
        {
            if (Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("BListSecretsRequest: GET method is accepted. But received request method:  " + Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + Context.Request.HttpMethod));
            }

            if (!FileService.ListAllFilesInBucket(
                    SecretsStorageBucket,
                    out List <string> KeysFound,
                    (string Message) =>
            {
                _ErrorMessageAction?.Invoke("BListSecretsRequest->Error-> " + Message);
            }))
            {
                return(BWebResponse.InternalError("List all files operation has failed.`"));
            }

            var ResultObject = new JObject
            {
                ["keys"] = new JArray()
            };

            foreach (var Key in KeysFound)
            {
                ((JArray)ResultObject["keys"]).Add(Key);
            }

            return(new BWebServiceResponse(
                       BWebResponse.Status_OK_Code,
                       new BStringOrStream(ResultObject.ToString()),
                       "application/json"));
        }
Пример #5
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            bIsInternalCall =
                BWebUtilities.DoesContextContainHeader(out List <string> ICHVs, out string _, _Context, "internal-call-secret") &&
                BUtility.CheckAndGetFirstStringFromList(ICHVs, out string ICH) &&
                ICH == CommonData.INTERNAL_CALL_PRIVATE_KEY;

            if (_Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("User_DeleteUserAccessMethod_ForUser: DELETE method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("DELETE methods is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            RequestedUserID        = RestfulUrlParameters[RestfulUrlParameter_UsersKey];
            RequestedAuthMethodKey = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_AccessMethodKey]);

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Atomic operation control has failed."));
            }

            var Result = DeleteAccessMethodForUser(_Context, out bool bSetClearanceForApiKey, out string ApiKey, _ErrorMessageAction);

            Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);
            if (bSetClearanceForApiKey)
            {
                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + ApiKey, _ErrorMessageAction);
            }

            return(Result);
        }
Пример #6
0
        public static BWebServiceResponse ProcessCommon(HttpListenerContext _Context, IBDatabaseServiceInterface _DatabaseService, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("ListGloballySharedModelIds: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            if (!_DatabaseService.ScanTable(GloballySharedModelIDsDBEntry.DBSERVICE_GLOBALLY_SHARED_MODEL_IDS_TABLE(), out List <JObject> GloballySharedModelIDObjects, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Scanning table for listing items has failed."));
            }

            var SharedModelIds = new JArray();

            foreach (var Current in GloballySharedModelIDObjects)
            {
                if (Current != null && Current.ContainsKey(GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID))
                {
                    SharedModelIds.Add((string)Current[GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID]);
                }
            }

            return(BWebResponse.StatusOK("Globally shared models have successfully been retrieved.", new JObject()
            {
                ["sharedModelIds"] = SharedModelIds
            }));
        }
Пример #7
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("User_AddListBaseRights_ForUser: GET and PUT methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and PUT methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            RequestedUserID = RestfulUrlParameters[RestfulUrlParameter_UsersKey];

            if (_Context.Request.HttpMethod == "GET")
            {
                return(ListBaseRightsForUser(_ErrorMessageAction));
            }
            //else
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                var Result = AddUpdateBaseRightsForUser(_Context, _ErrorMessageAction);

                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);

                return(Result);
            }
        }
Пример #8
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //GET is supported for easy calls from terraform scripts since it only has GET request support out of the box.
            //https://www.terraform.io/docs/providers/http/data_source.html
            //POST calls are recommended to use over GET.

            if (_Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("ScheduleRequest: DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody = null;

            if (_Context.Request.HttpMethod == "DELETE")
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }
            }

            if (!ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.URL_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY].Type != JTokenType.String)
            {
                return(BWebResponse.BadRequest("Request must contain all necessary fields validly. Given argument: " + ParsedBody.ToString()));
            }

            string Url = (string)ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY];

            if (!Uri.TryCreate(Url, UriKind.Absolute, out Uri UriResult) ||
                (UriResult.Scheme != Uri.UriSchemeHttp && UriResult.Scheme != Uri.UriSchemeHttps))
            {
                return(BWebResponse.BadRequest("Given field " + ScheduledUrlTaskDBEntry.URL_PROPERTY + " is invalid. Given argument: " + ParsedBody.ToString()));
            }

            if (!DatabaseService.DeleteItem(
                    ScheduledUrlTaskDBEntry.DBSERVICE_SCHEDULED_URL_TASKS_TABLE(),
                    ScheduledUrlTaskDBEntry.KEY_NAME_TASK_URL,
                    new BPrimitiveType(WebUtility.UrlEncode(Url)),
                    out JObject _,
                    EBReturnItemBehaviour.DoNotReturn,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database delete operation has failed."));
            }

            return(BWebResponse.StatusOK("Task has been unscheduled."));
        }
Пример #9
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("Model_GetHierarchyFile_ForRevision: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

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

            if (!int.TryParse(RestfulUrlParameters[RestfulUrlParameter_RevisionsKey], out RequestedRevisionIndex))
            {
                return(BWebResponse.BadRequest("Revision index must be an integer."));
            }

            RequestedGeometryId = RestfulUrlParameters[RestfulUrlParameter_GeometryKey];

            return(GetProcessedUnrealHierarchyGeometryFile(RequestedGeometryId, _ErrorMessageAction));
        }
Пример #10
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("GetModelsBy_MetadataKeyValueUserPair: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var UserID      = RestfulUrlParameters[RestfulUrlParameter_UserID];
            var MetadataKey = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_MetadataKey]);

            if (!DatabaseService.GetItem(
                    AttributeKUPairToOwnerDBEntry.TABLE(),
                    AttributeKUPairToOwnerDBEntry.KEY_NAME,
                    Controller_AttributeTables.MakeKey(MetadataKey, UserID),
                    new string[] { AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY },
                    out JObject Result,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database query has failed."));
            }

            if (Result == null || !Result.ContainsKey(AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY) || Result[AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY].Type != JTokenType.Array)
            {
                return(BWebResponse.NotFound("Entry not found."));
            }

            var AsArray = (JArray)Result[AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY];

            for (int i = 0; i < AsArray.Count; i++)
            {
                var AsStr = (string)AsArray[i];
                if (AsStr != null)
                {
                    if (AsStr.StartsWith(Controller_AttributeTables.MODEL_METADATA_PREFIX))
                    {
                        AsStr = AsStr.Substring(Controller_AttributeTables.MODEL_METADATA_PREFIX.Length);
                    }
                    else if (AsStr.StartsWith(Controller_AttributeTables.REVISION_METADATA_PREFIX))
                    {
                        AsStr = AsStr.Substring(Controller_AttributeTables.REVISION_METADATA_PREFIX.Length);
                        AsStr = AsStr.Replace(Controller_AttributeTables.REVISION_METADATA_MRV_DELIMITER, "->");
                    }

                    AsArray[i] = AsStr;
                }
            }

            return(BWebResponse.StatusOK("Model(s) have been located.", new JObject()
            {
                [AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY] = AsArray
            }));
        }
Пример #11
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "POST" && _Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("Model_GetUpdateDeleteRevision: GET, POST and DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET, POST and DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

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

            if (!int.TryParse(RestfulUrlParameters[RestfulUrlParameter_RevisionsKey], out RequestedRevisionIndex))
            {
                return(BWebResponse.BadRequest("Revision index must be an integer."));
            }

            if (_Context.Request.HttpMethod == "GET")
            {
                return(GetRevisionInfo(_ErrorMessageAction));
            }
            else
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                BWebServiceResponse Result;
                if (_Context.Request.HttpMethod == "DELETE")
                {
                    Result = DeleteRevision(_Context, _ErrorMessageAction);
                }
                else
                {
                    Result = UpdateRevisionInfo(_Context, _ErrorMessageAction);
                }

                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction);

                return(Result);
            }
        }
Пример #12
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                string ApiPassthroughPublicEndpoint = null;
                string CADFileServiceEndpoint       = null;

                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("SetCallRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                JObject ParsedBody;

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

                if (!ParsedBody.ContainsKey(InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY) &&
                    !ParsedBody.ContainsKey(InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY))
                {
                    _ErrorMessageAction?.Invoke("SetCallRequest-> Request does not have required fields.");
                    return(BWebResponse.BadRequest("Request does not have required fields."));
                }

                var LocalErrorMessage = "";

                if (ParsedBody.ContainsKey(InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY))
                {
                    ApiPassthroughPublicEndpoint = (string)ParsedBody[InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY];
                    if (!Process_SetApiPassthroughPublicEndpoint((string _Message) => { LocalErrorMessage = _Message; }, ApiPassthroughPublicEndpoint))
                    {
                        return(BWebResponse.InternalError(LocalErrorMessage));
                    }
                }
                if (ParsedBody.ContainsKey(InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY))
                {
                    CADFileServiceEndpoint = (string)ParsedBody[InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY];
                    if (!Process_SetCADFileServicePublicEndpoint((string _Message) => { LocalErrorMessage = _Message; }, CADFileServiceEndpoint))
                    {
                        return(BWebResponse.InternalError(LocalErrorMessage));
                    }
                }

                return(BWebResponse.StatusOK("Ok."));
            }
Пример #13
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("CreateTestUser: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                return(OnRequest_CreateTestUser(_Context, _ErrorMessageAction));
            }
Пример #14
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("User_CreateListUsers: GET and PUT methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and PUT methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            if (_Context.Request.HttpMethod == "GET")
            {
                return(ListUsers(_ErrorMessageAction));
            }
            //Atomicness handled inside the function
            return(CreateUser(_Context, _ErrorMessageAction));
        }
Пример #15
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("DeleteTestUser: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                JObject ParsedBody;

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

                if (!ParsedBody.ContainsKey(AuthDBEntry.USER_ID_PROPERTY))
                {
                    _ErrorMessageAction?.Invoke("DeleteTestUser-> Request does not have required fields.");
                    return(BWebResponse.BadRequest("Request does not have required fields."));
                }

                var UserId = (string)ParsedBody[AuthDBEntry.USER_ID_PROPERTY];

                if (!DeleteUser(UserId, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("User delete process has been failed."));
                }

                return(BWebResponse.StatusCreated("Test user has been deleted.", new JObject()
                {
                    [AuthDBEntry.USER_ID_PROPERTY] = UserId
                }));
            }
Пример #16
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("Model_AddListModels: GET and PUT methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and PUT methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            if (_Context.Request.HttpMethod == "GET")
            {
                return(ListModels(_ErrorMessageAction));
            }
            return(CreateModel(_Context, _ErrorMessageAction)); //Atomicness handled inside
        }
Пример #17
0
        protected override BWebServiceResponse OnRequestPP(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("ListRegisteredUserEmails: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            if (!DatabaseService.ScanTable(UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), out List <JObject> Result, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("ScanTable has failed."));
            }
            if (Result == null)
            {
                return(BWebResponse.StatusOK("Ok.", new JObject()
                {
                    ["emailAddresses"] = new JArray()
                }));
            }

            var FinalResultArray = new JArray();

            foreach (var Current in Result)
            {
                if (Current != null &&
                    Current.ContainsKey(UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL) &&
                    Current.ContainsKey(UserDBEntry.KEY_NAME_USER_ID))
                {
                    FinalResultArray.Add(
                        new JObject()
                    {
                        [UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL] = (string)Current[UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL],
                        [UserDBEntry.KEY_NAME_USER_ID] = (string)Current[UserDBEntry.KEY_NAME_USER_ID]
                    });
                }
            }
            return(BWebResponse.StatusOK("Ok.", new JObject()
            {
                ["emailAddresses"] = FinalResultArray
            }));
        }
Пример #18
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "POST" && _Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("User_GetUpdateDeleteUser: GET, POST and DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET, POST and DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            RequestedUserID = RestfulUrlParameters[RestfulUrlParameter_UsersKey];

            if (_Context.Request.HttpMethod == "GET")
            {
                return(GetUserInfo(_ErrorMessageAction));
            }
            else if (_Context.Request.HttpMethod == "DELETE")
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                var Result = DeleteUser(_Context, out bool bSetClearanceForApiKeys, out List <string> ApiKeys, _ErrorMessageAction);

                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);
                if (bSetClearanceForApiKeys)
                {
                    foreach (var ApiKey in ApiKeys)
                    {
                        Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + ApiKey, _ErrorMessageAction);
                    }
                }

                return(Result);
            }
            //Atomicness handled inside the function
            return(UpdateUserInfo(_Context, _ErrorMessageAction));
        }
Пример #19
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("SSOAzureTokenRefreshRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);

                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method:  " + _Context.Request.HttpMethod));
            }

            if (!BWebUtilities.DoesContextContainHeader(out List <string> ClientAuthorizationHeaderValues, out string _, _Context, "client-authorization") ||
                !BUtility.CheckAndGetFirstStringFromList(ClientAuthorizationHeaderValues, out string ClientAuthorization) ||
                ClientAuthorization.Length == 0)
            {
                return(BWebResponse.BadRequest("Authorization header must be set validly."));
            }

            //Check and try refresh if expired
            if (new Controller_SSOAccessToken(ClientAuthorization, DatabaseService, MemoryService, AzureAD_AppID, AzureAD_ClientSecret, SSOSuperAdmins, _ErrorMessageAction)
                .PerformCheckAndRefresh(
                    out Controller_SSOAccessToken.EPerformCheckAndRefreshSuccessStatus SuccessStatus,
                    out ClientAuthorization,
                    out string UserID,
                    out string EmailAddressWithoutPostfix) &&
                ClientAuthorization != null && ClientAuthorization.Length > 0)
            {
                return(BWebResponse.StatusOK("Success.", new JObject()
                {
                    ["token"] = ClientAuthorization,
                    ["status"] = SuccessStatus == Controller_SSOAccessToken.EPerformCheckAndRefreshSuccessStatus.Refreshed ? "Refreshed" : "AlreadyValid",
                    ["userId"] = UserID,
                    ["email"] = EmailAddressWithoutPostfix
                }));
            }

            return(BWebResponse.Unauthorized("Please re-login."));
        }
Пример #20
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("AccessCheckRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            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("AccessCheckRequest-> 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."));
                }
            }

            if (!ParsedBody.ContainsKey("forUrlPath") ||
                !ParsedBody.ContainsKey("requestMethod") ||
                !ParsedBody.ContainsKey("authorization"))
            {
                _ErrorMessageAction?.Invoke("AccessCheckRequest-> Request does not have required fields.");
                return(BWebResponse.BadRequest("Request does not have required fields."));
            }

            return(OnRequest_Internal_Logic(ParsedBody, _ErrorMessageAction));
        }
Пример #21
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("LoginRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody;

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

            if (!ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY) &&
                ((!ParsedBody.ContainsKey(AuthMethod.USER_NAME_PROPERTY) && !ParsedBody.ContainsKey(AuthMethod.USER_EMAIL_PROPERTY)) || !ParsedBody.ContainsKey(AuthMethod.PASSWORD_MD5_PROPERTY)))
            {
                _ErrorMessageAction?.Invoke("LoginRequest-> Request does not have required fields.");
                return(BWebResponse.BadRequest("Request does not have required fields."));
            }

            string Method;

            if (ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY))
            {
                var ApiKey = (string)ParsedBody[AuthMethod.API_KEY_PROPERTY];
                Method = ApiKey;
            }
            else
            {
                var PasswordMD5 = ((string)ParsedBody[AuthMethod.PASSWORD_MD5_PROPERTY]).ToLower();

                if (ParsedBody.ContainsKey(UserDBEntry.USER_NAME_PROPERTY))
                {
                    Method = (string)ParsedBody[UserDBEntry.USER_NAME_PROPERTY] + PasswordMD5;
                }
                else
                {
                    Method = ((string)ParsedBody[UserDBEntry.USER_EMAIL_PROPERTY]).ToLower() + PasswordMD5;
                }
            }

            if (!AuthenticationCommon.FetchUserInfoFromMemoryService_ByMethod(MemoryService, Method, out string UserID, out string _, out string _, _ErrorMessageAction))
            {
                if (!AuthenticationCommon.FetchUserInfoFromDatabaseService_ByMethod(DatabaseService, MemoryService, Method, out UserID, out _, out _, out BWebServiceResponse FailureResponse, _ErrorMessageAction))
                {
                    return(FailureResponse);
                }
            }

            if (!BUtility.CalculateStringMD5(BUtility.RandomString(32, true), out string AccessTokenMD5, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Hash operation failed."));
            }

            var AccessTokenMD5WithTokenType = "Basic " + AccessTokenMD5;

            var QueryParameters = new BMemoryQueryParameters()
            {
                Domain     = Resources_DeploymentManager.Get().GetDeploymentBranchNameEscapedLoweredWithDash().ToUpper(),
                SubDomain  = "SELF_SIGNED_ACCESS_TOKEN_VALIDATION",
                Identifier = AccessTokenMD5WithTokenType
            };

            MemoryService.SetKeyValue(QueryParameters, new Tuple <string, BPrimitiveType>[]
            {
                new Tuple <string, BPrimitiveType>("method", new BPrimitiveType(Method))
            },
                                      _ErrorMessageAction);

            MemoryService.SetKeyExpireTime(QueryParameters, TimeSpan.FromHours(1), _ErrorMessageAction);

            return(BWebResponse.StatusOK("Login successful.", new JObject()
            {
                ["userId"] = UserID,
                ["token"] = AccessTokenMD5WithTokenType
            }));
        }
Пример #22
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("StopProcessRequest: POST methods is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST methods is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            string BucketName       = null;
            string RelativeFilename = null;
            string ConversionID_FromRelativeUrl_UrlEncoded = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                var NewObjectJson = new JObject();

                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());

                        if (!ParsedBody.ContainsKey("bucketName") ||
                            !ParsedBody.ContainsKey("rawFileRelativeUrl"))
                        {
                            return(BWebResponse.BadRequest("Request body must contain all necessary fields."));
                        }
                        var BucketNameToken         = ParsedBody["bucketName"];
                        var RawFileRelativeUrlToken = ParsedBody["rawFileRelativeUrl"];
                        if (BucketNameToken.Type != JTokenType.String ||
                            RawFileRelativeUrlToken.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request body contains invalid fields."));
                        }
                        BucketName = (string)BucketNameToken;
                        ConversionID_FromRelativeUrl_UrlEncoded = WebUtility.UrlEncode((string)RawFileRelativeUrlToken);
                        RelativeFilename = (string)RawFileRelativeUrlToken;
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            //Temporarily, TODO: Change this when the implementation is in place.
            if (!DatabaseService.DeleteItem(
                    FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                    FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                    new BPrimitiveType(ConversionID_FromRelativeUrl_UrlEncoded),
                    out JObject _, EBReturnItemBehaviour.DoNotReturn,
                    _ErrorMessageAction))
            {
                if (!DatabaseService.GetItem(
                        FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                        FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                        new BPrimitiveType(ConversionID_FromRelativeUrl_UrlEncoded),
                        FileConversionDBEntry.Properties,
                        out JObject _ReturnObject,
                        _ErrorMessageAction) ||
                    _ReturnObject != null)
                {
                    return(BWebResponse.InternalError("Database error."));
                }
            }

            if (!BatchProcessingCreationService.Instance.StopBatchProcess(BucketName, RelativeFilename, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Failed to stop pod or connect to kubernetess"));
            }

            return(BWebResponse.StatusAccepted("Request has been accepted; process is now being stopped."));
        }
Пример #23
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("GetUserIDsFromEmailsRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                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("GetUserIDsFromEmailsRequest-> 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."));
                    }
                }

                if (!ParsedBody.ContainsKey("emailAddresses") || ParsedBody["emailAddresses"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Invalid request body."));
                }
                var AsJArray = (JArray)ParsedBody["emailAddresses"];

                var EmailAddresses = new List <string>();

                foreach (var Token in AsJArray)
                {
                    if (Token.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Invalid request body."));
                    }

                    var EmailAddress = ((string)Token).ToLower();
                    if (!EmailAddresses.Contains(EmailAddress))
                    {
                        EmailAddresses.Add(EmailAddress);
                    }
                }

                if (EmailAddresses.Count == 0)
                {
                    return(BWebResponse.BadRequest("Empty emailAddresses field."));
                }

                var ResponseObject = new JObject();

                foreach (var Email in EmailAddresses)
                {
                    if (!DatabaseService.GetItem(
                            UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                            UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                            new BPrimitiveType(Email),
                            UniqueUserFieldsDBEntry.Properties,
                            out JObject ExistenceCheck,
                            _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed."));
                    }
                    if (ExistenceCheck == null)
                    {
                        return(BWebResponse.NotFound("A user with e-mail " + Email + " does not exist."));
                    }

                    ResponseObject[Email] = (string)ExistenceCheck[UserDBEntry.KEY_NAME_USER_ID];
                }

                return(BWebResponse.StatusOK("OK.", new JObject()
                {
                    ["map"] = ResponseObject
                }));
            }
Пример #24
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext Context, Action <string> _ErrorMessageAction = null)
        {
            if (Context.Request.HttpMethod != "POST" && Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("BPutSecretsRequest: POST/PUT methods are accepted. But received request method:  " + Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST/PUT methods are accepted. But received request method: " + Context.Request.HttpMethod));
            }

            JObject ParsedBody;

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

            if (ParsedBody.Count == 0)
            {
                _ErrorMessageAction?.Invoke("BPutSecretsRequest-> Request does not have any secret field.");
                return(BWebResponse.BadRequest("Request does not have secret field."));
            }

            var WaitUntilSignal = new ManualResetEvent(false);

            var CompletionStateStack = new ConcurrentStack <object>();

            for (int i = 0; i < ParsedBody.Count; i++)
            {
                CompletionStateStack.Push(new object());
            }

            var SucceedQueue = new ConcurrentQueue <string>();
            var FailedQueue  = new ConcurrentQueue <string>();

            foreach (var Pair in ParsedBody)
            {
                BTaskWrapper.Run(() =>
                {
                    using var MemStream = new MemoryStream();
                    using var MemWriter = new StreamWriter(MemStream);
                    MemWriter.Write(Pair.Value);
                    MemWriter.Flush();
                    MemStream.Position = 0;

                    if (FileService.UploadFile(
                            new BStringOrStream(MemStream, MemStream.Length),
                            SecretsStorageBucket,
                            Pair.Key,
                            EBRemoteFileReadPublicity.AuthenticatedRead,
                            null,
                            (string Message) =>
                    {
                        _ErrorMessageAction?.Invoke("BPutSecretsRequest->Error-> " + Message);
                    }))
                    {
                        SucceedQueue.Enqueue(Pair.Key);
                    }
                    else
                    {
                        FailedQueue.Enqueue(Pair.Key);
                    }

                    CompletionStateStack.TryPop(out object Ignore);
                    if (CompletionStateStack.Count == 0)
                    {
                        try
                        {
                            WaitUntilSignal.Set();
                        }
                        catch (Exception) { }
                    }
                });
            }

            try
            {
                WaitUntilSignal.WaitOne();
                WaitUntilSignal.Close();
            }
            catch (Exception) { }

            var ResultObject = new JObject
            {
                ["succeed"] = new JArray(),
                ["failed"]  = new JArray()
            };

            while (SucceedQueue.TryDequeue(out string SucceedKey))
            {
                ((JArray)ResultObject["succeed"]).Add(SucceedKey);
            }
            while (FailedQueue.TryDequeue(out string FailedKey))
            {
                ((JArray)ResultObject["failed"]).Add(FailedKey);
            }

            return(new BWebServiceResponse(
                       BWebResponse.Status_OK_Code,
                       new BStringOrStream(ResultObject.ToString()),
                       "application/json"));
        }
Пример #25
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            //Azure sends a GET request in case user does not have access set from Integral.
            if (_Context.Request.HttpMethod == "GET")
            {
                if (!UrlParameters.TryGetValue("redirect_url", out string RedirectUrlEncoded) || RedirectUrlEncoded.Length == 0)
                {
                    RedirectUrlEncoded = SSOAzureLoginRequest.DEFAULT_REDIRECT_URL_ENCODED;
                }

                return(SSOCommon.MakeCallerRedirected(WebUtility.UrlDecode(RedirectUrlEncoded), true, BWebResponse.Error_Unauthorized_Code, "You do not have access to this service."));
            }

            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("SSOLoginCallback: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            string ResponseContent = null;

            try
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        ResponseContent = ResponseReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("Error: SSOLoginCallback: Error occured during request body read. Message: " + e.Message + ", trace: " + e.StackTrace);
                return(BWebResponse.BadRequest("Request body must be provided correctly."));
            }

            if (ResponseContent == null)
            {
                return(BWebResponse.BadRequest("Request body must be provided."));
            }

            if (!Parse_FirstLeg_Authentication_Content(
                    ResponseContent,
                    out string AuthorizationCode_From_FirstLeg,
                    out BMemoryQueryParameters SSOStateUniqueID_QueryParameters,
                    out SSOStateMEntry SSOState,
                    out string LocalRedirectUrl_From_FirstLeg,
                    out string EmailAddress_From_FirstLeg,
                    out string AzureADUniqueID_From_FirstLeg,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, FailureResponse.StatusCode, FailureResponse.ResponseContent.String));
            }

            if (!Perform_SecondLeg_Authorization(
                    AuthorizationCode_From_FirstLeg,
                    SSOStateUniqueID_QueryParameters,
                    SSOState,
                    out AuthorizationResult SuccessResponse,
                    out FailureResponse,
                    _ErrorMessageAction))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, FailureResponse.StatusCode, FailureResponse.ResponseContent.String));
            }

            //Like: Bearer [accessToken]
            var NewAuthorizationField = SuccessResponse.TokenType + (char)32 + SuccessResponse.AccessToken;

            var AccessTokenManager = new Controller_SSOAccessToken(NewAuthorizationField, DatabaseService, MemoryService, AzureAD_AppID, AzureAD_ClientSecret, SSOSuperAdmins, _ErrorMessageAction);

            if (!AccessTokenManager.RegisterUser(out string _UserID, SuccessResponse.RefreshToken, SuccessResponse.ExpiresInSeconds))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, 500, "User registration has failed."));
            }

            return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, false, 0, null, _UserID, NewAuthorizationField));
        }
Пример #26
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                string  RequestPayload = null;
                JObject ParsedBody;

                try
                {
                    using (var InputStream = _Context.Request.InputStream)
                    {
                        using var ResponseReader = new StreamReader(InputStream);

                        RequestPayload = ResponseReader.ReadToEnd();
                        ParsedBody     = JObject.Parse(RequestPayload);
                    }
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist-> 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."));
                }

                //get UserModels from parsed request body
                var UserModelIDs = new List <string>();

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

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

                    var UserModelID = (string)CurrentUserModelID;
                    if (!UserModelIDs.Contains(UserModelID))
                    {
                        UserModelIDs.Add(UserModelID);
                    }
                }

                //get UserSharedModels from parsed request body
                var UserSharedModelIDs = new List <string>();

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

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

                    var UserSharedModelID = (string)CurrentUserSharedModelID;
                    if (!UserSharedModelIDs.Contains(UserSharedModelID))
                    {
                        UserSharedModelIDs.Add(UserSharedModelID);
                    }
                }

                var CheckedUserModelIDs = new JArray();

                foreach (var ModelID in UserModelIDs)
                {
                    var ModelKey = new BPrimitiveType(ModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            ModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserModelIDs.Contains(ModelID))
                    {
                        CheckedUserModelIDs.Add(ModelID);
                    }
                }

                var CheckedUserSharedModelIDs = new JArray();

                foreach (var SharedModelID in UserSharedModelIDs)
                {
                    var ModelKey = new BPrimitiveType(SharedModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            SharedModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user shared model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserSharedModelIDs.Contains(SharedModelID))
                    {
                        CheckedUserSharedModelIDs.Add(SharedModelID);
                    }
                }

                return(BWebResponse.StatusOK("Check models have successfully been completed.", new JObject()
                {
                    ["checkedUserModelIds"] = CheckedUserModelIDs,
                    ["checkedUserSharedModelIds"] = CheckedUserSharedModelIDs
                }));
            }
Пример #27
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("StartProcessRequest: POST methods is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST methods is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var NewDBEntry = new FileConversionDBEntry()
            {
                ConversionStatus = (int)EInternalProcessStage.Queued
            };

            string NewConversionID_FromRelativeUrl_UrlEncoded = null;
            string BucketName       = null;
            string RelativeFileName = null;
            string ZipMainAssembly  = "";

            using (var InputStream = _Context.Request.InputStream)
            {
                var NewObjectJson = new JObject();

                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());

                        if (!ParsedBody.ContainsKey("bucketName") ||
                            !ParsedBody.ContainsKey("rawFileRelativeUrl"))
                        {
                            return(BWebResponse.BadRequest("Request body must contain all necessary fields."));
                        }
                        var BucketNameToken         = ParsedBody["bucketName"];
                        var RawFileRelativeUrlToken = ParsedBody["rawFileRelativeUrl"];

                        if (BucketNameToken.Type != JTokenType.String ||
                            RawFileRelativeUrlToken.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request body contains invalid fields."));
                        }

                        if (ParsedBody.ContainsKey("zipTypeMainAssemblyFileNameIfAny"))
                        {
                            var ZipMainAssemblyToken = ParsedBody["zipTypeMainAssemblyFileNameIfAny"];

                            if (ZipMainAssemblyToken.Type != JTokenType.String)
                            {
                                return(BWebResponse.BadRequest("Request body contains invalid fields."));
                            }

                            ZipMainAssembly = (string)ZipMainAssemblyToken;
                        }

                        NewDBEntry.BucketName = (string)BucketNameToken;
                        NewConversionID_FromRelativeUrl_UrlEncoded = WebUtility.UrlEncode((string)RawFileRelativeUrlToken);

                        BucketName       = (string)BucketNameToken;
                        RelativeFileName = (string)RawFileRelativeUrlToken;
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }


            if (BucketName == null || RelativeFileName == null)
            {
                return(BWebResponse.InternalError("No BucketName or FileName"));
            }

            BDatabaseAttributeCondition UpdateCondition = DatabaseService.BuildAttributeNotExistCondition(FileConversionDBEntry.KEY_NAME_CONVERSION_ID);


            //If a process was completed (success or failure) then allow reprocessing
            //Only stop if a process is currently busy processing or already queued
            if (DatabaseService.GetItem(
                    FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                    FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                    new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
                    FileConversionDBEntry.Properties,
                    out JObject ConversionObject
                    ))
            {
                if (ConversionObject != null && ConversionObject.ContainsKey("conversionStatus"))
                {
                    EInternalProcessStage ExistingStatus = (EInternalProcessStage)(int)ConversionObject["conversionStatus"];

                    if (ExistingStatus == EInternalProcessStage.ProcessFailed || ExistingStatus == EInternalProcessStage.ProcessComplete)
                    {
                        UpdateCondition = null;
                    }
                }
            }

            if (!DatabaseService.UpdateItem(
                    FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                    FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                    new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
                    JObject.Parse(JsonConvert.SerializeObject(NewDBEntry)),
                    out JObject _ExistingObject, EBReturnItemBehaviour.DoNotReturn,
                    UpdateCondition,
                    _ErrorMessageAction))
            {
                return(BWebResponse.Conflict("File is already being processed/queued."));
            }

            try
            {
                if (BatchProcessingCreationService.Instance.StartBatchProcess(BucketName, RelativeFileName, ZipMainAssembly, out string _PodName, _ErrorMessageAction))
                {
                    //Code for initial method of starting optimizer after pixyz completes
                    //return BWebResponse.StatusAccepted("Request has been accepted; process is now being started.");
                    if (BatchProcessingCreationService.Instance.StartFileOptimizer(BucketName, RelativeFileName, _ErrorMessageAction))
                    {
                        return(BWebResponse.StatusAccepted("Request has been accepted; process is now being started."));
                    }
                    else
                    {
                        NewDBEntry.ConversionStatus = (int)EInternalProcessStage.ProcessFailed;

                        if (!DatabaseService.UpdateItem(
                                FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                                FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                                new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
                                JObject.Parse(JsonConvert.SerializeObject(NewDBEntry)),
                                out JObject _, EBReturnItemBehaviour.DoNotReturn,
                                null,
                                _ErrorMessageAction))
                        {
                            return(BWebResponse.InternalError("Failed to start the batch process and experienced a Database error"));
                        }

                        //Try kill pixyz pod that we have succeeded in creating
                        if (!BatchProcessingCreationService.Instance.TryKillPod(_PodName, "cip-batch"))
                        {
                            return(BWebResponse.InternalError("Failed to start the unreal optimizer and failed to kill pixyz pod"));
                        }

                        return(BWebResponse.InternalError("Failed to start the batch process and experienced a Database error"));
                    }
                }
                else
                {
                    NewDBEntry.ConversionStatus = (int)EInternalProcessStage.ProcessFailed;

                    if (!DatabaseService.UpdateItem(
                            FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                            FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                            new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
                            JObject.Parse(JsonConvert.SerializeObject(NewDBEntry)),
                            out JObject _, EBReturnItemBehaviour.DoNotReturn,
                            null,
                            _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Failed to start the batch process and experienced a Database error"));
                    }

                    return(BWebResponse.InternalError("Failed to start the batch process"));
                }
            }
Пример #28
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //GET is supported for easy calls from terraform scripts since it only has GET request support out of the box.
            //https://www.terraform.io/docs/providers/http/data_source.html
            //POST calls are recommended to use over GET.

            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("ScheduleRequest: GET and POST methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and POST methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody = null;

            if (_Context.Request.HttpMethod == "GET")
            {
                if (!UrlParameters.ContainsKey("serialized"))
                {
                    return(BWebResponse.BadRequest("Malformed request. Url parameters must contain serialized= key."));
                }

                try
                {
                    ParsedBody = JObject.Parse(WebUtility.UrlDecode(UrlParameters["serialized"]));
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace + ", Content: " + UrlParameters["serialized"]);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }
            }
            else
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }
            }

            if (!ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.URL_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY].Type != JTokenType.String ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.VERB_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.VERB_PROPERTY].Type != JTokenType.String ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.HEADERS_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.HEADERS_PROPERTY].Type != JTokenType.Object) ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.BODY_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.BODY_PROPERTY].Type != JTokenType.Object) ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY].Type != JTokenType.Integer ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY].Type != JTokenType.Boolean) ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY].Type != JTokenType.Array) ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY].Type != JTokenType.Integer)
            {
                return(BWebResponse.BadRequest("Request must contain all necessary fields validly. Given argument: " + ParsedBody.ToString()));
            }

            var    Body = new JObject();
            bool   bCancelRetryOnSuccess = true;
            var    CancelOnReturnCodes   = new JArray();
            string Url = (string)ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY];

            if (!Uri.TryCreate(Url, UriKind.Absolute, out Uri UriResult) ||
                (UriResult.Scheme != Uri.UriSchemeHttp && UriResult.Scheme != Uri.UriSchemeHttps))
            {
                return(BWebResponse.BadRequest("Given field " + ScheduledUrlTaskDBEntry.URL_PROPERTY + " is invalid. Given argument: " + ParsedBody.ToString()));
            }
            string Verb = (string)ParsedBody[ScheduledUrlTaskDBEntry.VERB_PROPERTY];

            if (Verb != "GET" && Verb != "POST" && Verb != "PUT" && Verb != "DELETE")
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.VERB_PROPERTY + " must be one of these: GET, POST, PUT, DELETE. Given argument: " + ParsedBody.ToString()));
            }

            JObject Headers;

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.HEADERS_PROPERTY))
            {
                Headers = (JObject)ParsedBody[ScheduledUrlTaskDBEntry.HEADERS_PROPERTY];
            }
            else
            {
                Headers = new JObject();
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.BODY_PROPERTY))
            {
                if (Verb == "GET" || Verb == "DELETE")
                {
                    return(BWebResponse.BadRequest("GET/DELETE requests cannot contain field " + ScheduledUrlTaskDBEntry.BODY_PROPERTY + ", given argument: " + ParsedBody.ToString()));
                }
                Body = (JObject)ParsedBody[ScheduledUrlTaskDBEntry.BODY_PROPERTY];
            }
            else if (Verb == "POST" || Verb == "PUT")
            {
                return(BWebResponse.BadRequest("POST/PUT requests must contain field " + ScheduledUrlTaskDBEntry.BODY_PROPERTY + ", given argument: " + ParsedBody.ToString()));
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY))
            {
                bCancelRetryOnSuccess = (bool)ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY];
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY))
            {
                CancelOnReturnCodes = (JArray)ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY];
                foreach (var Item in CancelOnReturnCodes)
                {
                    if (Item.Type != JTokenType.Integer)
                    {
                        return(BWebResponse.BadRequest("All elements of " + ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY + " must be integer"));
                    }
                }
            }

            int RetryCount = (int)ParsedBody[ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY];

            if (RetryCount < -1)
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY + " must be greater than or equal to -1. Given argument: " + ParsedBody.ToString()));
            }
            int RetryInSeconds = (int)ParsedBody[ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY];

            if (RetryInSeconds < 0)
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY + " must be greater than or equal to 0. Given argument: " + ParsedBody.ToString()));
            }

            if (!DatabaseService.UpdateItem(
                    ScheduledUrlTaskDBEntry.DBSERVICE_SCHEDULED_URL_TASKS_TABLE(),
                    ScheduledUrlTaskDBEntry.KEY_NAME_TASK_URL,
                    new BPrimitiveType(WebUtility.UrlEncode(Url)),
                    JObject.Parse(JsonConvert.SerializeObject(new ScheduledUrlTaskDBEntry()
            {
                Url = Url,
                Verb = Verb,
                Body = Body,
                Headers = Headers,
                RetryCount = RetryCount,
                bCancelRetryOnSuccess = bCancelRetryOnSuccess,
                CancelOnReturnCodes = CancelOnReturnCodes,
                RetryInSeconds = RetryInSeconds,
                ScheduledToTime = new DateTimeOffset(DateTime.UtcNow.AddSeconds(RetryInSeconds)).ToUnixTimeSeconds()
            })),
                    out _,
                    EBReturnItemBehaviour.DoNotReturn,
                    null,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database write operation has failed."));
            }

            return(BWebResponse.StatusOK("Task has been scheduled."));
        }
Пример #29
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext Context, Action <string> _ErrorMessageAction = null)
        {
            if (Context.Request.HttpMethod != "POST" && Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest: POST/DELETE method is accepted. But received request method:  " + Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST/DELETE method is accepted. But received request method: " + Context.Request.HttpMethod));
            }

            JObject ParsedBody;

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

            if (!ParsedBody.ContainsKey("keys"))
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest-> Request does not have keys field.");
                return(BWebResponse.BadRequest("Request does not have keys field."));
            }

            var ToBeDeletedKeys = (JArray)ParsedBody["keys"];

            if (ToBeDeletedKeys == null || ToBeDeletedKeys.Count == 0)
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest-> Request does not have keys array or elements.");
                return(BWebResponse.BadRequest("Request does not have keys array."));
            }

            var CompletionStateStack = new ConcurrentStack <object>();

            for (int i = 0; i < ToBeDeletedKeys.Count; i++)
            {
                CompletionStateStack.Push(new object());
            }

            var WaitUntilSignal = new ManualResetEvent(false);

            var SucceedQueue = new ConcurrentQueue <string>();
            var FailedQueue  = new ConcurrentQueue <string>();

            foreach (string ToBeDeletedKey in ToBeDeletedKeys)
            {
                BTaskWrapper.Run(() =>
                {
                    if (FileService.DeleteFile(
                            SecretsStorageBucket,
                            ToBeDeletedKey,
                            (string Message) =>
                    {
                        _ErrorMessageAction?.Invoke("BDeleteSecretsRequest->Error-> " + Message);
                    }))
                    {
                        SucceedQueue.Enqueue(ToBeDeletedKey);
                    }
                    else
                    {
                        FailedQueue.Enqueue(ToBeDeletedKey);
                    }

                    CompletionStateStack.TryPop(out object Ignore);
                    if (CompletionStateStack.Count == 0)
                    {
                        try
                        {
                            WaitUntilSignal.Set();
                        }
                        catch (Exception) { }
                    }
                });
            }

            try
            {
                WaitUntilSignal.WaitOne();
                WaitUntilSignal.Close();
            }
            catch (Exception) {}

            var ResultObject = new JObject
            {
                ["succeed"] = new JArray(),
                ["failed"]  = new JArray()
            };

            while (SucceedQueue.TryDequeue(out string SucceedKey))
            {
                ((JArray)ResultObject["succeed"]).Add(SucceedKey);
            }
            while (FailedQueue.TryDequeue(out string FailedKey))
            {
                ((JArray)ResultObject["failed"]).Add(FailedKey);
            }

            return(new BWebServiceResponse(
                       BWebResponse.Status_OK_Code,
                       new BStringOrStream(ResultObject.ToString()),
                       "application/json"));
        }