using System; using System.Linq; using System.Net; using System.Threading.Tasks; using Bit.Core; using Bit.Core.Enums; using Bit.Core.Models.Api.Public; using Bit.Core.Repositories; using Bit.Core.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Bit.Api.Public.Controllers { [Route("public/policies")] [Authorize("Organization")] public class PoliciesController : Controller { private readonly IPolicyRepository _policyRepository; private readonly IPolicyService _policyService; private readonly CurrentContext _currentContext; public PoliciesController( IPolicyRepository policyRepository, IPolicyService policyService, CurrentContext currentContext) { _policyRepository = policyRepository; _policyService = policyService; _currentContext = currentContext; } /// /// Retrieve a policy. /// /// /// Retrieves the details of a policy. /// /// The type of policy to be retrieved. [HttpGet("{type}")] [ProducesResponseType(typeof(GroupResponseModel), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task Get(PolicyType type) { var policy = await _policyRepository.GetByOrganizationIdTypeAsync( _currentContext.OrganizationId.Value, type); if(policy == null) { return new NotFoundResult(); } var response = new PolicyResponseModel(policy); return new JsonResult(response); } /// /// List all policies. /// /// /// Returns a list of your organization's policies. /// [HttpGet] [ProducesResponseType(typeof(ListResponseModel), (int)HttpStatusCode.OK)] public async Task List() { var policies = await _policyRepository.GetManyByOrganizationIdAsync(_currentContext.OrganizationId.Value); var policyResponses = policies.Select(p => new PolicyResponseModel(p)); var response = new ListResponseModel(policyResponses); return new JsonResult(response); } /// /// Update a policy. /// /// /// Updates the specified policy. If a property is not provided, /// the value of the existing property will be reset. /// /// The type of policy to be updated. /// The request model. [HttpPut("{id}")] [ProducesResponseType(typeof(PolicyResponseModel), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task Put(PolicyType type, [FromBody]PolicyUpdateRequestModel model) { var policy = await _policyRepository.GetByOrganizationIdTypeAsync( _currentContext.OrganizationId.Value, type); if(policy == null) { policy = model.ToPolicy(_currentContext.OrganizationId.Value); } else { policy = model.ToPolicy(policy); } await _policyService.SaveAsync(policy); var response = new PolicyResponseModel(policy); return new JsonResult(response); } } }