Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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)));
            }
        }
Exemplo n.º 3
0
        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;
            }
        }
Exemplo n.º 4
0
        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));
        }
Exemplo n.º 5
0
        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));
            }
        }
Exemplo n.º 7
0
        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;
        }
        public async Task <IActionResult> PlatformLive([FromBody] UpdatePlatformStatusRequest request)
        {
            if (!ProjectId.IsValidIdentity(request.ProjectId))
            {
                // Test projects cannot be published
                throw new ApiException("Not a valid project id. Test projects cannot be published.");
            }

            using var session = _documentStore.OpenAsyncSession();
            var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session);

            var userId  = (PlatformAdminUserId)user.Id;
            var project = await _projectManager.Get((ProjectId)request.ProjectId, session);

            if (!project.AdminIds.Contains(userId.Value) && project.OwnerAdminId != userId.Value)
            {
                throw new ApiException("Seems you are not an admin on this project.", (int)System.Net.HttpStatusCode.Unauthorized);
            }

            var errors = this.stringErrors(new Dictionary <string, string>
            {
                { "project-name", project.Name },
                { "project-webpage", project.Webpage },
                { "project-description", project.Description },
                { "project-logo", project.LogoUrl },
            });

            if (errors != null && errors.Any())
            {
                throw new ApiException("The project information is incomplete. Please fill out a name, webpage and description, and add a logo to the project, to publish it.", (int)System.Net.HttpStatusCode.ExpectationFailed, errors);
            }

            var platformId = project.Platforms.FirstOrDefault().Id.ToString();

            try
            {
                var apiPlatform =
                    await _platformAdminHttpClient.GetPlatform(new ProjectModel { PlatformId = platformId });
            }
            catch (ApiException ex)
            {
                _logger.LogInformation("InnerException {exception} status code {statusCode}", ex.InnerException, ex.StatusCode);
                if (ex.InnerException is System.Net.Http.HttpRequestException && ex.StatusCode == 404)
                {
                    // The platform wasn't found - see if we can create it
                    _logger.LogInformation(ex, "Unable to get platform {platformId} - attempting creation", project.Platforms?.FirstOrDefault()?.Id);
                    var apiPlatform = await _platformAdminHttpClient.CreatePlatform(new CreatePlatformModel
                    {
                        AuthMechanism      = PlatformAuthenticationMechanism.Email,
                        Name               = project.Name,
                        MaxRating          = 5,
                        MinRating          = 1,
                        RatingSuccessLimit = 3,
                        Description        = project.Description,
                        LogoUrl            = project.LogoUrl,
                        WebsiteUrl         = project.Webpage
                    });

                    if (apiPlatform == null)
                    {
                        _logger.LogCritical(ex, "Unable to create platform for project {projectId}", project.Id);
                        throw;
                    }
                    platformId        = apiPlatform.PlatformId.ToString();
                    project.Platforms = new List <Core.Entities.Platform> {
                        Core.Entities.Platform.Create(apiPlatform.PlatformId, project.Platforms.FirstOrDefault().ExportDataUri)
                    };
                    _logger.LogInformation("Created platform {platformId} and added to project {projectId}", apiPlatform.PlatformId, project.Id);
                }
                else
                {
                    _logger.LogCritical(ex, "Unable to get platform status for project {projectId} platform {platformId}", project.Id, project.Platforms?.FirstOrDefault()?.Id);
                    throw;
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Unable to retrieve platform status for project {projectId} platform {platformId}", project.Id, project.Platforms?.FirstOrDefault()?.Id);
                throw new ApiException(ex, 500);
            }

            if (request.Status == "deactivate")
            {
                await _platformAdminHttpClient.DeactivatePlatform(new ProjectModel { PlatformId = platformId });

                project.DeactivatePlatform();
            }
            else
            {
                await _platformAdminHttpClient.ActivatePlatform(new ProjectModel { PlatformId = platformId });

                project.ActivatePlatform();
            }

            project = await _projectManager.Update(project, session);

            await session.SaveChangesAsync();

            return(Ok(project));
        }
        public async Task <IActionResult> PlatformUrl([FromBody] UpdatePlatformUrlRequest request)
        {
            //var errors = Util.UriErrors(new Dictionary<string, string>
            //{ { "platform-url", request.Url },
            //}, _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);

                var testMode = !ProjectId.IsValidIdentity(request.ProjectId);

                // Which project are we working on?
                Core.Entities.Project project = (!request.TestMode && ProjectId.IsValidIdentity(request.ProjectId)) ?
                                                await _projectManager.Get((ProjectId)request.ProjectId, session) :

                                                // if (request.TestMode && TestProjectId.IsValidIdentity(request.ProjectId))
                                                await _projectManager.GetTest(request.ProjectId, session);

                if (project == null)
                {
                    throw new ApiException("Project not found.", (int)System.Net.HttpStatusCode.NotFound);
                }
                // 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);
                }

                Core.Entities.Platform platform;

                if (project.Platforms == null || !project.Platforms.Any())
                {
                    _logger.LogCritical("Platform not found.");
                    throw new ApiException("Platform not found. Please contact your admin or create a new project.", (int)System.Net.HttpStatusCode.NotFound);
                }
                else if (project.Platforms.FirstOrDefault().ExportDataUri == request.Url)
                {
                    // No change. Return.
                    return(Ok(project));
                }
                else
                {
                    if (!testMode)
                    {
                        var existingPlatform = await _platformAdminHttpClient.GetPlatform(project.Platforms.FirstOrDefault().Id);

                        platform = new Core.Entities.Platform {
                            Id = existingPlatform.PlatformId, PlatformToken = project.Platforms.FirstOrDefault().PlatformToken, ExportDataUri = request.Url, LastUpdate = DateTime.UtcNow, Published = !existingPlatform.IsInactive
                        };
                    }
                    else
                    {
                        platform = project.Platforms.FirstOrDefault();
                        platform.ExportDataUri = request.Url;
                    }
                }
                // One platform per project, so just replace. Create() above also sets the LastUpdated date.
                project.Platforms = new List <Core.Entities.Platform> {
                    platform
                };

                // Save
                project = await _projectManager.Update(project, session);

                // TODO: If saving fails, revert back by deleting the platform that was registered with the GigDataService
                await session.SaveChangesAsync();

                return(Ok(project));
            }
            catch (ApiException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }