public async Task <Project> Update(Project project, IAsyncDocumentSession session) { _logger.LogInformation("Project update request {@id}", project.Id); if (TestProjectId.IsValidIdentity(project.Id)) { return(await UpdateTest((TestProject)project, session)); } var p = await session.LoadAsync <Project>(project.Id); // _logger.LogDebug("Project before {@p}", p); if (ProjectId.IsValidIdentity(project.Id)) { await UpdateTestProjectName(project.Id, project.Name, session); p.Name = project.Name; } p.LogoUrl = project.LogoUrl; p.Webpage = project.Webpage; p.Description = project.Description; p.Applications = project.Applications; p.Platforms = project.Platforms; p.OwnerAdminId = project.OwnerAdminId; p.AdminIds = project.AdminIds; //await session.SaveChangesAsync(); // _logger.LogDebug("Project after {@p}", p); _logger.LogInformation("Project updated {@id}", p.Id); return(p); }
private async Task <IActionResult> AuthTest(string projectId, string resultOutcome) { try { using var session = _documentStore.OpenAsyncSession(); var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); var testMode = TestProjectId.IsValidIdentity(projectId) && !ProjectId.IsValidIdentity(projectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)projectId, session) : await _projectManager.Get((ProjectId)projectId, session); var result = await _applicationTestHttpClient.SendAuthCallback(project.Applications.First(), Guid.NewGuid().ToString(), resultOutcome, Guid.NewGuid().ToString()); return(Ok(result)); } catch (ApiException ex) { _logger.LogError(ex, "Unable to test application. {@request}", projectId); // return error message if there was an exception return(Ok(GenericResponse.Failed(ex.Message, (System.Net.HttpStatusCode)ex.StatusCode))); } catch (Exception ex) { _logger.LogError(ex, "Unable to test application. {@request}", projectId); // return error message if there was an exception return(Ok(GenericResponse.Failed(ex.Message, System.Net.HttpStatusCode.BadRequest))); } }
public async Task <IActionResult> Create([FromBody] ApplicationCreationRequest request) { try { // Who's logged in? using var session = _documentStore.OpenAsyncSession(); var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); // Which project are we working on? var testMode = TestProjectId.IsValidIdentity(request.ProjectId) && !ProjectId.IsValidIdentity(request.ProjectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)request.ProjectId, session) : await _projectManager.Get((ProjectId)request.ProjectId, session); // Does the user have access to the project? if (!project.AdminIds.Contains(user.Id) && project.OwnerAdminId != user.Id) { throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.Unauthorized); } var registeredApplication = await _applicationHttpClient.CreateApplication(new CreateApplicationModel { Name = project.Name, AuthCallbackUrl = request.AuthCallbackUrl ?? "", //EmailVerificationNotificationEndpointUrl = request.EmailVerificationUrl ?? "", DataUpdateCallbackUrl = request.DataUpdateCallbackUrl ?? "" }); if (string.IsNullOrEmpty(registeredApplication.ApplicationId)) { _logger.LogError("Create application failed. {@request} {@registeredApplication}", request, registeredApplication); throw new ApiException("Creating the application failed."); } var application = request.CreateApplication(registeredApplication); // One application per project, so just replace project.Applications = new List <Core.Entities.Application> { application }; // Save project = await _projectManager.Update(project, session); await session.SaveChangesAsync(); return(Ok(project)); } catch (ApiException ex) { _logger.LogError(ex, "Unable to create application. {@request}", request); // return error message if there was an exception // return BadRequest(new { message = ex.Message }); throw; } }
public async Task <IActionResult> Dummy([FromRoute] string projectType, [FromRoute] string id) { var projectId = $"{projectType}/{id}"; _logger.LogInformation("Dummy data for {projectId}", projectId); using var session = _documentStore.OpenAsyncSession(); //var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); var testMode = TestProjectId.IsValidIdentity(projectId) && !ProjectId.IsValidIdentity(projectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)projectId, session) : await _projectManager.Get((ProjectId)projectId, session); var payload = DummyPayload(project.Name, project.Applications.FirstOrDefault()?.SecretKey); return(Ok(payload)); }
public async Task <IActionResult> Data([FromRoute] string projectType, [FromRoute] string id) { var projectId = $"{projectType}/{id}"; _logger.LogInformation("Dummy data url test for {projectId}", projectId); using var session = _documentStore.OpenAsyncSession(); //var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); var testMode = TestProjectId.IsValidIdentity(projectId) && !ProjectId.IsValidIdentity(projectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)projectId, session) : await _projectManager.Get((ProjectId)projectId, session); var payload = DummyPayload(project.Name, project.Applications.FirstOrDefault()?.SecretKey); try { var result = await _applicationTestHttpClient.SendDataTest(project.Applications.First(), payload); return(Ok(result)); } catch (Exception ex) { _logger.LogError(ex, "Unable to test application. {@request}", projectId); return(Ok(GenericResponse.Failed(ex.Message, System.Net.HttpStatusCode.BadRequest))); } }
public async Task <IActionResult> Save(IFormFile file, [FromRoute] string projectNamespace, [FromRoute] string projectId, CancellationToken cancellationToken) { if (!string.Equals(file.ContentType, "image/jpg", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.ContentType, "image/jpeg", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.ContentType, "image/pjpeg", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.ContentType, "image/gif", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.ContentType, "image/x-png", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.ContentType, "image/png", StringComparison.OrdinalIgnoreCase)) { throw new Exception("Incorrect file type"); } // Who's logged in? using var session = _documentStore.OpenAsyncSession(); var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); projectId = $"{projectNamespace}/{projectId}"; var testMode = TestProjectId.IsValidIdentity(projectId) && !ProjectId.IsValidIdentity(projectId); // Which project are we working on? var project = testMode ? await _projectManager.GetTest((TestProjectId)projectId, session) : await _projectManager.Get((ProjectId)projectId, session); string fileExtension; switch (file.ContentType) { case "image/jpg": case "image/jpeg": case "image/pjpeg": fileExtension = ".jpg"; break; case "image/x-png": case "image/png": fileExtension = ".png"; break; case "image/gif": fileExtension = ".gif"; break; default: throw new Exception("Incorrect file type"); } var fileName = $"{Guid.NewGuid()}{fileExtension}"; // Does the user have access to the project? if (!project.AdminIds.Contains(user.Id) && project.OwnerAdminId != user.Id) { throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.Unauthorized); } try { return(Ok(await _fileManager.UploadFileAsync(file, fileName, $"devprojects/assets"))); } catch (Exception e) { _logger.LogError(e, "Unable to upload file."); return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public async Task <IActionResult> Save([FromBody] UpdateApplicationUrlsRequest request) { var errors = Util.UriErrors(new Dictionary <string, string> { { "auth-callback-url", request.AuthCallbackUrl }, { "data-update-callback-url", request.DataUpdateCallbackUrl }, //{ "email-verification-url", request.EmailVerificationUrl }, }, _logger); // if (errors != null && errors.Any()) // { // return BadRequest(new { message = "All urls have to be valid.", errors = errors }); // } try { // Who's logged in? using var session = _documentStore.OpenAsyncSession(); var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); // Which project are we working on? var testMode = TestProjectId.IsValidIdentity(request.ProjectId) && !ProjectId.IsValidIdentity(request.ProjectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)request.ProjectId, session) : await _projectManager.Get((ProjectId)request.ProjectId, session); // Does the user have access to the project? if (!project.AdminIds.Contains(user.Id) && project.OwnerAdminId != user.Id) { throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.Unauthorized); } var application = project.Applications?.FirstOrDefault(); bool recreated = false; if (application != null) { // Check that the application exists through the API try { var apiApplication = await _applicationHttpClient.Get(application.Id); } catch (ApiException ex) { // Unable to get the application if (ex.InnerException is System.Net.Http.HttpRequestException && ex.StatusCode == (int)System.Net.HttpStatusCode.NotFound) { // Not found in API - recreate the application _logger.LogInformation("Application not found in API. Attempting to re-create."); var apiApplication = await _applicationHttpClient.CreateApplication(new CreateApplicationModel { Name = project.Name, AuthCallbackUrl = request.AuthCallbackUrl ?? "", //EmailVerificationNotificationEndpointUrl = request.EmailVerificationUrl ?? "", DataUpdateCallbackUrl = request.DataUpdateCallbackUrl ?? "" }); if (apiApplication != null) { _logger.LogInformation("New application created. {id}", apiApplication.ApplicationId); recreated = true; application = new Core.Entities.Application { Id = apiApplication.ApplicationId, SecretKey = apiApplication.SecretKey, AuthCallbackUrl = request.AuthCallbackUrl, //EmailVerificationUrl = request.EmailVerificationUrl, DataUpdateCallbackUrl = request.DataUpdateCallbackUrl }; } } if (ex.InnerException is System.Net.Http.HttpRequestException && ex.StatusCode == (int)System.Net.HttpStatusCode.RequestTimeout) { throw; } // throw; } catch (System.Exception) { throw; } if (!recreated) { //await _applicationHttpClient.PatchEmailVerificationUrl(application.Id, request.EmailVerificationUrl); await _applicationHttpClient.PatchApiEndpointAppSetNotificationUrl(application.Id, request.DataUpdateCallbackUrl); await _applicationHttpClient.PatchAuthCallbackUrl(application.Id, request.AuthCallbackUrl); application = new Core.Entities.Application { Id = application.Id, SecretKey = application.SecretKey, AuthCallbackUrl = request.AuthCallbackUrl, //EmailVerificationUrl = request.EmailVerificationUrl, DataUpdateCallbackUrl = request.DataUpdateCallbackUrl }; } } else { _logger.LogError("No application found."); return(BadRequest(new { message = "No application found." })); } // One application per project, so just replace project.Applications = new List <Core.Entities.Application> { application }; // Save project = await _projectManager.Update(project, session); await session.SaveChangesAsync(); return(Ok(project)); } catch (ApiException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public async Task<Project> Update(UpdateProjectRequest request, IAsyncDocumentSession session, PlatformAdminUserId userId) { _logger.LogInformation("Project update {@projectId}", request.Id); var requestName = request.Name.Trim(); if (string.IsNullOrEmpty(requestName) || string.IsNullOrWhiteSpace(requestName)) { _logger.LogError("Project update - empty name requested"); throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.BadRequest); } var testMode = TestProjectId.IsValidIdentity(request.Id) && !ProjectId.IsValidIdentity(request.Id); var project = testMode ? await _projectManager.GetTest((TestProjectId)request.Id, session) : await _projectManager.Get((ProjectId)request.Id, session); if (!project.AdminIds.Contains(userId.Value) && project.OwnerAdminId != userId.Value) { _logger.LogError("User {userId} is not part of {ownerId} or {@adminIds}", userId.Value, project.OwnerAdminId, project.AdminIds); throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.Unauthorized); } var updates = new List<string>(); var application = project.Applications.FirstOrDefault(); var platform = project.Platforms.FirstOrDefault(); if (project.Name != requestName) { if (testMode) { _logger.LogInformation("TestProject - skipping name update {@projectId}", request.Id); } else { // TODO: Catch exception thrown on failed update if (application != null) await _applicationHttpClient.SetName(application.Id, requestName); if (platform != null) await _platformAdminHttpClient.SetName(platform.Id.ToString(), requestName); project.Name = requestName; updates.Add(nameof(Project.Name)); // _logger.LogInformation("Project update: {@property}", nameof(Project.Name)); } } if (project.LogoUrl != request.LogoUrl) { // TODO: Catch exception thrown on failed update if (application != null && !testMode) await _applicationHttpClient.SetLogoUrl(application.Id, request.LogoUrl); if (platform != null && !testMode) await _platformAdminHttpClient.SetLogoUrl(platform.Id.ToString(), request.LogoUrl); project.LogoUrl = request.LogoUrl; updates.Add(nameof(Project.LogoUrl)); // _logger.LogInformation("Project update: {@property}", nameof(Project.LogoUrl)); } if (project.Description != request.Description) { // TODO: Catch exception thrown on failed update if (application != null && !testMode) await _applicationHttpClient.SetDescription(application.Id, request.Description); if (platform != null && !testMode) await _platformAdminHttpClient.SetDescription(platform.Id.ToString(), request.Description); project.Description = request.Description; updates.Add(nameof(Project.Description)); // _logger.LogInformation("Project update: {@property}", nameof(Project.Description)); } if (project.Webpage != request.Webpage) { // TODO: Catch exception thrown on failed update if (application != null && !testMode) await _applicationHttpClient.SetWebsiteUrl(application.Id, request.Webpage); if (platform != null && !testMode) await _platformAdminHttpClient.SetWebsiteUrl(platform.Id.ToString(), request.Webpage); project.Webpage = request.Webpage; updates.Add(nameof(Project.Webpage)); // _logger.LogInformation("Project update: {@property}", nameof(Project.Webpage)); } if (updates.Any()) { _logger.LogInformation("Project update: Preparing to save {@updates}", updates); project = await _projectManager.Update(project, session); await session.SaveChangesAsync(); } return project; }