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;
}
/// List API keys for the caller's instance
[HttpGet]
public async Task 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);
}
/// Create a new API key (plain key returned once)
[HttpPost]
public async Task 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 });
}
/// Revoke an API key
[HttpDelete("{id}")]
public async Task 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; }
}
}