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)))); }
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 })); }
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 })); }
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.")); }
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.")); }
public static bool TryGettingAllInfo( IBDatabaseServiceInterface _DatabaseService, string _ModelID, int _RevisionIndex, out ModelDBEntry _ModelObject, out Revision _RevisionObject, out int _RevisionListIx, out BWebServiceResponse _FailureResponse, Action <string> _ErrorMessageAction = null) { _RevisionObject = null; _RevisionListIx = -1; _FailureResponse = BWebResponse.InternalError(""); if (!TryGettingModelInfo( _DatabaseService, _ModelID, out JObject _, true, out _ModelObject, out BWebServiceResponse FailureResponse, _ErrorMessageAction)) { _FailureResponse = FailureResponse; return(false); } if (!DoesRevisionExist( _ModelObject, _RevisionIndex, out _RevisionObject, out _RevisionListIx)) { _FailureResponse = BWebResponse.NotFound("Revision does not exist."); return(false); } return(true); }
public static bool TryGettingModelInfo( IBDatabaseServiceInterface _DatabaseService, string _ModelID, out JObject _SuccessResultJson, bool _bDeserialize, out ModelDBEntry _SuccessResultDeserialized, out BWebServiceResponse _FailureResponse, Action <string> _ErrorMessageAction = null) { _FailureResponse = BWebResponse.InternalError(""); _SuccessResultDeserialized = null; var ModelKey = new BPrimitiveType(_ModelID); if (!_DatabaseService.GetItem( ModelDBEntry.DBSERVICE_MODELS_TABLE(), ModelDBEntry.KEY_NAME_MODEL_ID, ModelKey, ModelDBEntry.Properties, out _SuccessResultJson, _ErrorMessageAction)) { _FailureResponse = BWebResponse.InternalError("Database fetch-model-info operation has failed."); return(false); } if (_SuccessResultJson == null) { _FailureResponse = BWebResponse.NotFound("Model does not exist."); return(false); } if (_bDeserialize) { _SuccessResultDeserialized = JsonConvert.DeserializeObject <ModelDBEntry>(_SuccessResultJson.ToString()); } return(true); }
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 })); }
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)); }
private BWebServiceResponse AddUpdateBaseRightsForUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { var NewBaseScopeListFromRequest = new List <AccessScope>(); using (var InputStream = _Context.Request.InputStream) { using (var ResponseReader = new StreamReader(InputStream)) { try { var NewScopes = JArray.Parse(ResponseReader.ReadToEnd()); foreach (JObject NewScope in NewScopes) { var ConvertedScope = JsonConvert.DeserializeObject <AccessScope>(NewScope.ToString()); for (int i = ConvertedScope.AccessRights.Count - 1; i >= 0; i--) { ConvertedScope.AccessRights[i] = ConvertedScope.AccessRights[i].ToUpper(); if (!AccessScopeLibrary.ACCESS_RIGHTS.Contains(ConvertedScope.AccessRights[i])) { ConvertedScope.AccessRights.RemoveAt(i); } } if (ConvertedScope.AccessRights.Count > 0) { ConvertedScope.AccessRights = ConvertedScope.AccessRights.Distinct().ToList(); NewBaseScopeListFromRequest.Add(ConvertedScope); } } } catch (Exception e) { _ErrorMessageAction?.Invoke("User_AddListBaseRights_ForUser->AddUpdateBaseRightsForUser: 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 (NewBaseScopeListFromRequest.Count == 0) { return(BWebResponse.BadRequest("Request does not contain any valid base scope. Access rights can be: " + AccessScopeLibrary.GetPossibleAccessRightsText())); } 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 NewBaseAccessScopeAsJArray = new JArray(); var NewBaseAccessScopeAsList = new List <AccessScope>(); bool bUpdateOccurredForUserEntry = false; if (UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY)) { var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY]; foreach (var NewScope in NewBaseScopeListFromRequest) { bool bNewScopeFoundInExisting = false; NewScope.AccessRights.Sort(); foreach (JObject ExistingScopeObject in BaseAccessScopeAsArray) { bool bChangeOccurredForScope = false; var ExistingScope = JsonConvert.DeserializeObject <AccessScope>(ExistingScopeObject.ToString()); ExistingScope.AccessRights.Sort(); if (!bNewScopeFoundInExisting && ExistingScope.WildcardPath == NewScope.WildcardPath) { bNewScopeFoundInExisting = true; if (NewScope.AccessRights.Count != ExistingScope.AccessRights.Count) { bUpdateOccurredForUserEntry = true; NewBaseAccessScopeAsList.Add(NewScope); NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope))); break; } else { bool bLocalChangeExists = false; for (int i = 0; i < NewScope.AccessRights.Count; i++) { if (NewScope.AccessRights[i] != ExistingScope.AccessRights[i]) { bLocalChangeExists = true; break; } } if (bLocalChangeExists) { bUpdateOccurredForUserEntry = true; bChangeOccurredForScope = true; NewBaseAccessScopeAsList.Add(NewScope); NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope))); } } } if (!bChangeOccurredForScope) { NewBaseAccessScopeAsList.Add(ExistingScope); NewBaseAccessScopeAsJArray.Add(ExistingScopeObject); } } if (!bNewScopeFoundInExisting) { NewBaseAccessScopeAsList.Add(NewScope); NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope))); bUpdateOccurredForUserEntry = true; } } } if (bUpdateOccurredForUserEntry) { UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = NewBaseAccessScopeAsJArray; MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[] { new Tuple <string, BPrimitiveType>( UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID, new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry() { BaseAccessScope = NewBaseAccessScopeAsList }))) }, _ErrorMessageAction); Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget( _Context, UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, UserKey, UserObject); } return(BWebResponse.StatusCreated("New base rights have been added.")); }
private BWebServiceResponse DeleteRawFile(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { if (!CommonMethods.TryGettingAllInfo( DatabaseService, RequestedModelID, RequestedRevisionIndex, out ModelDBEntry ModelObject, out Revision RevisionObject, out int ModelRevisionListIx, out BWebServiceResponse _FailureResponse, _ErrorMessageAction)) { return(_FailureResponse); } var PreviousProcessStage = RevisionObject.FileEntry.FileProcessStage; if (PreviousProcessStage == (int)Constants.EProcessStage.NotUploaded) { return(BWebResponse.NotFound("Raw files have not been uploaded.")); } //if (RevisionObject.FileEntry.FileProcessStage == (int)Constants.EProcessStage.Uploaded_Processing) //{ // var RequestObject = new JObject() // { // ["bucketName"] = CadFileStorageBucketName, // ["rawFileRelativeUrl"] = RevisionObject.FileEntry.RawFileRelativeUrl // }; // GetTracingService()?.On_FromServiceToService_Sent(_Context, _ErrorMessageAction); // var Result = BWebUtilities_GC_CloudRun.InterServicesRequest(new BWebUtilities_GC_CloudRun.InterServicesRequestRequest() // { // DestinationServiceUrl = CadProcessServiceEndpoint + "/3d/process/stop", // RequestMethod = "POST", // ContentType = "application/json", // Content = new BStringOrStream(RequestObject.ToString()), // bWithAuthToken = false, //Kubernetes Service // UseContextHeaders = _Context, // 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); // } //} Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelRevisionFileEntryDeleteAll ( RequestedModelID, RequestedRevisionIndex, ModelObject.ModelOwnerUserID, ModelObject.ModelSharedWithUserIDs, AuthorizedUser.UserID, JObject.Parse(JsonConvert.SerializeObject(RevisionObject.FileEntry)) ), _ErrorMessageAction); var FileType = RevisionObject.FileEntry.FileEntryFileType; RevisionObject.FileEntry = new FileEntry() { FileEntryFileType = FileType }; RevisionObject.FileEntry.SetRelativeUrls_GetCommonUrlPart_FileEntryFileTypePreSet(RequestedModelID, RequestedRevisionIndex); ModelObject.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(ModelObject))); Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelRevisionFileEntryDeleted ( RequestedModelID, RequestedRevisionIndex, ModelObject.ModelOwnerUserID, ModelObject.ModelSharedWithUserIDs, AuthorizedUser.UserID ), _ErrorMessageAction); return(BWebResponse.StatusOK("Raw " + (PreviousProcessStage == (int)Constants.EProcessStage.Uploaded_Processed ? "and processed models have " : "model has ") + "been deleted.")); }
//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.")); }
private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { if (_Context.Request.HttpMethod != "GET") { return(BWebResponse.BadRequest($"This service does not accept requests of type : {_Context.Request.HttpMethod}")); } string FileTypeStr = ""; string Filename = "file"; try { FileTypeStr = _Context.Request.QueryString.Get("fileType").ToLower().Trim().TrimStart('.'); } catch { return(BWebResponse.BadRequest($"Expected parameters have not been provided")); } EProcessedFileType FileTypeEnum = EProcessedFileType.NONE_OR_RAW; if (Constants.ProcessedFileType_Enum_Map.ContainsKey(FileTypeStr)) { FileTypeEnum = Constants.ProcessedFileType_Enum_Map[FileTypeStr]; } else { return(BWebResponse.BadRequest($"Invalid File Type was provided")); } try { Filename = _Context.Request.QueryString.Get("fileName"); } catch { //This is an optional field so do nothing } if (string.IsNullOrWhiteSpace(Filename)) { Filename = "file"; } string Url = _Context.Request.RawUrl; int CopyStart = Url.LastIndexOf('/') + 1; int CopyEnd = Url.IndexOf("?"); string Podname = Url.Substring(CopyStart, CopyEnd - CopyStart).TrimEnd('/'); if (CopyEnd == -1) { return(BWebResponse.BadRequest($"Expected parameters have not been provided")); } BatchProcessingCreationService.Instance.GetBucketAndFile(Podname, out string _Bucket, out string _Filename); if (!string.IsNullOrWhiteSpace(_Bucket) && !string.IsNullOrWhiteSpace(_Filename)) { string RawStrippedPath = _Filename.TrimStart("raw/"); int FilenameStripLength = RawStrippedPath.LastIndexOf('/'); RawStrippedPath = RawStrippedPath.Substring(0, FilenameStripLength); if (!FileService.CreateSignedURLForUpload(out string SignedUploadUrl, DEFAULT_UPLOAD_BUCKET, $"{Constants.ProcessedFileType_FolderPrefix_Map[FileTypeEnum]}{RawStrippedPath}/{Filename}.{Constants.ProcessedFileType_Extension_Map[FileTypeEnum]}", UPLOAD_CONTENT_TYPE, UPLOAD_URL_VALIDITY_MINUTES, _ErrorMessageAction)) { return(BWebResponse.InternalError("Failed to create Upload Url")); } return(BWebResponse.StatusOK("success", new JObject() { ["uploadUrl"] = SignedUploadUrl })); } else { return(BWebResponse.NotFound("Could not find pod details")); } }
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.")); }
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); }
public static bool FetchBaseAccessRights_ByUserID( IBDatabaseServiceInterface _DatabaseService, IBMemoryServiceInterface _MemoryService, string _UserID, out List <AccessScope> _AccessScopes, out BWebServiceResponse _FailureResponse, Action <string> _ErrorMessageAction = null) { _AccessScopes = null; _FailureResponse = new BWebServiceResponse(); var InMemoryResult = _MemoryService.GetKeyValue(CommonData.MemoryQueryParameters, UserBaseAccessMEntry.M_KEY_NAME_USER_ID + _UserID, _ErrorMessageAction); if (InMemoryResult != null) { try { _AccessScopes = JsonConvert.DeserializeObject <UserBaseAccessMEntry>(InMemoryResult.AsString).BaseAccessScope; return(true); } catch (Exception) { } } if (!_DatabaseService.GetItem( UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, new BPrimitiveType(_UserID), UserDBEntry.Properties, out JObject UserObject, _ErrorMessageAction)) { _FailureResponse = BWebResponse.InternalError("Database fetch-user-info operation has failed."); return(false); } if (UserObject == null) { _FailureResponse = BWebResponse.NotFound("User does not exist."); return(false); } _AccessScopes = new List <AccessScope>(); if (UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY)) { var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY]; foreach (JObject ScopeObject in BaseAccessScopeAsArray) { _AccessScopes.Add(JsonConvert.DeserializeObject <AccessScope>(ScopeObject.ToString())); } } _MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[] { new Tuple <string, BPrimitiveType>( UserBaseAccessMEntry.M_KEY_NAME_USER_ID + _UserID, new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry() { BaseAccessScope = _AccessScopes }))) }, _ErrorMessageAction); return(true); }
private BWebServiceResponse UpdateUserInfo(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { var UpdateFieldsUserEntry = new JObject(); var UpdateFieldsAuthEntry = new JObject(); string NewEmailChange = null; string NewUserNameChange = null; using (var InputStream = _Context.Request.InputStream) { using (var ResponseReader = new StreamReader(InputStream)) { try { var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd()); foreach (var Child in ParsedBody) { if (UserDBEntry.UpdatableProperties.Contains(Child.Key)) { if (!UserDBEntry.UpdatablePropertiesValidityCheck[Child.Key](Child.Value)) { return(BWebResponse.BadRequest("Given field " + Child.Key + " has invalid value.")); } UpdateFieldsUserEntry[Child.Key] = Child.Value; } if (AuthDBEntry.UpdatableProperties.Contains(Child.Key)) { UpdateFieldsAuthEntry[Child.Key] = Child.Value; } if (Child.Key == UserDBEntry.USER_EMAIL_PROPERTY) { NewEmailChange = ((string)Child.Value).ToLower(); if (NewEmailChange.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)) { return(BWebResponse.BadRequest("Email address cannot end with " + Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)); } } else if (Child.Key == UserDBEntry.USER_NAME_PROPERTY) { NewUserNameChange = (string)Child.Value; if (NewUserNameChange.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)) { return(BWebResponse.BadRequest("Username cannot end with " + Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)); } } } } catch (Exception e) { _ErrorMessageAction?.Invoke("User_GetUpdateDeleteUser->UpdateUserInfo: 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 (UpdateFieldsUserEntry.Count == 0) { return(BWebResponse.BadRequest("Request does not contain any matching field with the expected structure.")); } bool bNewEmailAtomicnessSet = false, bNewUsernameAtomicnessSet = false; try { if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction)) { return(BWebResponse.InternalError("Atomic operation control has failed.")); } if (!DatabaseService.GetItem( UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, new BPrimitiveType(RequestedUserID), 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 bEmailExistInUserObject = UserObject.ContainsKey(UserDBEntry.USER_EMAIL_PROPERTY); var bUsernameExistInUserObject = UserObject.ContainsKey(UserDBEntry.USER_NAME_PROPERTY); if (NewEmailChange != null && bEmailExistInUserObject && (string)UserObject[UserDBEntry.USER_EMAIL_PROPERTY] == NewEmailChange) { NewEmailChange = null; UpdateFieldsUserEntry.Remove(UserDBEntry.USER_EMAIL_PROPERTY); UpdateFieldsAuthEntry.Remove(AuthDBEntry.USER_EMAIL_PROPERTY); } else if (NewEmailChange != null) { if (bEmailExistInUserObject && ((string)UserObject[UserDBEntry.USER_EMAIL_PROPERTY]).EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)) { return(BWebResponse.BadRequest("E-mail address cannot be changed for this account type.")); } if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL + ":" + NewEmailChange, _ErrorMessageAction)) { return(BWebResponse.InternalError("Atomic operation control has failed.")); } bNewEmailAtomicnessSet = true; if (!DatabaseService.GetItem( UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL, new BPrimitiveType(NewEmailChange), UniqueUserFieldsDBEntry.Properties, out JObject ExistenceCheck, _ErrorMessageAction)) { return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed.")); } if (ExistenceCheck != null) { return(BWebResponse.Conflict("A user with same user e-mail already exists.")); } } if (NewUserNameChange != null && UserObject.ContainsKey(UserDBEntry.USER_NAME_PROPERTY) && (string)UserObject[UserDBEntry.USER_NAME_PROPERTY] == NewUserNameChange) { NewUserNameChange = null; UpdateFieldsUserEntry.Remove(UserDBEntry.USER_NAME_PROPERTY); UpdateFieldsAuthEntry.Remove(AuthDBEntry.USER_NAME_PROPERTY); } else if (NewUserNameChange != null) { if (bUsernameExistInUserObject && ((string)UserObject[UserDBEntry.USER_NAME_PROPERTY]).EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX)) { return(BWebResponse.BadRequest("Username cannot be changed for this account type.")); } if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME + ":" + NewUserNameChange, _ErrorMessageAction)) { return(BWebResponse.InternalError("Atomic operation control has failed.")); } bNewUsernameAtomicnessSet = true; if (!DatabaseService.GetItem( UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME, new BPrimitiveType(NewUserNameChange), UniqueUserFieldsDBEntry.Properties, out JObject ExistenceCheck, _ErrorMessageAction)) { return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed.")); } if (ExistenceCheck != null) { return(BWebResponse.Conflict("A user with same username already exists.")); } } return(UpdateUserInfo_Internal( _Context, NewEmailChange, NewUserNameChange, UserObject, UpdateFieldsUserEntry, UpdateFieldsAuthEntry, _ErrorMessageAction)); } finally { Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction); if (bNewEmailAtomicnessSet) { Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL + ":" + NewEmailChange, _ErrorMessageAction); } if (bNewUsernameAtomicnessSet) { Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME + ":" + NewUserNameChange, _ErrorMessageAction); } } }
private BWebServiceResponse DeleteBaseRightForUser(HttpListenerContext _Context, 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.")); } if (!UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY)) { return(BWebResponse.NotFound("User does not have any base rights.")); } var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY]; var NewBaseAccessScopeAsList = new List <AccessScope>(); //Check existence of access scope var ExistingAccessScopeIndex = -1; int j = 0; foreach (JObject BaseAccessScopeObject in BaseAccessScopeAsArray) { var Scope = JsonConvert.DeserializeObject <AccessScope>(BaseAccessScopeObject.ToString()); if (ExistingAccessScopeIndex == -1 && Scope.WildcardPath == RequestedBaseRightWildcard) { ExistingAccessScopeIndex = j; } else { NewBaseAccessScopeAsList.Add(Scope); } j++; } if (ExistingAccessScopeIndex == -1) { return(BWebResponse.NotFound("User does not have the given base right.")); } BaseAccessScopeAsArray.RemoveAt(ExistingAccessScopeIndex); UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = BaseAccessScopeAsArray; Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget( _Context, UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, UserKey, UserObject); MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[] { new Tuple <string, BPrimitiveType>( UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID, new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry() { BaseAccessScope = NewBaseAccessScopeAsList }))) }, _ErrorMessageAction); return(BWebResponse.StatusOK("Base right has been deleted.")); }
private BWebServiceResponse UpdateBaseRightForUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { var NewRights = new List <string>(); using (var InputStream = _Context.Request.InputStream) { using (var ResponseReader = new StreamReader(InputStream)) { try { var NewRightsArray = JArray.Parse(ResponseReader.ReadToEnd()); foreach (string NewRight in NewRightsArray) { var NewRightCaseCorrected = NewRight.ToUpper(); if (AccessScopeLibrary.ACCESS_RIGHTS.Contains(NewRightCaseCorrected)) { NewRights.Add(NewRightCaseCorrected); } } NewRights = NewRights.Distinct().ToList(); NewRights.Sort(); } catch (Exception e) { _ErrorMessageAction?.Invoke("User_UpdateDeleteBaseRight_ForUser->UpdateBaseRightForUser: 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 (NewRights.Count == 0) { return(BWebResponse.BadRequest("Request does not contain any valid access right. Use DELETE method for deleting the scope. Access rights can be: " + AccessScopeLibrary.GetPossibleAccessRightsText())); } 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.BASE_ACCESS_SCOPE_PROPERTY)) { return(BWebResponse.NotFound("User does not have any base rights.")); } var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY]; var BaseAccessScopeAsList = new List <AccessScope>(); //Check existence of access scope AccessScope ExistingAccessScope = null; int ExistingAccessScopeIndex = -1; int j = 0; foreach (JObject BaseAccessScopeObject in BaseAccessScopeAsArray) { var Scope = JsonConvert.DeserializeObject <AccessScope>(BaseAccessScopeObject.ToString()); BaseAccessScopeAsList.Add(Scope); if (ExistingAccessScopeIndex == -1 && Scope.WildcardPath == RequestedBaseRightWildcard) { ExistingAccessScope = Scope; ExistingAccessScopeIndex = j; } j++; } if (ExistingAccessScopeIndex == -1) { return(BWebResponse.NotFound("User does not have the given base right.")); } ExistingAccessScope.AccessRights.Sort(); //Check if requested rights are different bool bDifferent = false; if (ExistingAccessScope.AccessRights.Count == NewRights.Count) { for (var i = 0; i < ExistingAccessScope.AccessRights.Count; i++) { if (ExistingAccessScope.AccessRights[i] != NewRights[i]) { bDifferent = true; break; } } } else { bDifferent = true; } if (bDifferent) { ExistingAccessScope.AccessRights = NewRights; BaseAccessScopeAsArray[ExistingAccessScopeIndex] = JObject.Parse(JsonConvert.SerializeObject(ExistingAccessScope)); UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = BaseAccessScopeAsArray; Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget( _Context, UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, UserKey, UserObject); MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[] { new Tuple <string, BPrimitiveType>( UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID, new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry() { BaseAccessScope = BaseAccessScopeAsList }))) }, _ErrorMessageAction); } return(BWebResponse.StatusOK("Base right has been updated.")); }
protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null) { if (_Context.Request.HttpMethod != "POST") { _ErrorMessageAction?.Invoke("GetUserIDsFromEmailsRequest: POST method is accepted. But received request method: " + _Context.Request.HttpMethod); return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod)); } string RequestPayload = null; JObject ParsedBody; using (var InputStream = _Context.Request.InputStream) { using var ResponseReader = new StreamReader(InputStream); try { RequestPayload = ResponseReader.ReadToEnd(); ParsedBody = JObject.Parse(RequestPayload); } catch (Exception e) { _ErrorMessageAction?.Invoke("GetUserIDsFromEmailsRequest-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace); return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form.")); } } if (!ParsedBody.ContainsKey("emailAddresses") || ParsedBody["emailAddresses"].Type != JTokenType.Array) { return(BWebResponse.BadRequest("Invalid request body.")); } var AsJArray = (JArray)ParsedBody["emailAddresses"]; var EmailAddresses = new List <string>(); foreach (var Token in AsJArray) { if (Token.Type != JTokenType.String) { return(BWebResponse.BadRequest("Invalid request body.")); } var EmailAddress = ((string)Token).ToLower(); if (!EmailAddresses.Contains(EmailAddress)) { EmailAddresses.Add(EmailAddress); } } if (EmailAddresses.Count == 0) { return(BWebResponse.BadRequest("Empty emailAddresses field.")); } var ResponseObject = new JObject(); foreach (var Email in EmailAddresses) { if (!DatabaseService.GetItem( UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL, new BPrimitiveType(Email), UniqueUserFieldsDBEntry.Properties, out JObject ExistenceCheck, _ErrorMessageAction)) { return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed.")); } if (ExistenceCheck == null) { return(BWebResponse.NotFound("A user with e-mail " + Email + " does not exist.")); } ResponseObject[Email] = (string)ExistenceCheck[UserDBEntry.KEY_NAME_USER_ID]; } return(BWebResponse.StatusOK("OK.", new JObject() { ["map"] = ResponseObject })); }
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.")); }
private static bool GetProcessedFile_Internal( EProcessedFileType _FileType, IBDatabaseServiceInterface _DatabaseService, IBFileServiceInterface _FileService, string _CadFileStorageBucketName, string _ModelID, int _RevisionIndex, out BWebServiceResponse _SuccessResponse, out BWebServiceResponse _FailureResponse, string _GeometryId = null, Action <string> _ErrorMessageAction = null) { _SuccessResponse = BWebResponse.InternalError(""); if (!TryGettingAllInfo( _DatabaseService, _ModelID, _RevisionIndex, out ModelDBEntry _, 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); } string RelativeFileUrl = null; switch (_FileType) { case EProcessedFileType.HIERARCHY_CF: RelativeFileUrl = RevisionObject.FileEntry.HierarchyCFRelativeUrl; break; case EProcessedFileType.HIERARCHY_RAF: RelativeFileUrl = RevisionObject.FileEntry.HierarchyRAFRelativeUrl; break; case EProcessedFileType.METADATA_CF: RelativeFileUrl = RevisionObject.FileEntry.MetadataCFRelativeUrl; break; case EProcessedFileType.METADATA_RAF: RelativeFileUrl = RevisionObject.FileEntry.MetadataRAFRelativeUrl; break; case EProcessedFileType.GEOMETRY_CF: RelativeFileUrl = RevisionObject.FileEntry.GeometryCFRelativeUrl; break; case EProcessedFileType.GEOMETRY_RAF: RelativeFileUrl = RevisionObject.FileEntry.GeometryRAFRelativeUrl; break; case EProcessedFileType.UNREAL_HGM: RelativeFileUrl = RevisionObject.FileEntry.UnrealHGMRelativeUrl; break; case EProcessedFileType.UNREAL_HG: RelativeFileUrl = RevisionObject.FileEntry.UnrealHGRelativeUrl; break; case EProcessedFileType.UNREAL_H: RelativeFileUrl = RevisionObject.FileEntry.UnrealHRelativeUrl; break; case EProcessedFileType.UNREAL_G: if (_GeometryId == null) { _ErrorMessageAction?.Invoke("GeometryId was not set when tried to retrieve UnrealGeometry file (u_g)"); _FailureResponse = BWebResponse.InternalError("GeometryId was not provided."); } RelativeFileUrl = $"{RevisionObject.FileEntry.UnrealGRelativeUrlBasePath}{_GeometryId}.{Constants.ProcessedFileType_Extension_Map[EProcessedFileType.UNREAL_G]}"; break; } if (!_FileService.CreateSignedURLForDownload( out string DownloadUrl, _CadFileStorageBucketName, RelativeFileUrl, FileEntry.EXPIRY_MINUTES, _ErrorMessageAction)) { _FailureResponse = BWebResponse.InternalError("Signed url generation has failed."); return(false); } _SuccessResponse = BWebResponse.StatusOK("File has been located.", new JObject() { [FileEntry.FILE_DOWNLOAD_URL_PROPERTY] = DownloadUrl, [FileEntry.FILE_DOWNLOAD_UPLOAD_EXPIRY_MINUTES_PROPERTY] = FileEntry.EXPIRY_MINUTES }); return(true); }
private static bool GetProcessedFile_Internal( 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 (!TryGettingAllInfo( _DatabaseService, _ModelID, _RevisionIndex, out ModelDBEntry _, 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); } string RelativeFileUrl = null; switch (_FileType) { case ENodeType.Hierarchy: RelativeFileUrl = RevisionObject.FileEntry.HierarchyCFRelativeUrl; break; case ENodeType.Geometry: RelativeFileUrl = RevisionObject.FileEntry.GeometryCFRelativeUrl; break; case ENodeType.Metadata: RelativeFileUrl = RevisionObject.FileEntry.MetadataCFRelativeUrl; break; } if (!_FileService.CreateSignedURLForDownload( out string DownloadUrl, _CadFileStorageBucketName, RelativeFileUrl, FileEntry.EXPIRY_MINUTES, _ErrorMessageAction)) { _FailureResponse = BWebResponse.InternalError("Signed url generation has failed."); return(false); } _SuccessResponse = BWebResponse.StatusOK("File has been located.", new JObject() { [FileEntry.FILE_DOWNLOAD_URL_PROPERTY] = DownloadUrl, [FileEntry.FILE_DOWNLOAD_UPLOAD_EXPIRY_MINUTES_PROPERTY] = FileEntry.EXPIRY_MINUTES }); return(true); }
private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction) { _ErrorMessageAction?.Invoke("Trying to get Optimizer Env Vars"); if (_Context.Request.HttpMethod != "GET") { _ErrorMessageAction?.Invoke("Wrong type"); return(BWebResponse.BadRequest($"This service does not accept requests of type : {_Context.Request.HttpMethod}")); } string Url = _Context.Request.RawUrl; int CopyStart = Url.LastIndexOf('/') + 1; string Podname = Url.Substring(CopyStart).TrimEnd('/'); BatchProcessingCreationService.Instance.GetBucketAndFile(Podname, out string _Bucket, out string _Filename); if (!string.IsNullOrWhiteSpace(_Bucket) && !string.IsNullOrWhiteSpace(_Filename)) { string NewConversionID_FromRelativeUrl_UrlEncoded = WebUtility.UrlEncode(_Filename); bool CanProceed = false; bool ProcessError = false; if (DatabaseService.GetItem( FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(), FileConversionDBEntry.KEY_NAME_CONVERSION_ID, new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded), FileConversionDBEntry.Properties, out JObject ConversionObject )) { if (ConversionObject != null && ConversionObject.ContainsKey("conversionStatus")) { EInternalProcessStage ExistingStatus = (EInternalProcessStage)(int)ConversionObject["conversionStatus"]; if (ExistingStatus == EInternalProcessStage.ProcessComplete) { CanProceed = true; } else if (ExistingStatus == EInternalProcessStage.ProcessFailed) { ProcessError = true; } } } else { ProcessError = true; } if (CanProceed) { Dictionary <string, string> EnvVars = BatchProcessingCreationService.Instance.GetOptimizerEnvVars(_Bucket, _Filename, Podname, _ErrorMessageAction); if (EnvVars == null) { _ErrorMessageAction?.Invoke("EnvVars null"); return(BWebResponse.InternalError("An error occured trying to generate optimizer parameters")); } return(BWebResponse.StatusOK("success", new JObject() { ["uploadRequestUrl"] = EnvVars["CAD_PROCESS_UPLOAD_REQUEST_URL"], ["downloadHierarchyCfUrl"] = EnvVars["DOWNLOAD_HIERARCHY_CF"], ["downloadGeometryCfUrl"] = EnvVars["DOWNLOAD_GEOMETRY_CF"], ["downloadMetadataCfUrl"] = EnvVars["DOWNLOAD_METADATA_CF"] })); } else if (ProcessError) { _ErrorMessageAction?.Invoke("Cad process Failed"); return(BWebResponse.InternalError("Pixyz process has failed")); } else { _ErrorMessageAction?.Invoke("Not found"); return(BWebResponse.NotFound("Cad process has not completed yet")); } } else { _ErrorMessageAction?.Invoke("General failure"); return(BWebResponse.InternalError("An error occured trying to retreive pod details")); } }