Example #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);
        }
Example #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);
            }
        }
Example #3
0
        public static bool GetProcessedFile(
            WebServiceBaseTimeoutable _Request,
            ENodeType _FileType,
            IBDatabaseServiceInterface _DatabaseService,
            IBFileServiceInterface _FileService,
            string _CadFileStorageBucketName,
            string _ModelID,
            int _RevisionIndex,
            out BWebServiceResponse _SuccessResponse,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _SuccessResponse = BWebResponse.InternalError("");

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(_Request.InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), _ModelID, _ErrorMessageAction))
            {
                _FailureResponse = BWebResponse.InternalError("Atomic operation control has failed.");
                return(false);
            }

            var bResult = GetProcessedFile_Internal(
                _FileType,
                _DatabaseService,
                _FileService,
                _CadFileStorageBucketName,
                _ModelID,
                _RevisionIndex,
                out _SuccessResponse,
                out _FailureResponse,
                _ErrorMessageAction);

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

            return(bResult);
        }
Example #4
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
            }));
        }
Example #5
0
        public BWebServiceResponse ProcessRequest(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            bDoNotGetDBClearance =
                BWebUtilities.DoesContextContainHeader(out List <string> DNGDBCs, out string _, _Context, "do-not-get-db-clearance") &&
                BUtility.CheckAndGetFirstStringFromList(DNGDBCs, out string DNGDBC) &&
                DNGDBC == "true";

            BTaskWrapper.Run(() =>
            {
                var Response = OnRequestCallback?.Invoke(_Context, _ErrorMessageAction);
                if (Response.HasValue)
                {
                    Responses.Enqueue(Response.Value);
                }

                try
                {
                    WaitUntilSignal.Set();
                }
                catch (Exception) { }
            });

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

            if (!Responses.TryDequeue(out BWebServiceResponse FirstResponse))
            {
                FirstResponse = BWebResponse.InternalError("Unexpected error in concurrence.");
            }
            return(FirstResponse);
        }
Example #6
0
        public static bool TryGettingModelID(
            IBDatabaseServiceInterface _DatabaseService,
            string _RequestedModelName,
            out string _ModelID,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction)
        {
            _FailureResponse = BWebResponse.InternalError("");
            _ModelID         = string.Empty;

            if (!_DatabaseService.GetItem(
                    UniqueFileFieldsDBEntry.DBSERVICE_UNIQUEFILEFIELDS_TABLE(),
                    UniqueFileFieldsDBEntry.KEY_NAME_MODEL_UNIQUE_NAME,
                    new BPrimitiveType(_RequestedModelName),
                    UniqueFileFieldsDBEntry.Properties,
                    out JObject ModelIDResponse,
                    _ErrorMessageAction) || !ModelIDResponse.ContainsKey(ModelDBEntry.KEY_NAME_MODEL_ID))
            {
                _FailureResponse = BWebResponse.InternalError("Model ID could not be retrieved from the database.");
                return(false);
            }

            _ModelID = (string)ModelIDResponse[ModelDBEntry.KEY_NAME_MODEL_ID];
            return(true);
        }
Example #7
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (!GetTokenForAzure(out string TokenType, out string AccessToken, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Acquiring access token from Azure has failed."));
                }

                if (!GetUserListFromAzure(out List <UserPrincipal> Users, TokenType, AccessToken, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Acquiring user list from Azure has failed."));
                }

                if (!FindMissingUsersInDatabase(out List <UserPrincipal> UsersToBePut, Users, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Acquiring difference in user list from Azure and system database has failed."));
                }

                foreach (var UserToBePut in UsersToBePut)
                {
                    if (!Controller_SSOAccessToken.RegisterUserAsPlaceholder(out string _, DatabaseService, UserToBePut.Email, UserToBePut.Name, SSOSuperAdmins, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Register user operation has failed."));
                    }
                }
                return(BWebResponse.StatusOK("Ok."));
            }
Example #8
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);
        }
Example #9
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);
            }
        }
Example #10
0
        private BWebServiceResponse ListBaseRightsForUser(Action <string> _ErrorMessageAction)
        {
            var UserKey = new BPrimitiveType(RequestedUserID);

            if (!DatabaseService.GetItem(
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserDBEntry.Properties,
                    out JObject UserObject,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
            }
            if (UserObject == null)
            {
                return(BWebResponse.NotFound("User does not exist."));
            }

            JArray BaseScopeArray;

            if (UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY))
            {
                BaseScopeArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY];
            }
            else
            {
                BaseScopeArray = new JArray();
            }

            return(BWebResponse.StatusOK("List base rights operation has succeeded.", new JObject()
            {
                [UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = BaseScopeArray
            }));
        }
Example #11
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);
            }
        }
Example #12
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."));
        }
Example #13
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));
        }
Example #14
0
        private BWebServiceResponse ListUsers(Action <string> _ErrorMessageAction)
        {
            if (!DatabaseService.ScanTable(UserDBEntry.DBSERVICE_USERS_TABLE(), out List <JObject> UsersJson, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Scan-table operation has failed."));
            }

            var Result     = new JObject();
            var UsersArray = new JArray();

            Result["users"] = UsersArray;

            foreach (var UserJson in UsersJson)
            {
                var DecimatedUserJson = new JObject();
                foreach (var GetKey in UserDBEntry.GetableProperties)
                {
                    DecimatedUserJson[GetKey] = UserJson[GetKey];
                }
                DecimatedUserJson[UserDBEntry.KEY_NAME_USER_ID] = UserJson[UserDBEntry.KEY_NAME_USER_ID];
                UsersArray.Add(DecimatedUserJson);
            }

            return(BWebResponse.StatusOK("List users operation has succeeded.", Result));
        }
Example #15
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"));
        }
Example #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")
            {
                _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
            }));
        }
Example #17
0
        public static bool FetchUserInfoFromDatabaseService_ByMethod(
            IBDatabaseServiceInterface _DatabaseService,
            IBMemoryServiceInterface _MemoryService,
            string _Method,
            out string _UserID,
            out string _UserEmail,
            out string _UserName,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _UserID          = null;
            _UserEmail       = null;
            _UserName        = null;
            _FailureResponse = new BWebServiceResponse();

            string ReturnedEntryAsString = null;

            if (!_DatabaseService.GetItem(
                    AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                    AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                    new BPrimitiveType(_Method),
                    AuthDBEntry.Properties,
                    out JObject ReturnedObject,
                    _ErrorMessageAction))
            {
                _FailureResponse = BWebResponse.InternalError("Database fetch operation has failed");
                return(false);
            }
            if (ReturnedObject == null)
            {
                _ErrorMessageAction?.Invoke("FetchFromDatabaseService: Given credentials are invalid: " + _Method);
                _FailureResponse = BWebResponse.Unauthorized("Given credentials are invalid.");
                return(false);
            }

            try
            {
                ReturnedEntryAsString = ReturnedObject.ToString();
                var ReturnedEntry = JsonConvert.DeserializeObject <AuthDBEntry>(ReturnedEntryAsString);
                _UserID    = ReturnedEntry.UserID;
                _UserEmail = ReturnedEntry.UserEmail;
                _UserName  = ReturnedEntry.UserName;
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("FetchFromDatabaseService: " + e.Message + ", Trace: " + e.StackTrace);
                _FailureResponse = BWebResponse.InternalError("Database fetch operation failed.");
                return(false);
            }

            _MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[]
            {
                new Tuple <string, BPrimitiveType>(AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY + _Method, new BPrimitiveType(ReturnedEntryAsString))
            },
                                       _ErrorMessageAction);

            return(true);
        }
Example #18
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."));
            }
Example #19
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);
            }
        }
Example #20
0
 private void TimeoutOccurred()
 {
     Responses.Enqueue(BWebResponse.InternalError("Database operation timed out."));
     try
     {
         WaitUntilSignal.Set();
     }
     catch (Exception) { }
 }
Example #21
0
        public BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            CachedContext = _Context;
            var Result = OnRequestCallback?.Invoke(_Context, _ErrorMessageAction);

            Controller_DeliveryEnsurer.Get().WaitUntilActionsCompleted(_Context, _ErrorMessageAction);
            if (OwnerProcessor.TryGetTarget(out WebServiceBaseTimeoutableProcessor StrongOwner))
            {
                Controller_AtomicDBOperation.Get().WaitUntilSetClearancesCompleted(StrongOwner, _ErrorMessageAction);
            }
            return(Result ?? BWebResponse.InternalError("WebServiceBaseTimeoutableDeliveryEnsurerUserProcessor has failed."));
        }
Example #22
0
        public static bool GetProcessedFileNode(
            WebServiceBaseTimeoutable _Request,
            ENodeType _FileType,
            IBDatabaseServiceInterface _DatabaseService,
            IBFileServiceInterface _FileService,
            string _CadFileStorageBucketName,
            string _ModelID,
            int _RevisionIndex,
            bool _bRootNodeRequested, ulong _NodeID,
            out BWebServiceResponse _SuccessResponse,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _SuccessResponse = BWebResponse.InternalError("");

            uint StartIndex = 0, Size = 0;

            if (!_bRootNodeRequested)
            {
                Convert.UniqueIDToStartIndexAndSize(_NodeID, out StartIndex, out Size);
                if (StartIndex == 0 || Size == 0)
                {
                    _FailureResponse = BWebResponse.BadRequest("Invalid Node ID.");
                    return(false);
                }
            }

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(_Request.InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), _ModelID, _ErrorMessageAction))
            {
                _FailureResponse = BWebResponse.InternalError("Atomic operation control has failed.");
                return(false);
            }

            var bResult = GetProcessedFileNode_Internal(
                _FileType,
                _DatabaseService,
                _FileService,
                _CadFileStorageBucketName,
                _ModelID,
                _RevisionIndex,
                _bRootNodeRequested,
                StartIndex,
                Size,
                out _SuccessResponse,
                out _FailureResponse,
                _ErrorMessageAction);

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

            return(bResult);
        }
Example #23
0
        public bool AddRemoveMetadataSets_AttributesTables(
            WebServiceBaseTimeoutableDeliveryEnsurerUserProcessor _Request,
            string _UserID,
            MetadataLocator _MetadataLocator,
            List <Metadata> _MetadataList_Ref,
            EAddRemove _Operation,
            EKillProcedureIfGetClearanceFails _KillProcedureIfGetClearanceFails,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _FailureResponse = BWebResponse.InternalError("");
            if (_MetadataList_Ref == null || _MetadataList_Ref.Count == 0)
            {
                return(true);
            }

            //Full copy
            var MetadataList_Local = new List <Metadata>();

            for (int i = 0; i < _MetadataList_Ref.Count; i++)
            {
                var Current = _MetadataList_Ref[i];
                MetadataList_Local.Add(new Metadata()
                {
                    MetadataKey    = Current.MetadataKey,
                    MetadataValues = new List <string>(Current.MetadataValues)
                });
            }

            var OperationInstance = new AddRemoveMetadataSets_AttributesTables_Operation();

            if (!OperationInstance.ClearanceInstance.GetClearanceForAll(_Request, MetadataList_Local, _ErrorMessageAction))
            {
                if (_KillProcedureIfGetClearanceFails == EKillProcedureIfGetClearanceFails.Yes)
                {
                    OperationInstance.ClearanceInstance.SetClearanceForObtained(_ErrorMessageAction);
                    _FailureResponse = BWebResponse.InternalError("Atomic operation control has failed.");
                    return(false);
                }
            }
            //From now on, there should not be a case that it returns false.

            OperationInstance.ProcedureInstance.Perform(_Request.CachedContext, _Operation, MetadataList_Local, _MetadataLocator, _UserID);

            OperationInstance.ClearanceInstance.SetClearanceForObtained(_ErrorMessageAction);

            return(true);
        }
Example #24
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
                }));
            }
Example #25
0
 private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
 {
     try
     {
         if (BatchProcessingService.Instance.CheckProcessComplete())
         {
             return(BWebResponse.StatusOK(BatchProcessingService.Instance.State));
         }
         else
         {
             return(BWebResponse.NotAcceptable("Queue not ready"));
         }
     }
     catch (Exception ex)
     {
         _ErrorMessageAction?.Invoke($"{ex.Message}\n{ex.StackTrace}");
         return(BWebResponse.InternalError("Failed to get state"));
     }
 }
Example #26
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
        }
Example #27
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
            }));
        }
Example #28
0
        private BWebServiceResponse ListModels(Action <string> _ErrorMessageAction)
        {
            if (!DatabaseService.ScanTable(ModelDBEntry.DBSERVICE_MODELS_TABLE(), out List <JObject> ModelsJson, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Scan-table operation has failed."));
            }

            var Result      = new JObject();
            var ModelsArray = new JArray();

            Result["models"] = ModelsArray;

            foreach (var ModelJson in ModelsJson)
            {
                var AsModel = JsonConvert.DeserializeObject <ModelDBEntry>(ModelJson.ToString());
                AsModel.Prune_NonGettableProperties();
                ModelsArray.Add(JObject.Parse(ModelJson.ToString()));
            }

            return(BWebResponse.StatusOK("List models operation has succeeded.", Result));
        }
Example #29
0
            private BWebServiceResponse OnRequest_CreateTestUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
            {
                string OptionalName        = BUtility.RandomString(12, true) + "_test";
                string EmailWithoutPostfix = OptionalName + "@test.com";

                var AccumulatedSSOMethodRightsOrDefault = new JArray()
                {
                    JObject.Parse(JsonConvert.SerializeObject(
                                      new AccessScope()
                    {
                        WildcardPath = "*",
                        AccessRights = new List <string>()
                        {
                            "GET", "POST", "PUT", "DELETE"
                        }
                    }))
                };

                if (!CreateUser(out string _UserID, EmailWithoutPostfix, _ErrorMessageAction, OptionalName))
                {
                    return(BWebResponse.InternalError("User creation process has been failed."));
                }

                if (!CreateAuthMethod(out string _ApiKey, _UserID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Auth method creation process has been failed."));
                }

                if (!Controller_Rights_Internal.Get().GrantUserWithRights(false, _UserID, AccumulatedSSOMethodRightsOrDefault, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Grant user with rights process has been failed."));
                }

                return(BWebResponse.StatusCreated("User has been created.", new JObject()
                {
                    [UserDBEntry.KEY_NAME_USER_ID] = _UserID,
                    [AuthMethod.API_KEY_PROPERTY] = _ApiKey,
                    [AuthMethod.USER_EMAIL_PROPERTY] = EmailWithoutPostfix
                }));
            }
Example #30
0
        public static bool TryGettingAllInfo(
            IBDatabaseServiceInterface _DatabaseService,
            string _ModelID,
            int _RevisionIndex,
            out ModelDBEntry _ModelObject,
            out Revision _RevisionObject,
            out int _RevisionListIx,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _RevisionObject  = null;
            _RevisionListIx  = -1;
            _FailureResponse = BWebResponse.InternalError("");

            if (!TryGettingModelInfo(
                    _DatabaseService,
                    _ModelID,
                    out JObject _,
                    true, out _ModelObject,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                _FailureResponse = FailureResponse;
                return(false);
            }

            if (!DoesRevisionExist(
                    _ModelObject,
                    _RevisionIndex,
                    out _RevisionObject,
                    out _RevisionListIx))
            {
                _FailureResponse = BWebResponse.NotFound("Revision does not exist.");
                return(false);
            }

            return(true);
        }