public async Task <IActionResult> Get()
        {
            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            var projectTypes = await projectTypesRepository
                               .ListAsync()
                               .ToListAsync()
                               .ConfigureAwait(false);

            var config = new TeamCloudConfiguration
            {
                ProjectTypes = projectTypes,
                Providers    = teamCloudInstance.Providers,
                Users        = teamCloudInstance.Users,
                Tags         = teamCloudInstance.Tags,
                Properties   = teamCloudInstance.Properties,
            };

            return(DataResult <TeamCloudConfiguration>
                   .Ok(config)
                   .ActionResult());
        }
        public async Task <IActionResult> Post([FromBody] ProjectType projectType)
        {
            if (projectType is null)
            {
                throw new ArgumentNullException(nameof(projectType));
            }

            var validation = new ProjectTypeValidator().Validate(projectType);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var existingProjectType = await projectTypesRepository
                                      .GetAsync(projectType.Id)
                                      .ConfigureAwait(false);

            if (existingProjectType != null)
            {
                return(ErrorResult
                       .Conflict($"A ProjectType with id '{projectType.Id}' already exists.  Please try your request again with a unique id or call PUT to update the existing ProjectType.")
                       .ActionResult());
            }

            var teamCloud = await teamCloudRepository
                            .GetAsync()
                            .ConfigureAwait(false);

            var validProviders = projectType.Providers
                                 .All(projectTypeProvider => teamCloud.Providers.Any(teamCloudProvider => teamCloudProvider.Id == projectTypeProvider.Id));

            if (!validProviders)
            {
                var validProviderIds = string.Join(", ", teamCloud.Providers.Select(p => p.Id));
                return(ErrorResult
                       .BadRequest(new ValidationError {
                    Field = "projectType", Message = $"All provider ids on a ProjectType must match the id of a registered Provider on the TeamCloud instance. Valid provider ids are: {validProviderIds}"
                })
                       .ActionResult());
            }

            var addResult = await orchestrator
                            .AddAsync(projectType)
                            .ConfigureAwait(false);

            var baseUrl  = HttpContext.GetApplicationBaseUrl();
            var location = new Uri(baseUrl, $"api/projectTypes/{addResult.Id}").ToString();

            return(DataResult <ProjectType>
                   .Created(addResult, location)
                   .ActionResult());
        }
        public async Task <IActionResult> Get()
        {
            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            var users = teamCloudInstance?.Users;

            return(users is null
                ? (IActionResult) new NotFoundResult()
                : new OkObjectResult(users));
        }
Esempio n. 4
0
        public async Task <IActionResult> Get()
        {
            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            return(teamCloudInstance is null
                ? (IActionResult) new NotFoundResult()
                : new OkObjectResult(teamCloudInstance.Configuration));
        }
Esempio n. 5
0
        public async Task <IActionResult> Get()
        {
            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            var users = teamCloudInstance?.Users ?? new List <User>();

            return(DataResult <List <User> >
                   .Ok(users.ToList())
                   .ActionResult());
        }
Esempio n. 6
0
        public async Task <IActionResult> Get()
        {
            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            var tags = teamCloudInstance?.Tags is null ? new Dictionary <string, string>() : new Dictionary <string, string>(teamCloudInstance.Tags);

            return(DataResult <Dictionary <string, string> >
                   .Ok(tags)
                   .ActionResult());
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next is null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            // teamcloud needs a at least one admin user to work properly.
            // to avoid calls that will fail because of a missing user
            // we will check its existance in this middleware and block
            // calls until an admin user is in place.

            // as we ensure there is at least one admin user in the delete
            // and update apis we can keep the hasadmin state once it is
            // evaluated to true to avoid unnecessary request to the
            // teamcloud repository in the future.

            HasAdmin = HasAdmin || await AdminExistsAsync().ConfigureAwait(false);

            if (HasAdmin)
            {
                await next(context).ConfigureAwait(false);
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

                var error     = ErrorResult.BadRequest("Must POST an Admin user to api/admin/users before calling any other APIs.", ResultErrorCode.ValidationError);
                var errorJson = JsonConvert.SerializeObject(error);

                await context.Response
                .WriteAsync(errorJson)
                .ConfigureAwait(false);
            }

            async Task <bool> AdminExistsAsync()
            {
                var teamCloudInstance = await teamCloudRepository
                                        .GetAsync()
                                        .ConfigureAwait(false);

                return(teamCloudInstance.Users?.Any(u => u.IsAdmin()) ?? false);
            }
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (Configured)
            {
                await next(context);
            }
            else if (context.Request.Path.StartsWithSegments("/api/config", StringComparison.OrdinalIgnoreCase) &&
                     context.Request.Method == HttpMethods.Post)
            {
                await next(context);
            }
            else
            {
                var teamCloud = await teamCloudRepository.GetAsync().ConfigureAwait(false);

                if (teamCloud?.Configuration != null)
                {
                    var teamCloudConfigValidation = await new TeamCloudConfigurationValidator().ValidateAsync(teamCloud.Configuration);

                    if (teamCloudConfigValidation.IsValid)
                    {
                        Configured = true;

                        await next(context);

                        return;
                    }
                }

                // not configured

                context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                await context.Response.WriteAsync("Must POST a teamcloud.yaml file to api/config before calling any other APIs");
            }
        }
        public async Task <IActionResult> Post([FromBody] UserDefinition userDefinition)
        {
            if (userDefinition is null)
            {
                throw new ArgumentNullException(nameof(userDefinition));
            }

            var validation = new UserDefinitionAdminValidator().Validate(userDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            if (teamCloudInstance.Users.Any(u => u.Role == UserRoles.TeamCloud.Admin))
            {
                return(ErrorResult
                       .BadRequest($"The TeamCloud instance already has an Admin user. To add additional users to the TeamCloud instance POST to api/users.", ResultErrorCode.ValidationError)
                       .ActionResult());
            }

            var newUser = await userService
                          .GetUserAsync(userDefinition)
                          .ConfigureAwait(false);

            if (newUser is null)
            {
                return(ErrorResult
                       .NotFound($"A User with the Email '{userDefinition.Email}' could not be found.")
                       .ActionResult());
            }

            if (teamCloudInstance.Users.Contains(newUser))
            {
                return(ErrorResult
                       .Conflict($"A User with the Email '{userDefinition.Email}' already exists on this TeamCloud Instance. Please try your request again with a unique email or call PUT to update the existing User.")
                       .ActionResult());
            }

            var command = new OrchestratorTeamCloudUserCreateCommand(CurrentUser, newUser);

            var commandResult = await orchestrator
                                .InvokeAsync(command)
                                .ConfigureAwait(false);

            if (commandResult.Links.TryGetValue("status", out var statusUrl))
            {
                return(StatusResult
                       .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
                       .ActionResult());
            }

            throw new Exception("This shouldn't happen, but we need to decide to do when it does.");
        }