using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Robware.Auth.API; using System.Linq; namespace Robware.Api.Auth.Controllers { [ApiController] [Route("[controller]")] public class ApiController : ControllerBase { private readonly ILogger _logger; private readonly IApiKeyValidator _apiKeyValidator; private readonly IApiKeys _apiKeyRepository; public ApiController(ILogger logger, IApiKeyValidator apiKeyValidator, IApiKeys apiKeyRepository) { _logger = logger; _apiKeyValidator = apiKeyValidator; _apiKeyRepository = apiKeyRepository; } [HttpGet(nameof(Validate))] public async Task Validate(string key) => await _apiKeyValidator.Validate(key) ? (ActionResult) Ok() : Unauthorized(); [HttpPost(nameof(Create))] public async Task> Create(string name) => await _apiKeyRepository.Create(name); [HttpGet(nameof(List))] public async Task> List() => (await _apiKeyRepository.GetAll()).ToArray(); [HttpDelete(nameof(Delete))] public async Task Delete(string key) => await _apiKeyRepository.Delete(key) ? (ActionResult) NoContent() : BadRequest(); private async Task SetEnabled(string key, bool enabled) { try { var apiKey = await _apiKeyRepository.Get(key); apiKey.Enabled = enabled; return await _apiKeyRepository.Update(apiKey) ? (ActionResult)NoContent() : BadRequest(); } catch (ApiKeyNotFoundException) { return NotFound(); } } [HttpPatch(nameof(Disable))] public async Task Disable(string key) => await SetEnabled(key, false); [HttpPatch(nameof(Enable))] public async Task Enable(string key) => await SetEnabled(key, true); } }