/// <inheritdoc/>
        protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            GiteaPushPermissionRequirement requirement)
        {
            if (_httpContext == null)
            {
                return;
            }

            string org = _httpContext.GetRouteValue("org")?.ToString();
            string app = _httpContext.GetRouteValue("app")?.ToString();

            if (string.IsNullOrWhiteSpace(org) ||
                string.IsNullOrWhiteSpace(app))
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            RepositoryClient.Model.Repository repository = await _giteaApiWrapper.GetRepository(org, app);

            if (repository?.Permissions?.Push == true ||
                repository?.Permissions?.Admin == true)
            {
                context.Succeed(requirement);
            }
            else
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
        }
Пример #2
0
        public Repository GetRepository(string owner, string repository)
        {
            Repository returnRepository = _giteaApi.GetRepository(owner, repository).Result;

            return(returnRepository);
        }
Пример #3
0
        public async Task <IActionResult> StartDeployment(string org, string appName)
        {
            if (org == null || appName == null)
            {
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Application owner (org) and application name must be supplied",
                }));
            }

            if (_configuration["AccessTokenDevOps"] == null)
            {
                ViewBag.ServiceUnavailable = true;
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Deployment failed: no access token",
                }));
            }

            Repository repository = _giteaAPI.GetRepository(org, appName).Result;

            if (repository != null && repository.Permissions != null && repository.Permissions.Push != true)
            {
                ViewBag.ServiceUnavailable = true;
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Deployment failed: not authorized",
                }));
            }

            string credentials = _configuration["AccessTokenDevOps"];

            string result       = string.Empty;
            Branch masterBranch = _giteaAPI.GetBranch(org, appName, "master").Result;

            if (masterBranch == null)
            {
                _logger.LogWarning($"Unable to fetch branch information for app owner {org} and app {appName}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed: unable to find latest commit",
                }));
            }

            // register application in platform storage
            bool applicationInStorage = await RegisterApplicationInStorage(org, appName, masterBranch.Commit.Id);

            if (!applicationInStorage)
            {
                _logger.LogWarning($"Unable to deploy app {appName} for {org} to Platform Storage");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = $"Deployment of Application Metadata to Platform Storage failed",
                }));
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                    string giteaEnvironment = (Environment.GetEnvironmentVariable("GeneralSettings__HostName") ?? _settings.HostName) + "/repos";
                    object buildContent     = new
                    {
                        definition = new
                        {
                            id = 5,
                        },
                        parameters = $"{{\"APP_OWNER\":\"{org}\",\"APP_REPO\":\"{appName}\",\"APP_DEPLOY_TOKEN\":\"{_sourceControl.GetDeployToken()}\",\"GITEA_ENVIRONMENT\":\"{giteaEnvironment}\", \"APP_COMMIT_ID\":\"{masterBranch.Commit.Id}\",\"should_deploy\":\"{true}\"}}\"",
                    };

                    string        buildjson   = JsonConvert.SerializeObject(buildContent);
                    StringContent httpContent = new StringContent(buildjson, Encoding.UTF8, "application/json");

                    using (HttpResponseMessage response = await client.PostAsync("https://dev.azure.com/brreg/altinn-studio/_apis/build/builds?api-version=5.0-preview.4", httpContent))
                    {
                        response.EnsureSuccessStatusCode();
                        BuildModel responseBody = await response.Content.ReadAsAsync <BuildModel>();

                        result = responseBody.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Unable deploy app {appName} for {org} because {ex}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed " + ex,
                }));
            }

            return(Ok(new DeploymentResponse
            {
                Success = true,
                BuildId = result,
                Message = "Deployment status: " + result,
            }));
        }
        public async Task <RepositoryModel> GetRepository(string org, string repository)
        {
            RepositoryModel returnRepository = await _giteaApi.GetRepository(org, repository);

            return(returnRepository);
        }
        /// <inheritdoc/>
        protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            GiteaDeployPermissionRequirement requirement)
        {
            if (_httpContext == null)
            {
                return;
            }

            string org = _httpContext.GetRouteValue("org")?.ToString();
            string app = _httpContext.GetRouteValue("app")?.ToString();

            if (string.IsNullOrWhiteSpace(org) ||
                string.IsNullOrWhiteSpace(app))
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (!_settings.CheckTeamMembershipForDeploy)
            {
                RepositoryClient.Model.Repository repository = await _giteaApiWrapper.GetRepository(org, app);

                if (repository?.Permissions?.Push == true ||
                    repository?.Permissions?.Admin == true)
                {
                    context.Succeed(requirement);
                }
                else
                {
                    _httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                }

                return;
            }

            string environment = _httpContext.GetRouteValue("environment")?.ToString();

            if (string.IsNullOrEmpty(environment))
            {
                _httpContext.Request.EnableBuffering();

                using (var reader = new StreamReader(
                           _httpContext.Request.Body,
                           encoding: Encoding.UTF8,
                           detectEncodingFromByteOrderMarks: false,
                           bufferSize: 1024,
                           leaveOpen: true))
                {
                    string body = await reader.ReadToEndAsync();

                    try
                    {
                        CreateDeploymentRequestViewModel model = JsonConvert.DeserializeObject <CreateDeploymentRequestViewModel>(body);
                        environment = model.Environment.Name;
                    }
                    catch
                    {
                        reader.Close();
                        _httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return;
                    }

                    // Reset the request body stream position so the next middleware can read it
                    _httpContext.Request.Body.Position = 0;
                }
            }

            string      matchTeam = $"Deploy-{environment}";
            List <Team> teams     = await _giteaApiWrapper.GetTeams();

            bool any = teams.Any(t => t.Organization.Username.Equals(
                                     org, System.StringComparison.OrdinalIgnoreCase) &&
                                 t.Name.Equals(matchTeam, System.StringComparison.OrdinalIgnoreCase));

            if (any)
            {
                context.Succeed(requirement);
            }
            else
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
        }
Пример #6
0
        public RepositoryModel GetRepository(string org, string repository)
        {
            RepositoryModel returnRepository = _giteaApi.GetRepository(org, repository).Result;

            return(returnRepository);
        }