69 lines
2.4 KiB
C#
69 lines
2.4 KiB
C#
using ManagerService.Data;
|
|
using ManagerService.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using NSwag.Annotations;
|
|
using System;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ManagerService.Controllers
|
|
{
|
|
[Authorize(Policy = ManagerService.Service.Security.Policies.InstanceAdmin)]
|
|
[ApiController, Route("api/[controller]")]
|
|
[OpenApiTag("ApiKey", Description = "API Key management for mobile apps")]
|
|
public class ApiKeyController : ControllerBase
|
|
{
|
|
private readonly ApiKeyDatabaseService _apiKeyService;
|
|
|
|
public ApiKeyController(ApiKeyDatabaseService apiKeyService)
|
|
{
|
|
_apiKeyService = apiKeyService;
|
|
}
|
|
|
|
/// <summary>List API keys for the caller's instance</summary>
|
|
[HttpGet]
|
|
public async Task<IActionResult> GetApiKeys()
|
|
{
|
|
var instanceId = User.FindFirst(ManagerService.Service.Security.ClaimTypes.InstanceId)?.Value;
|
|
if (string.IsNullOrEmpty(instanceId))
|
|
return Forbid();
|
|
|
|
var keys = await _apiKeyService.GetByInstanceAsync(instanceId);
|
|
return Ok(keys);
|
|
}
|
|
|
|
/// <summary>Create a new API key (plain key returned once)</summary>
|
|
[HttpPost]
|
|
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
|
|
{
|
|
if (request == null || string.IsNullOrEmpty(request.Name))
|
|
return BadRequest("Name is required");
|
|
|
|
var instanceId = User.FindFirst(ManagerService.Service.Security.ClaimTypes.InstanceId)?.Value;
|
|
if (string.IsNullOrEmpty(instanceId))
|
|
return Forbid();
|
|
|
|
var plainKey = await _apiKeyService.CreateAsync(instanceId, request.Name, request.AppType);
|
|
return Ok(new { key = plainKey });
|
|
}
|
|
|
|
/// <summary>Revoke an API key</summary>
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> RevokeApiKey(string id)
|
|
{
|
|
var instanceId = User.FindFirst(ManagerService.Service.Security.ClaimTypes.InstanceId)?.Value;
|
|
if (string.IsNullOrEmpty(instanceId))
|
|
return Forbid();
|
|
|
|
var success = await _apiKeyService.RevokeAsync(id, instanceId);
|
|
return success ? NoContent() : NotFound();
|
|
}
|
|
}
|
|
|
|
public class CreateApiKeyRequest
|
|
{
|
|
public string Name { get; set; }
|
|
public ApiKeyAppType AppType { get; set; }
|
|
}
|
|
}
|