Example #1
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 #2
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 #3
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 #4
0
        private BWebServiceResponse ListRevisions(Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            var Result = new JArray();

            foreach (var Rev in Model.ModelRevisions)
            {
                Rev.Prune_NonGettableProperties();
                Result.Add(JObject.Parse(JsonConvert.SerializeObject(Rev)));
            }

            return(BWebResponse.StatusOK("List revisions operation has succeeded", new JObject()
            {
                [ModelDBEntry.MODEL_REVISIONS_PROPERTY] = Result
            }));
        }
Example #5
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 #6
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 #7
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 #8
0
        private BWebServiceResponse GetRevisionInfo(Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!CommonMethods.DoesRevisionExist(
                    Model,
                    RequestedRevisionIndex,
                    out Revision RevisionObject,
                    out int _))
            {
                return(BWebResponse.NotFound("Revision does not exist."));
            }

            RevisionObject.Prune_NonGettableProperties();

            return(BWebResponse.StatusOK("Get revision operation has succeeded.", JObject.Parse(JsonConvert.SerializeObject(RevisionObject))));
        }
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                Cleanup_UniqueFileFields(_ErrorMessageAction);
                //Cleanup_AttributeTables(_ErrorMessageAction);

                return(BWebResponse.StatusOK("OK."));
            }
Example #16
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 #17
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 #18
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 #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")
            {
                _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 #20
0
 protected override BWebServiceResponse OnRequestPP(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
 {
     if (UrlParameters.ContainsKey("secret") && UrlParameters["secret"] == InternalCallPrivateKey)
     {
         return(Process(_Context, _ErrorMessageAction));
     }
     return(BWebResponse.Forbidden("You are trying to access to a private service."));
 }
Example #21
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                Cleanup_AuthMethods(_ErrorMessageAction);
                Cleanup_UniqueUserFields(_ErrorMessageAction);
                Cleanup_UserModels(_Context, _ErrorMessageAction);

                return(BWebResponse.StatusOK("OK."));
            }
Example #22
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 #23
0
 private void TimeoutOccurred()
 {
     Responses.Enqueue(BWebResponse.InternalError("Database operation timed out."));
     try
     {
         WaitUntilSignal.Set();
     }
     catch (Exception) { }
 }
Example #24
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 #25
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 #26
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));
            }
Example #27
0
        private BWebServiceResponse DeleteRevision(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!CommonMethods.DoesRevisionExist(
                    Model,
                    RequestedRevisionIndex,
                    out Revision RevisionObject,
                    out int ModelRevisionListIx))
            {
                return(BWebResponse.NotFound("Revision does not exist."));
            }

            Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelRevisionFileEntryDeleteAll
                                                               (
                                                                   RequestedModelID,
                                                                   RequestedRevisionIndex,
                                                                   Model.ModelOwnerUserID,
                                                                   Model.ModelSharedWithUserIDs,
                                                                   AuthorizedUser.UserID,
                                                                   JObject.Parse(JsonConvert.SerializeObject(RevisionObject.FileEntry))
                                                               ),
                                                               _ErrorMessageAction);

            Model.ModelRevisions.RemoveAt(ModelRevisionListIx);
            Model.MRVLastUpdateTime = CommonMethods.GetTimeAsCreationTime();

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

            Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelRevisionDeleted
                                                               (
                                                                   RequestedModelID,
                                                                   RequestedRevisionIndex,
                                                                   Model.ModelOwnerUserID,
                                                                   Model.ModelSharedWithUserIDs,
                                                                   AuthorizedUser.UserID
                                                               ),
                                                               _ErrorMessageAction);

            return(BWebResponse.StatusOK("Revision has been deleted."));
        }
Example #28
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 #29
0
        private BWebServiceResponse ProcessRequestLocked(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

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

            RequestedUserID = RestfulUrlParameters[RestfulUrlParameter_UserIDKey];

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

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

            if (!Model.ModelSharedWithUserIDs.Remove(RequestedUserID))
            {
                return(BWebResponse.NotFound("Given userId is not among sharees of the model."));
            }

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

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

            return(BWebResponse.StatusOK("Operation has been completed."));
        }
Example #30
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);
        }