예제 #1
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
            }));
        }
예제 #2
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
            }));
        }
예제 #3
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))));
        }
예제 #4
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."));
            }
예제 #5
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."));
        }
예제 #6
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                Cleanup_UniqueFileFields(_ErrorMessageAction);
                //Cleanup_AttributeTables(_ErrorMessageAction);

                return(BWebResponse.StatusOK("OK."));
            }
예제 #7
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));
        }
예제 #8
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
            }));
        }
예제 #9
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("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
            }));
        }
예제 #10
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."));
            }
예제 #11
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."));
            }
예제 #12
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."));
        }
예제 #13
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."));
        }
예제 #14
0
        protected override BWebServiceResponse OnRequestPP(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            _ErrorMessageAction?.Invoke($"InternalWebServiceBaseWebhook->OnRequest: Message received. HttpMethod: {_Context.Request.HttpMethod}");

            // Cloud Event Schema v1.0
            // https://github.com/cloudevents/spec/blob/v1.0/http-webhook.md#4-abuse-protection
            if (_Context.Request.HttpMethod == "OPTIONS")
            {
                var WebhookRequestCallbak = _Context.Request.Headers.Get("webhook-request-callback");
                var WebhookRequestOrigin  = _Context.Request.Headers.Get("webhook-request-origin");

                BTaskWrapper.Run(() =>
                {
                    Thread.CurrentThread.IsBackground = true;

                    Thread.Sleep(3000);
                    using var Handler = new HttpClientHandler
                          {
                              SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
                              ServerCertificateCustomValidationCallback = (a, b, c, d) => true
                          };
                    using var Client = new HttpClient(Handler);
                    Client.DefaultRequestHeaders.TryAddWithoutValidation("WebHook-Allowed-Origin", WebhookRequestOrigin);
                    Client.DefaultRequestHeaders.TryAddWithoutValidation("WebHook-Allowed-Rate", "*");
                    using (var RequestTask = Client.GetAsync(WebhookRequestCallbak))
                    {
                        RequestTask.Wait();
                        using var Response        = RequestTask.Result;
                        using var ResponseContent = Response.Content;

                        using var ReadResponseTask = ResponseContent.ReadAsStringAsync();
                        ReadResponseTask.Wait();

                        var ResponseString        = ReadResponseTask.Result;
                        var ResponseStatusCode    = (int)Response.StatusCode;
                        var ResponseSuccessString = Response.IsSuccessStatusCode ? "Request is successful." : "Request has an error.";
                        _ErrorMessageAction?.Invoke($"InternalWebServiceBaseWebhook->ValidationRequest: {ResponseSuccessString} Origin: '{WebhookRequestOrigin}', Response: '{ResponseString}', Code: '{ResponseStatusCode}'");
                    }
                });

                return(BWebResponse.StatusOK("OK."));
            }

            if (UrlParameters.ContainsKey("secret") && UrlParameters["secret"] == InternalCallPrivateKey)
            {
                return(Process(_Context, _ErrorMessageAction));
            }

            return(BWebResponse.Forbidden("You are trying to access to a private service."));
        }
예제 #15
0
        private BWebServiceResponse GetModelInfo(Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            Model.Prune_NonGettableProperties();

            return(BWebResponse.StatusOK("Get model operation has succeeded.", JObject.Parse(JsonConvert.SerializeObject(Model))));
        }
예제 #16
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"));
     }
 }
예제 #17
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //Any verb is accepted.

            var StartTimestamp = MSSinceEpoch();

            if (!DatabaseService.ScanTable(
                    ScheduledUrlTaskDBEntry.DBSERVICE_SCHEDULED_URL_TASKS_TABLE(),
                    out List <JObject> URLTasks_UrlEncoded,
                    _ErrorMessageAction))
            {
                return(BWebResponse.StatusOK("Table does not exist or ScanTable operation has failed.")); //Still ok.
            }
            if (URLTasks_UrlEncoded.Count == 0)
            {
                return(BWebResponse.StatusOK("There is no task in the database."));
            }

            var URLTasks = new List <ScheduledUrlTaskDBEntry>();

            foreach (var Current in URLTasks_UrlEncoded)
            {
                URLTasks.Add(JsonConvert.DeserializeObject <ScheduledUrlTaskDBEntry>(Current.ToString()));
            }

            long RemainedMS = 50000 - (MSSinceEpoch() - StartTimestamp); //60-50=10 seconds is for possible delays.

            while (RemainedMS > 0)
            {
                var BeforeTS = MSSinceEpoch();
                SecondCheck(_Context, URLTasks, _ErrorMessageAction);

                var Diff = MSSinceEpoch() - BeforeTS;
                if (Diff < 10000)
                {
                    Thread.Sleep(10000 - (int)Diff);
                }
                RemainedMS -= (MSSinceEpoch() - BeforeTS);
            }

            return(BWebResponse.StatusAccepted("Request has been accepted."));
        }
예제 #18
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
            }));
        }
예제 #19
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));
        }
예제 #20
0
        private BWebServiceResponse GetRawFile(Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryGettingAllInfo(
                    DatabaseService,
                    RequestedModelID,
                    RequestedRevisionIndex,
                    out ModelDBEntry _,
                    out Revision RevisionObject,
                    out int _,
                    out BWebServiceResponse _FailureResponse,
                    _ErrorMessageAction))
            {
                return(_FailureResponse);
            }

            if (RevisionObject.FileEntry.FileProcessStage == (int)Constants.EProcessStage.NotUploaded)
            {
                return(BWebResponse.NotFound("Raw file has not been uploaded yet."));
            }

            if (!FileService.CreateSignedURLForDownload(
                    out string DownloadUrl,
                    CadFileStorageBucketName,
                    RevisionObject.FileEntry.RawFileRelativeUrl,
                    FileEntry.EXPIRY_MINUTES,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Signed url generation has failed."));
            }

            return(BWebResponse.StatusOK("File has been located and download link has been generated.", new JObject()
            {
                [FileEntry.FILE_DOWNLOAD_URL_PROPERTY] = DownloadUrl,
                [FileEntry.FILE_DOWNLOAD_UPLOAD_EXPIRY_MINUTES_PROPERTY] = FileEntry.EXPIRY_MINUTES
            }));
        }
예제 #21
0
        private BWebServiceResponse GetUserInfo(Action <string> _ErrorMessageAction)
        {
            var UserKey = new BPrimitiveType(RequestedUserID);

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

            //Append id
            UserObject[UserDBEntry.KEY_NAME_USER_ID] = RequestedUserID;

            return(BWebResponse.StatusOK("Get user information operation has succeeded.", UserObject));
        }
예제 #22
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("SSOAzureTokenRefreshRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);

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

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

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

            return(BWebResponse.Unauthorized("Please re-login."));
        }
예제 #23
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //GET is supported for easy calls from terraform scripts since it only has GET request support out of the box.
            //https://www.terraform.io/docs/providers/http/data_source.html
            //POST calls are recommended to use over GET.

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

            JObject ParsedBody = null;

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

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

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

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

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

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

            JObject Headers;

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

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

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

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

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

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

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

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

            return(BWebResponse.StatusOK("Task has been scheduled."));
        }
예제 #24
0
        private BWebServiceResponse DeleteUser(HttpListenerContext _Context, out bool _bSetClearanceForApiKeys, out List <string> _ApiKeys, Action <string> _ErrorMessageAction)
        {
            _bSetClearanceForApiKeys = false;
            _ApiKeys = new List <string>();

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

            var UserData = JsonConvert.DeserializeObject <UserDBEntry>(UserObject.ToString());

            if (UserData.AuthMethods != null && UserData.AuthMethods.Count > 0)
            {
                foreach (var AMethod in UserData.AuthMethods)
                {
                    string OldField = null;

                    BPrimitiveType AuthMethodKey = null;
                    switch (AMethod.Method)
                    {
                    case AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD:
                    {
                        AuthMethodKey = new BPrimitiveType(AMethod.UserEmail + AMethod.PasswordMD5);
                        OldField      = AMethod.UserEmail;
                        break;
                    }

                    case AuthMethod.Methods.USER_NAME_PASSWORD_METHOD:
                    {
                        AuthMethodKey = new BPrimitiveType(AMethod.UserName + AMethod.PasswordMD5);
                        OldField      = AMethod.UserName;
                        break;
                    }

                    case AuthMethod.Methods.API_KEY_METHOD:
                    {
                        AuthMethodKey = new BPrimitiveType(AMethod.ApiKey);

                        _bSetClearanceForApiKeys = true;
                        _ApiKeys.Add(AMethod.ApiKey);

                        if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + AMethod.ApiKey, _ErrorMessageAction))
                        {
                            return(BWebResponse.InternalError("Atomic operation control has failed."));
                        }
                        break;
                    }
                    }

                    if (AuthMethodKey != null)
                    {
                        Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                            _Context,
                            AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                            AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                            AuthMethodKey);

                        MemoryService.DeleteKey(CommonData.MemoryQueryParameters, AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY + AuthMethodKey.AsString, _ErrorMessageAction);
                    }
                }
            }

            MemoryService.DeleteKey(CommonData.MemoryQueryParameters, UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID, _ErrorMessageAction);

            Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                _Context,
                UserDBEntry.DBSERVICE_USERS_TABLE(),
                UserDBEntry.KEY_NAME_USER_ID,
                UserKey);

            Controller_UserActions.Get().BroadcastUserAction(new Action_UserDeleted
                                                             (
                                                                 RequestedUserID,
                                                                 UserData.UserEmail,
                                                                 UserData.UserName,
                                                                 UserData.UserModels,
                                                                 UserData.UserSharedModels
                                                             ),
                                                             _ErrorMessageAction);

            if (UserData.UserEmail != null && UserData.UserEmail.Length > 0)
            {
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                    UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                    new BPrimitiveType(UserData.UserEmail));
            }
            if (UserData.UserName != null && UserData.UserName.Length > 0)
            {
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                    UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME,
                    new BPrimitiveType(UserData.UserName));
            }

            foreach (var ApiKey in _ApiKeys)
            {
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                    UniqueUserFieldsDBEntry.KEY_NAME_API_KEY,
                    new BPrimitiveType(ApiKey));
            }

            return(BWebResponse.StatusOK("User has been deleted."));
        }
예제 #25
0
        private BWebServiceResponse UpdateUserInfo_Internal(
            HttpListenerContext _Context,
            string _NewEmailChange,
            string _NewUserNameChange,
            JObject _UserObject,
            JObject _UpdateFieldsUserEntry, JObject _UpdateFieldsAuthEntry,
            Action <string> _ErrorMessageAction)
        {
            var UserKey = new BPrimitiveType(RequestedUserID);

            if (_UpdateFieldsUserEntry.Count > 0)
            {
                string OldEmail    = null;
                string OldUserName = null;

                if (_NewEmailChange != null && _UserObject.ContainsKey(UserDBEntry.USER_EMAIL_PROPERTY))
                {
                    OldEmail = (string)_UserObject[UserDBEntry.USER_EMAIL_PROPERTY];

                    Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                        _Context,
                        UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                        UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                        new BPrimitiveType(OldEmail));

                    Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                        _Context,
                        UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                        UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                        new BPrimitiveType(_NewEmailChange),
                        new JObject()
                    {
                        [UserDBEntry.KEY_NAME_USER_ID] = RequestedUserID
                    });
                }
                if (_NewUserNameChange != null && _UserObject.ContainsKey(UserDBEntry.USER_NAME_PROPERTY))
                {
                    OldUserName = (string)_UserObject[UserDBEntry.USER_NAME_PROPERTY];

                    Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                        _Context,
                        UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                        UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME,
                        new BPrimitiveType(OldUserName));

                    Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                        _Context,
                        UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                        UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME,
                        new BPrimitiveType(_NewUserNameChange),
                        new JObject()
                    {
                        [UserDBEntry.KEY_NAME_USER_ID] = RequestedUserID
                    });
                }

                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    _UpdateFieldsUserEntry);

                var NewEmail    = _NewEmailChange ?? (string)_UserObject[UserDBEntry.USER_EMAIL_PROPERTY];
                var NewUserName = _NewUserNameChange ?? (string)_UserObject[UserDBEntry.USER_NAME_PROPERTY];
                Controller_UserActions.Get().BroadcastUserAction(new Action_UserUpdated(
                                                                     RequestedUserID,
                                                                     OldEmail ?? NewEmail,
                                                                     NewEmail,
                                                                     OldUserName ?? NewUserName,
                                                                     NewUserName,
                                                                     _UpdateFieldsUserEntry), _ErrorMessageAction);
            }

            if (_UpdateFieldsAuthEntry.Count > 0)
            {
                var UserData = JsonConvert.DeserializeObject <UserDBEntry>(_UserObject.ToString());

                if (UserData.AuthMethods != null && UserData.AuthMethods.Count > 0)
                {
                    foreach (var Method in UserData.AuthMethods)
                    {
                        string PasswordMD5 = null;
                        string OldField    = null;

                        BPrimitiveType AuthMethodKey = null;
                        switch (Method.Method)
                        {
                        case AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD:
                        {
                            PasswordMD5   = Method.PasswordMD5;
                            OldField      = Method.UserEmail;
                            AuthMethodKey = new BPrimitiveType(Method.UserEmail + PasswordMD5);
                            break;
                        }

                        case AuthMethod.Methods.USER_NAME_PASSWORD_METHOD:
                        {
                            PasswordMD5   = Method.PasswordMD5;
                            OldField      = Method.UserName;
                            AuthMethodKey = new BPrimitiveType(Method.UserName + PasswordMD5);
                            break;
                        }

                        case AuthMethod.Methods.API_KEY_METHOD:
                            AuthMethodKey = new BPrimitiveType(Method.ApiKey);
                            break;
                        }
                        if (AuthMethodKey != null)
                        {
                            bool bRecreateNeed =
                                (_NewEmailChange != null && Method.Method == AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD) ||
                                (_NewUserNameChange != null && Method.Method == AuthMethod.Methods.USER_NAME_PASSWORD_METHOD);

                            if (bRecreateNeed)
                            {
                                MemoryService.DeleteKey(CommonData.MemoryQueryParameters, AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY + AuthMethodKey.AsString, _ErrorMessageAction);
                                //No in-memory recreation for security.

                                if (!DatabaseService.DeleteItem(
                                        AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                                        AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                                        AuthMethodKey,
                                        out JObject DeletedAuthMethodObject,
                                        EBReturnItemBehaviour.ReturnAllOld,
                                        _ErrorMessageAction))
                                {
                                    DatabaseService.GetItem(
                                        AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                                        AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                                        AuthMethodKey,
                                        AuthDBEntry.Properties,
                                        out DeletedAuthMethodObject,
                                        _ErrorMessageAction);

                                    Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                                        _Context,
                                        AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                                        AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                                        AuthMethodKey);
                                }

                                if (DeletedAuthMethodObject != null)
                                {
                                    DeletedAuthMethodObject.Merge(_UpdateFieldsAuthEntry, new JsonMergeSettings()
                                    {
                                        MergeArrayHandling = MergeArrayHandling.Replace
                                    });
                                    _UpdateFieldsAuthEntry = DeletedAuthMethodObject;
                                }

                                if (_NewEmailChange != null && Method.Method == AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD)
                                {
                                    AuthMethodKey = new BPrimitiveType(_NewEmailChange + PasswordMD5);
                                }
                                else if (_NewUserNameChange != null && Method.Method == AuthMethod.Methods.USER_NAME_PASSWORD_METHOD)
                                {
                                    AuthMethodKey = new BPrimitiveType(_NewUserNameChange + PasswordMD5);
                                }
                                Controller_DeliveryEnsurer.Get().DB_PutItem_FireAndForget(
                                    _Context,
                                    AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                                    AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                                    AuthMethodKey,
                                    _UpdateFieldsAuthEntry);
                            }
                            else
                            {
                                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                                    _Context,
                                    AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                                    AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                                    AuthMethodKey,
                                    _UpdateFieldsAuthEntry);
                            }
                        }
                    }
                }
            }

            return(BWebResponse.StatusOK("User has been updated."));
        }
예제 #26
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                string  RequestPayload = null;
                JObject ParsedBody;

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

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

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

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

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

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

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

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

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

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

                var CheckedUserModelIDs = new JArray();

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

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

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

                var CheckedUserSharedModelIDs = new JArray();

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

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

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

                return(BWebResponse.StatusOK("Check models have successfully been completed.", new JObject()
                {
                    ["checkedUserModelIds"] = CheckedUserModelIDs,
                    ["checkedUserSharedModelIds"] = CheckedUserSharedModelIDs
                }));
            }
예제 #27
0
        private static bool GetProcessedFileNode_Internal(
            ENodeType _FileType,
            IBDatabaseServiceInterface _DatabaseService,
            IBFileServiceInterface _FileService,
            string _CadFileStorageBucketName,
            string _ModelID,
            int _RevisionIndex,
            bool _bRootNodeRequested, uint _NodeStartIndex, uint _NodeSize,
            out BWebServiceResponse _SuccessResponse,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _SuccessResponse = BWebResponse.InternalError("");

            if (!TryGettingAllInfo(
                    _DatabaseService,
                    _ModelID,
                    _RevisionIndex,
                    out ModelDBEntry ModelObject,
                    out Revision RevisionObject,
                    out int _,
                    out _FailureResponse,
                    _ErrorMessageAction))
            {
                return(false);
            }

            if (RevisionObject.FileEntry.FileProcessStage != (int)Constants.EProcessStage.Uploaded_Processed)
            {
                _FailureResponse = BWebResponse.NotFound("Raw file has not been processed yet.");
                return(false);
            }

            if (_bRootNodeRequested)
            {
                Convert.UniqueIDToStartIndexAndSize(RevisionObject.FileEntry.ProcessedFilesRootNodeID, out _NodeStartIndex, out _NodeSize);
                if (_NodeStartIndex == 0 || _NodeSize == 0)
                {
                    _FailureResponse = BWebResponse.InternalError("Invalid Root Node ID.");
                    return(false);
                }
            }

            string RelativeFileUrl = null;

            switch (_FileType)
            {
            case ENodeType.Hierarchy:
                RelativeFileUrl = RevisionObject.FileEntry.HierarchyRAFRelativeUrl;
                break;

            case ENodeType.Geometry:
                RelativeFileUrl = RevisionObject.FileEntry.GeometryRAFRelativeUrl;
                break;

            case ENodeType.Metadata:
                RelativeFileUrl = RevisionObject.FileEntry.MetadataRAFRelativeUrl;
                break;
            }

            Node RetrievedNode;

            var Buffer = new byte[_NodeSize];

            try
            {
                using (var MemStream = new MemoryStream((int)_NodeStartIndex))
                {
                    var Destination = new BStringOrStream(MemStream, _NodeSize);

                    if (!_FileService.DownloadFile(_CadFileStorageBucketName, RelativeFileUrl, Destination, _ErrorMessageAction, _NodeStartIndex, _NodeSize))
                    {
                        _ErrorMessageAction?.Invoke("DownloadFile has failed in GetProcessedFileNode_Internal. ModelID: " + _ModelID + ", RevisionIndex: " + _RevisionIndex + ", NodeStartIndex: " + _NodeStartIndex + ", NodeSize: " + _NodeSize);
                        _FailureResponse = BWebResponse.NotFound("Given Node ID does not exist.");
                        return(false);
                    }

                    MemStream.Seek(0, SeekOrigin.Begin);
                    if (MemStream.Read(Buffer, 0, (int)_NodeSize) < (int)_NodeSize)
                    {
                        _FailureResponse = BWebResponse.InternalError("Stream read operation has failed.");
                        return(false);
                    }

                    Convert.BufferToNode(out RetrievedNode, _FileType, Buffer, 0);
                }
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("File random access/stream operations have failed. ModelID: " + _ModelID + ", RevisionIndex: " + _RevisionIndex + ", NodeStartIndex: " + _NodeStartIndex + ", NodeSize: " + _NodeSize + ", Message: " + e.Message + ", Trace: " + e.StackTrace);
                _FailureResponse = BWebResponse.NotFound("Given Node ID does not exist.");
                return(false);
            }

            if (RetrievedNode == null)
            {
                _FailureResponse = BWebResponse.InternalError("File node parse operation has failed.");
                return(false);
            }

            _SuccessResponse = BWebResponse.StatusOK("Node has been located.", new JObject()
            {
                ["node"] = JObject.Parse(JsonConvert.SerializeObject(RetrievedNode))
            });
            return(true);
        }
예제 #28
0
        //TODO: If SSO is enabled for user; when it loses access to the tenant, delete all rights but keep the models and user.
        private BWebServiceResponse DeleteAccessMethodForUser(HttpListenerContext _Context, out bool _bSetClearanceForApiKey, out string _ApiKey, Action <string> _ErrorMessageAction)
        {
            _bSetClearanceForApiKey = false;
            _ApiKey = null;

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

            if (!UserObject.ContainsKey(UserDBEntry.AUTH_METHODS_PROPERTY))
            {
                return(BWebResponse.NotFound("User does not have any auth method."));
            }

            bool bFound = false;

            var AuthMethodsArray = (JArray)UserObject[UserDBEntry.AUTH_METHODS_PROPERTY];

            for (var i = (AuthMethodsArray.Count - 1); i >= 0; i--)
            {
                var MethodObject = (JObject)AuthMethodsArray[i];
                var Method       = JsonConvert.DeserializeObject <AuthMethod>(MethodObject.ToString());

                string AuthMethodKey = null;
                switch (Method.Method)
                {
                case AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD:
                {
                    if (!bIsInternalCall && Method.UserEmail.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                    {
                        return(BWebResponse.BadRequest("This auth method cannot be deleted."));
                    }
                    AuthMethodKey = Method.UserEmail + Method.PasswordMD5;
                    break;
                }

                case AuthMethod.Methods.USER_NAME_PASSWORD_METHOD:
                {
                    AuthMethodKey = Method.UserName + Method.PasswordMD5;
                    break;
                }

                case AuthMethod.Methods.API_KEY_METHOD:
                {
                    AuthMethodKey = Method.ApiKey;

                    _bSetClearanceForApiKey = true;
                    _ApiKey = Method.ApiKey;

                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + Method.ApiKey, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Atomic operation control has failed."));
                    }
                    break;
                }
                }

                if (AuthMethodKey == RequestedAuthMethodKey)
                {
                    AuthMethodsArray.RemoveAt(i);
                    bFound = true;
                }
            }

            if (!bFound)
            {
                return(BWebResponse.NotFound("Auth method does not exist."));
            }

            //Update UserDBEntry
            Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                _Context,
                UserDBEntry.DBSERVICE_USERS_TABLE(),
                UserDBEntry.KEY_NAME_USER_ID,
                UserKey,
                UserObject);

            //Delete AuthDBEntry
            Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                _Context,
                AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                new BPrimitiveType(RequestedAuthMethodKey));

            if (_bSetClearanceForApiKey)
            {
                //Delete ApiKey from UniqueUserFields
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                    UniqueUserFieldsDBEntry.KEY_NAME_API_KEY,
                    new BPrimitiveType(_ApiKey));
            }

            //Delete from cache
            MemoryService.DeleteKey(
                CommonData.MemoryQueryParameters,
                AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY + RequestedAuthMethodKey,
                _ErrorMessageAction);

            return(BWebResponse.StatusOK("Access method has been deleted."));
        }
예제 #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);
            }

            string  RequestPayload = null;
            JObject ParsedBody;

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

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

            var FinalUserIds = new List <string>();

            bool bShareWithAll = false;

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

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

                    FinalUserIds.Add("*");
                }
            }

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

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

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

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

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

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

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

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

                    var EmailsJArray = new JArray();

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

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

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

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

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

                    string InterServicesRequestStringResponse = null;

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

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

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

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

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

            Model.ModelSharedWithUserIDs = FinalUserIds;

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

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

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

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

            return(BWebResponse.StatusOK("Operation has been completed."));
        }
예제 #30
0
        private BWebServiceResponse UpdateRevisionInfo(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryParsingRequestFor(
                    _Context,
                    out JObject UpdatedRevisionJson,
                    true, out Revision UpdatedRevision,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

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

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

            if (UpdatedRevision.RevisionName != null && UpdatedRevision.RevisionName.Length > 0 &&
                RevisionObject.RevisionName != UpdatedRevision.RevisionName)
            {
                //There is a change in the revision name
                foreach (var CurrentRev in Model.ModelRevisions)
                {
                    if (CurrentRev.RevisionName.ToUpper() == UpdatedRevision.RevisionName)
                    {
                        return(BWebResponse.Conflict("A revision with same " + Revision.REVISION_NAME_PROPERTY + " already exists."));
                    }
                }
            }

            RevisionObject.Merge(UpdatedRevisionJson);
            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_ModelRevisionUpdated
                                                               (
                                                                   RequestedModelID,
                                                                   RequestedRevisionIndex,
                                                                   Model.ModelOwnerUserID,
                                                                   Model.ModelSharedWithUserIDs,
                                                                   AuthorizedUser.UserID,
                                                                   UpdatedRevisionJson
                                                               ),
                                                               _ErrorMessageAction);

            return(BWebResponse.StatusOK("Revision has been updated."));
        }