From 043f78fbad456b12c48da6b779b1e5efc1d7fa78 Mon Sep 17 00:00:00 2001 From: Alexander van Delft Date: Thu, 28 Nov 2024 10:02:35 +0100 Subject: [PATCH] [FIX] according to review and add return statements where needed --- .../Modules/10-25/EngineeringModelApi.cs | 360 +++++++++--------- .../Modules/10-25/ExchangeFileExportApi.cs | 31 +- .../Modules/10-25/ExchangeFileImportyApi.cs | 4 + CometServer/Modules/10-25/SiteDirectoryApi.cs | 165 ++++---- CometServer/Modules/Tasks/CometTasksModule.cs | 6 +- CometServer/appsettings.Development.json | 2 +- 6 files changed, 285 insertions(+), 283 deletions(-) diff --git a/CometServer/Modules/10-25/EngineeringModelApi.cs b/CometServer/Modules/10-25/EngineeringModelApi.cs index b0fd3d3e..a0b4a88c 100644 --- a/CometServer/Modules/10-25/EngineeringModelApi.cs +++ b/CometServer/Modules/10-25/EngineeringModelApi.cs @@ -160,28 +160,27 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else - { - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The GET REQUEST was not authorized for {identity}", req.HttpContext.User.Identity.Name); - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The GET REQUEST was not authorized for {identity}", req.HttpContext.User.Identity.Name); - await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, fileBinaryService, fileArchiveService, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, obfuscationService, cherryPickService, containmentService); + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; } + + await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, fileBinaryService, fileArchiveService, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, obfuscationService, cherryPickService, containmentService); }); app.MapPost("EngineeringModel/{engineeringModelIid:guid}/iteration/{iterationIid:guid}", @@ -192,77 +191,78 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else - { - var requestToken = this.TokenGeneratorService.GenerateRandomToken(); - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The {requestToken} POST REQUEST was not authorized for {Identity}", requestToken, req.HttpContext.User.Identity.Name); + var requestToken = this.TokenGeneratorService.GenerateRandomToken(); - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The {requestToken} POST REQUEST was not authorized for {Identity}", requestToken, req.HttpContext.User.Identity.Name); - var cometTask = this.CreateAndRegisterCometTask(credentialsService.Credentials.Person.Iid, TopContainer, requestToken); - - PostRequestData postRequestData = null; + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; + } - try - { - postRequestData = await this.ProcessPostRequest(req, requestUtils, metaInfoProvider, jsonSerializer, fileBinaryService); - } - catch (BadRequestException ex) - { - this.logger.LogWarning("Request {requestToken} failed as BadRequest \n {ErrorMessage}", requestToken, ex.Message); + var cometTask = this.CreateAndRegisterCometTask(credentialsService.Credentials.Person.Iid, TopContainer, requestToken); + + PostRequestData postRequestData = null; - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - {ex.Message}"); + try + { + postRequestData = await this.ProcessPostRequest(req, requestUtils, metaInfoProvider, jsonSerializer, fileBinaryService); + } + catch (BadRequestException ex) + { + this.logger.LogWarning("Request {requestToken} failed as BadRequest \n {ErrorMessage}", requestToken, ex.Message); - res.StatusCode = (int)HttpStatusCode.BadRequest; - await res.AsJson($"exception:{ex.Message}"); - } - catch (Exception ex) - { - this.logger.LogError("Request {requestToken} failed as InternalServerError \n {ErrorMessage}", requestToken, ex.Message); + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - {ex.Message}"); - cometTask.FinishedAt = DateTime.Now; - cometTask.StatusKind = StatusKind.FAILED; - cometTask.Error = $"INTERNAL SERVER ERROR - {ex.Message}"; - this.CometTaskService.AddOrUpdateTask(cometTask); + res.StatusCode = (int)HttpStatusCode.BadRequest; + await res.AsJson($"exception:{ex.Message}"); + return; + } + catch (Exception ex) + { + this.logger.LogError("Request {requestToken} failed as InternalServerError \n {ErrorMessage}", requestToken, ex.Message); - res.StatusCode = (int)HttpStatusCode.InternalServerError; - await res.AsJson($"exception:{ex.Message}"); - return; - } + cometTask.FinishedAt = DateTime.Now; + cometTask.StatusKind = StatusKind.FAILED; + cometTask.Error = $"INTERNAL SERVER ERROR - {ex.Message}"; + this.CometTaskService.AddOrUpdateTask(cometTask); - if (postRequestData.IsMultiPart && requestUtils.QueryParameters.WaitTime > 0) - { - this.logger.LogWarning("Request {requestToken} failed as BadRequest: a POST request may not have a wait time when it is multipart", requestToken); + res.StatusCode = (int)HttpStatusCode.InternalServerError; + await res.AsJson($"exception:{ex.Message}"); + return; + } - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - a POST request may not have a wait time when it is multipart"); + if (postRequestData.IsMultiPart && requestUtils.QueryParameters.WaitTime > 0) + { + this.logger.LogWarning("Request {requestToken} failed as BadRequest: a POST request may not have a wait time when it is multipart", requestToken); - res.StatusCode = (int)HttpStatusCode.BadRequest; - await res.AsJson("a POST request may not have a wait time when it is multipart"); - } + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - a POST request may not have a wait time when it is multipart"); - if (requestUtils.QueryParameters.WaitTime > 0) - { - await this.EnqueCometTaskForPostRequest(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, changeLogService); - } - else - { - await this.PostResponseData(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, changeLogService); - } + res.StatusCode = (int)HttpStatusCode.BadRequest; + await res.AsJson("a POST request may not have a wait time when it is multipart"); + return; + } + + if (requestUtils.QueryParameters.WaitTime > 0) + { + await this.EnqueueCometTaskForPostRequest(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, changeLogService); + } + else + { + await this.PostResponseData(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, changeLogService); } }); } @@ -301,155 +301,154 @@ private async Task GetEngineeringModelsShallow(HttpRequest request, HttpResponse { response.UpdateWithNotAuthenticatedSettings(); await response.AsJson("not authenticated"); + return; } - else + + try { - try - { - await this.Authorize(this.AppConfigService, credentialsService, request.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The GET REQUEST was not authorized for {identity}", request.HttpContext.User.Identity.Name); - response.UpdateWithNotAutherizedSettings(); - await response.AsJson("not authorized"); - return; - } - - NpgsqlConnection connection = null; - var credentials = credentialsService.Credentials; - var transaction = transactionManager.SetupTransaction(ref connection, credentials); + await this.Authorize(this.AppConfigService, credentialsService, request.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The GET REQUEST was not authorized for {identity}", request.HttpContext.User.Identity.Name); + response.UpdateWithNotAutherizedSettings(); + await response.AsJson("not authorized"); + return; + } + + NpgsqlConnection connection = null; + var credentials = credentialsService.Credentials; + var transaction = transactionManager.SetupTransaction(ref connection, credentials); - transactionManager.SetCachedDtoReadEnabled(true); - transactionManager.SetFullAccessState(true); + transactionManager.SetCachedDtoReadEnabled(true); + transactionManager.SetFullAccessState(true); - var stopwatch = Stopwatch.StartNew(); - var requestToken = this.TokenGeneratorService.GenerateRandomToken(); + var stopwatch = Stopwatch.StartNew(); + var requestToken = this.TokenGeneratorService.GenerateRandomToken(); - this.logger.LogInformation("{request}:{requestToken} - START HTTP REQUEST PROCESSING", request.QueryNameMethodPath(), requestToken); - - try - { - var engineeringModels = new List(); - var allEngineeringModelIds = new List(); + this.logger.LogInformation("{request}:{requestToken} - START HTTP REQUEST PROCESSING", request.QueryNameMethodPath(), requestToken); + + try + { + var engineeringModels = new List(); + var allEngineeringModelIds = new List(); - var processor = new ResourceProcessor(transaction, serviceProvider, requestUtils, metaInfoProvider); - requestUtils.OverrideQueryParameters = new QueryParameters() { ExtentDeep = false }; + var processor = new ResourceProcessor(transaction, serviceProvider, requestUtils, metaInfoProvider); + requestUtils.OverrideQueryParameters = new QueryParameters() { ExtentDeep = false }; - var securityContext = new RequestSecurityContext(); + var securityContext = new RequestSecurityContext(); - // get all the Participants and filter out only those Participants that are active and for the current Person - var activeAndAssignedParticipantsForCurrentPerson = processor.GetResource("Participant", SiteDirectoryData, null, securityContext) - .OfType().Where(x => x.IsActive && x.Person == credentials.Person.Iid); + // get all the Participants and filter out only those Participants that are active and for the current Person + var activeAndAssignedParticipantsForCurrentPerson = processor.GetResource("Participant", SiteDirectoryData, null, securityContext) + .OfType().Where(x => x.IsActive && x.Person == credentials.Person.Iid); - // get all EngineeringModelSetup - var engineeringModelSetups = processor.GetResource("EngineeringModelSetup", SiteDirectoryData, null, securityContext) - .OfType(); + // get all EngineeringModelSetup + var engineeringModelSetups = processor.GetResource("EngineeringModelSetup", SiteDirectoryData, null, securityContext) + .OfType(); - if (ids is null) + if (ids is null) + { + foreach (var participant in activeAndAssignedParticipantsForCurrentPerson) { - foreach (var participant in activeAndAssignedParticipantsForCurrentPerson) + foreach (var engineeringModelSetup in engineeringModelSetups) { - foreach (var engineeringModelSetup in engineeringModelSetups) + if (engineeringModelSetup.Participant.Contains(participant.Iid)) { - if (engineeringModelSetup.Participant.Contains(participant.Iid)) - { - allEngineeringModelIds.Add(engineeringModelSetup.EngineeringModelIid); - } + allEngineeringModelIds.Add(engineeringModelSetup.EngineeringModelIid); } } } - else if (ids.TryParseEnumerableOfGuid(out var identifiers)) + } + else if (ids.TryParseEnumerableOfGuid(out var identifiers)) + { + foreach (var participant in activeAndAssignedParticipantsForCurrentPerson) { - foreach (var participant in activeAndAssignedParticipantsForCurrentPerson) + foreach (var engineeringModelSetup in engineeringModelSetups) { - foreach (var engineeringModelSetup in engineeringModelSetups) + if (engineeringModelSetup.Participant.Contains(participant.Iid) && identifiers.Contains(engineeringModelSetup.EngineeringModelIid)) { - if (engineeringModelSetup.Participant.Contains(participant.Iid) && identifiers.Contains(engineeringModelSetup.EngineeringModelIid)) - { - allEngineeringModelIds.Add(engineeringModelSetup.EngineeringModelIid); - } + allEngineeringModelIds.Add(engineeringModelSetup.EngineeringModelIid); } } } + } - foreach (var engineeringModelIid in allEngineeringModelIds.Distinct()) - { - var partition = requestUtils.GetEngineeringModelPartitionString(engineeringModelIid); + foreach (var engineeringModelIid in allEngineeringModelIds.Distinct()) + { + var partition = requestUtils.GetEngineeringModelPartitionString(engineeringModelIid); - var things = this.ProcessRequestPath(requestUtils, transactionManager, processor, TopContainer, partition, - new[] { nameof(EngineeringModel), engineeringModelIid.ToString() }, out _); + var things = this.ProcessRequestPath(requestUtils, transactionManager, processor, TopContainer, partition, + new[] { nameof(EngineeringModel), engineeringModelIid.ToString() }, out _); - engineeringModels.AddRange(things); - } + engineeringModels.AddRange(things); + } - var contentTypeKind = request.QueryContentTypeKind(); - var version = request.QueryDataModelVersion(); + var contentTypeKind = request.QueryContentTypeKind(); + var version = request.QueryDataModelVersion(); - if (contentTypeKind == ContentTypeKind.JSON) - { - await this.WriteJsonResponse(headerInfoProvider, metaInfoProvider, jsonSerializer, permissionInstanceFilterService, engineeringModels, version, response, HttpStatusCode.OK, requestToken); - } - else if (contentTypeKind == ContentTypeKind.MESSAGEPACK) - { - await this.WriteMessagePackResponse(headerInfoProvider, messagePackSerializer, permissionInstanceFilterService, engineeringModels, version, response, HttpStatusCode.OK, requestToken); - } - else - { - throw new NotSupportedException($"ContentType {contentTypeKind} is not supported for this request"); - } + if (contentTypeKind == ContentTypeKind.JSON) + { + await this.WriteJsonResponse(headerInfoProvider, metaInfoProvider, jsonSerializer, permissionInstanceFilterService, engineeringModels, version, response, HttpStatusCode.OK, requestToken); } - catch (SecurityException exception) + else if (contentTypeKind == ContentTypeKind.MESSAGEPACK) { - if (transaction != null) - { - await transaction.RollbackAsync(); - } - - this.logger.LogWarning("{request}:{requestToken} - Unauthorized request returned after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); - - response.StatusCode = (int)HttpStatusCode.Unauthorized; - await response.AsJson($"exception:{exception.Message}"); + await this.WriteMessagePackResponse(headerInfoProvider, messagePackSerializer, permissionInstanceFilterService, engineeringModels, version, response, HttpStatusCode.OK, requestToken); } - catch (ThingNotFoundException exception) + else { - if (transaction != null) - { - await transaction.RollbackAsync(); - } - - this.logger.LogWarning("{request}:{requestToken} - Unauthorized (Thing Not Found) request returned after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); - - response.StatusCode = (int)HttpStatusCode.NotFound; - await response.AsJson($"exception:{exception.Message}"); + throw new NotSupportedException($"ContentType {contentTypeKind} is not supported for this request"); } - catch (Exception exception) + } + catch (SecurityException exception) + { + if (transaction != null) { - if (transaction != null) - { - await transaction.RollbackAsync(); - } + await transaction.RollbackAsync(); + } - this.logger.LogError(exception, "{request}:{requestToken} - Failed after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); + this.logger.LogWarning("{request}:{requestToken} - Unauthorized request returned after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); - // error handling - response.StatusCode = (int)HttpStatusCode.InternalServerError; - await response.AsJson($"exception:{exception.Message}"); + response.StatusCode = (int)HttpStatusCode.Unauthorized; + await response.AsJson($"exception:{exception.Message}"); + } + catch (ThingNotFoundException exception) + { + if (transaction != null) + { + await transaction.RollbackAsync(); } - finally + + this.logger.LogWarning("{request}:{requestToken} - Unauthorized (Thing Not Found) request returned after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); + + response.StatusCode = (int)HttpStatusCode.NotFound; + await response.AsJson($"exception:{exception.Message}"); + } + catch (Exception exception) + { + if (transaction != null) { - if (transaction != null) - { - await transaction.DisposeAsync(); - } + await transaction.RollbackAsync(); + } - if (connection != null) - { - await connection.DisposeAsync(); - } + this.logger.LogError(exception, "{request}:{requestToken} - Failed after {ElapsedMilliseconds} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); - this.logger.LogInformation("{request}:{requestToken} - Response returned in {sw} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); + // error handling + response.StatusCode = (int)HttpStatusCode.InternalServerError; + await response.AsJson($"exception:{exception.Message}"); + } + finally + { + if (transaction != null) + { + await transaction.DisposeAsync(); } + + if (connection != null) + { + await connection.DisposeAsync(); + } + + this.logger.LogInformation("{request}:{requestToken} - Response returned in {sw} [ms]", request.QueryNameMethodPath(), requestToken, stopwatch.ElapsedMilliseconds); } } @@ -825,6 +824,7 @@ protected async Task< PostRequestData> ProcessPostRequest(HttpRequest httpReques }; Stream bodyStream; + if (postRequestData.IsMultiPart) { var requestStream = new MemoryStream(); @@ -919,7 +919,7 @@ protected async Task< PostRequestData> ProcessPostRequest(HttpRequest httpReques /// /// an awaitable /// - protected async Task EnqueCometTaskForPostRequest(PostRequestData postRequestData, string requestToken, HttpResponse httpResponse, CometTask cometTask, IRequestUtils requestUtils, ICdp4TransactionManager transactionManager, ICredentialsService credentialsService, IHeaderInfoProvider headerInfoProvider, Services.IServiceProvider serviceProvider, IMetaInfoProvider metaInfoProvider, IOperationProcessor operationProcessor, IRevisionService revisionService, ICdp4JsonSerializer jsonSerializer, IMessagePackSerializer messagePackSerializer, IPermissionInstanceFilterService permissionInstanceFilterService, IChangeLogService changeLogService) + protected async Task EnqueueCometTaskForPostRequest(PostRequestData postRequestData, string requestToken, HttpResponse httpResponse, CometTask cometTask, IRequestUtils requestUtils, ICdp4TransactionManager transactionManager, ICredentialsService credentialsService, IHeaderInfoProvider headerInfoProvider, Services.IServiceProvider serviceProvider, IMetaInfoProvider metaInfoProvider, IOperationProcessor operationProcessor, IRevisionService revisionService, ICdp4JsonSerializer jsonSerializer, IMessagePackSerializer messagePackSerializer, IPermissionInstanceFilterService permissionInstanceFilterService, IChangeLogService changeLogService) { var longRunningCometTask = Task.Run(() => { diff --git a/CometServer/Modules/10-25/ExchangeFileExportApi.cs b/CometServer/Modules/10-25/ExchangeFileExportApi.cs index 23851cc3..5cc92220 100644 --- a/CometServer/Modules/10-25/ExchangeFileExportApi.cs +++ b/CometServer/Modules/10-25/ExchangeFileExportApi.cs @@ -117,28 +117,27 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else + + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) { - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The POST REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); - - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } - - await this.PostResponseData(req, res, requestUtils, transactionManager, credentialsService, metaInfoProvider, jsonSerializer, jsonExchangeFileWriter); + this.logger.LogWarning("The POST REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); + + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; } + + await this.PostResponseData(req, res, requestUtils, transactionManager, credentialsService, metaInfoProvider, jsonSerializer, jsonExchangeFileWriter); }); } diff --git a/CometServer/Modules/10-25/ExchangeFileImportyApi.cs b/CometServer/Modules/10-25/ExchangeFileImportyApi.cs index 490d081c..53e04783 100644 --- a/CometServer/Modules/10-25/ExchangeFileImportyApi.cs +++ b/CometServer/Modules/10-25/ExchangeFileImportyApi.cs @@ -281,6 +281,7 @@ internal async Task ImportDataStore(HttpRequest httpRequest, HttpResponse respon response.StatusCode = (int)HttpStatusCode.Forbidden; await response.AsJson("Data store IMPORT is not allowed"); + return; } this.logger.LogInformation("{request}:{requestToken} - Starting data store IMPORT", httpRequest.QueryNameMethodPath(), requestToken); @@ -456,6 +457,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager try { var sw = new Stopwatch(); + if (seed) { // clear database schemas if seeding @@ -544,6 +546,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager foreach (var person in items.OfType()) { var credential = migrationCredentials.FirstOrDefault(mc => mc.Iid == person.Iid); + if (credential != null) { personService.UpdateCredentials(transaction, "SiteDirectory", person, credential); @@ -558,6 +561,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager var engineeringModelSetups = items.OfType() .ToList(); + var engineeringModelService = serviceProvider.MapToPersitableService("EngineeringModel"); var iterationService = serviceProvider.MapToPersitableService("Iteration"); diff --git a/CometServer/Modules/10-25/SiteDirectoryApi.cs b/CometServer/Modules/10-25/SiteDirectoryApi.cs index 7babaec9..cbc9f5b8 100644 --- a/CometServer/Modules/10-25/SiteDirectoryApi.cs +++ b/CometServer/Modules/10-25/SiteDirectoryApi.cs @@ -151,28 +151,27 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else - { - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The GET REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The GET REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); - await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService); + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; } + + await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService); }); app.MapGet("SiteDirectory/{*path}", @@ -183,28 +182,27 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else - { - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The GET REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The GET REQUEST was not authorized for {Identity}", req.HttpContext.User.Identity.Name); - await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService); + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; } + + await this.GetResponseData(req, res, requestUtils, transactionManager, credentialsService, headerInfoProvider, serviceProvider, metaInfoProvider, revisionService, revisionResolver, jsonSerializer, messagePackSerializer, permissionInstanceFilterService); }); app.MapPost("SiteDirectory/{iid:guid}", @@ -215,74 +213,75 @@ public override void AddRoutes(IEndpointRouteBuilder app) return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); + return; } - else - { - var requestToken = this.TokenGeneratorService.GenerateRandomToken(); - try - { - await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); - } - catch (AuthorizationException) - { - this.logger.LogWarning("The {requestToken} POST REQUEST was not authorized for {Identity}", requestToken, req.HttpContext.User.Identity.Name); + var requestToken = this.TokenGeneratorService.GenerateRandomToken(); - res.UpdateWithNotAutherizedSettings(); - await res.AsJson("not authorized"); - return; - } + try + { + await this.Authorize(this.AppConfigService, credentialsService, req.HttpContext.User.Identity.Name); + } + catch (AuthorizationException) + { + this.logger.LogWarning("The {requestToken} POST REQUEST was not authorized for {Identity}", requestToken, req.HttpContext.User.Identity.Name); - var cometTask = this.CreateAndRegisterCometTask(credentialsService.Credentials.Person.Iid, TopContainer, requestToken); - - PostRequestData postRequestData = null; + res.UpdateWithNotAutherizedSettings(); + await res.AsJson("not authorized"); + return; + } - try - { - postRequestData = this.ProcessPostRequest(req, requestUtils, metaInfoProvider, jsonSerializer); - } - catch (BadRequestException ex) - { - this.logger.LogWarning("Request {requestToken} failed as BadRequest \n {ErrorMessage}", requestToken, ex.Message); + var cometTask = this.CreateAndRegisterCometTask(credentialsService.Credentials.Person.Iid, TopContainer, requestToken); + + PostRequestData postRequestData = null; - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - {ex.Message}"); + try + { + postRequestData = this.ProcessPostRequest(req, requestUtils, metaInfoProvider, jsonSerializer); + } + catch (BadRequestException ex) + { + this.logger.LogWarning("Request {requestToken} failed as BadRequest \n {ErrorMessage}", requestToken, ex.Message); - res.StatusCode = (int)HttpStatusCode.BadRequest; - await res.AsJson($"exception:{ex.Message}"); - } - catch (Exception ex) - { - this.logger.LogError("Request {requestToken} failed as InternalServerError \n {ErrorMessage}", requestToken, ex.Message); + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - {ex.Message}"); - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"INTERNAL SERVER ERROR - {ex.Message}"); + res.StatusCode = (int)HttpStatusCode.BadRequest; + await res.AsJson($"exception:{ex.Message}"); + return; + } + catch (Exception ex) + { + this.logger.LogError("Request {requestToken} failed as InternalServerError \n {ErrorMessage}", requestToken, ex.Message); - res.StatusCode = (int)HttpStatusCode.InternalServerError; - await res.AsJson($"exception:{ex.Message}"); - return; - } + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"INTERNAL SERVER ERROR - {ex.Message}"); - if (postRequestData.IsMultiPart ) - { - this.logger.LogWarning("Request {requestToken} failed as BadRequest: The SiteDirectory does not support MultiPart POST request", requestToken); + res.StatusCode = (int)HttpStatusCode.InternalServerError; + await res.AsJson($"exception:{ex.Message}"); + return; + } - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - The SiteDirectory does not support MultiPart POST request"); + if (postRequestData.IsMultiPart ) + { + this.logger.LogWarning("Request {requestToken} failed as BadRequest: The SiteDirectory does not support MultiPart POST request", requestToken); - res.StatusCode = (int)HttpStatusCode.BadRequest; - await res.AsJson("The SiteDirectory does not support MultiPart POST request"); - } + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - The SiteDirectory does not support MultiPart POST request"); - if (requestUtils.QueryParameters.WaitTime > 0) - { - await this.EnqueCometTaskForPostRequest(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, modelCreatorManager); - } - else - { - await this.PostResponseData(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, modelCreatorManager); - } + res.StatusCode = (int)HttpStatusCode.BadRequest; + await res.AsJson("The SiteDirectory does not support MultiPart POST request"); + return; + } + + if (requestUtils.QueryParameters.WaitTime > 0) + { + await this.EnqueueCometTaskForPostRequest(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, modelCreatorManager); + } + else + { + await this.PostResponseData(postRequestData, requestToken, res, cometTask, requestUtils, transactionManager, credentialsService, headerInfoProvider, metaInfoProvider, operationProcessor, revisionService, jsonSerializer, messagePackSerializer, permissionInstanceFilterService, modelCreatorManager); } }); } @@ -558,7 +557,7 @@ protected PostRequestData ProcessPostRequest(HttpRequest httpRequest, IRequestUt /// /// an awaitable /// - protected async Task EnqueCometTaskForPostRequest(PostRequestData postRequestData, string requestToken, HttpResponse httpResponse, CometTask cometTask, IRequestUtils requestUtils, ICdp4TransactionManager transactionManager, ICredentialsService credentialsService, IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, IOperationProcessor operationProcessor, IRevisionService revisionService, ICdp4JsonSerializer jsonSerializer, IMessagePackSerializer messagePackSerializer, IPermissionInstanceFilterService permissionInstanceFilterService, IModelCreatorManager modelCreatorManager) + protected async Task EnqueueCometTaskForPostRequest(PostRequestData postRequestData, string requestToken, HttpResponse httpResponse, CometTask cometTask, IRequestUtils requestUtils, ICdp4TransactionManager transactionManager, ICredentialsService credentialsService, IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, IOperationProcessor operationProcessor, IRevisionService revisionService, ICdp4JsonSerializer jsonSerializer, IMessagePackSerializer messagePackSerializer, IPermissionInstanceFilterService permissionInstanceFilterService, IModelCreatorManager modelCreatorManager) { var longRunningCometTask = Task.Run(() => { diff --git a/CometServer/Modules/Tasks/CometTasksModule.cs b/CometServer/Modules/Tasks/CometTasksModule.cs index 7c0ac8bc..40ed0e1b 100644 --- a/CometServer/Modules/Tasks/CometTasksModule.cs +++ b/CometServer/Modules/Tasks/CometTasksModule.cs @@ -138,7 +138,7 @@ public async Task QueryTasks(HttpRequest req, HttpResponse res, ICredentialsServ return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); @@ -185,7 +185,7 @@ public async Task QueryTask(HttpRequest req, HttpResponse res, ICredentialsServi return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); @@ -241,7 +241,7 @@ public async Task CancelTask(HttpRequest req, HttpResponse res, ICredentialsServ return; } - if (!req.HttpContext.User.Identity.IsAuthenticated) + if (!(req.HttpContext.User.Identity?.IsAuthenticated ?? false)) { res.UpdateWithNotAuthenticatedSettings(); await res.AsJson("not authenticated"); diff --git a/CometServer/appsettings.Development.json b/CometServer/appsettings.Development.json index f00969de..6097d667 100644 --- a/CometServer/appsettings.Development.json +++ b/CometServer/appsettings.Development.json @@ -55,7 +55,7 @@ "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Grafana.Loki" ], "MinimumLevel": { - "Default": "Information", + "Default": "Debug", "Override": { "Microsoft": "Warning", "System": "Warning"