Add methods for managing API keys

This commit is contained in:
Robert Marshall 2021-05-08 10:42:49 +01:00
parent 84ae81d411
commit 3adef125a2
4 changed files with 174 additions and 2 deletions

View file

@ -3,6 +3,7 @@ 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]
@ -24,5 +25,34 @@ namespace Robware.Api.Auth.Controllers {
[HttpPost(nameof(Create))]
[Authorize]
public async Task<ActionResult<ApiKey>> Create(string name) => await _apiKeyRepository.Create(name);
[HttpGet(nameof(List))]
[Authorize]
public async Task<ActionResult<ApiKey[]>> List() => (await _apiKeyRepository.GetAll()).ToArray();
[HttpDelete(nameof(Delete))]
[Authorize]
public async Task<ActionResult> Delete(string key) => await _apiKeyRepository.Delete(key) ? (ActionResult) NoContent() : BadRequest();
private async Task<ActionResult> 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))]
[Authorize]
public async Task<ActionResult> Disable(string key) => await SetEnabled(key, false);
[HttpPatch(nameof(Enable))]
[Authorize]
public async Task<ActionResult> Enable(string key) => await SetEnabled(key, true);
}
}