52 lines
1.8 KiB
C#
52 lines
1.8 KiB
C#
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<ApiController> _logger;
|
|
private readonly IApiKeyValidator _apiKeyValidator;
|
|
private readonly IApiKeys _apiKeyRepository;
|
|
|
|
public ApiController(ILogger<ApiController> logger, IApiKeyValidator apiKeyValidator, IApiKeys apiKeyRepository) {
|
|
_logger = logger;
|
|
_apiKeyValidator = apiKeyValidator;
|
|
_apiKeyRepository = apiKeyRepository;
|
|
}
|
|
|
|
[HttpGet(nameof(Validate))]
|
|
public async Task<ActionResult> Validate(string key) => await _apiKeyValidator.Validate(key) ? (ActionResult) Ok() : Unauthorized();
|
|
|
|
[HttpPost(nameof(Create))]
|
|
public async Task<ActionResult<ApiKey>> Create(string name) => await _apiKeyRepository.Create(name);
|
|
|
|
[HttpGet(nameof(List))]
|
|
public async Task<ActionResult<ApiKey[]>> List() => (await _apiKeyRepository.GetAll()).ToArray();
|
|
|
|
[HttpDelete(nameof(Delete))]
|
|
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))]
|
|
public async Task<ActionResult> Disable(string key) => await SetEnabled(key, false);
|
|
|
|
[HttpPatch(nameof(Enable))]
|
|
public async Task<ActionResult> Enable(string key) => await SetEnabled(key, true);
|
|
}
|
|
}
|