2020-02-24 18:43:28 +01:00
|
|
|
using System.Threading.Tasks;
|
2020-03-19 19:11:15 +09:00
|
|
|
using System.Linq;
|
|
|
|
using BTCPayServer.Client;
|
2020-03-02 16:50:28 +01:00
|
|
|
using BTCPayServer.Client.Models;
|
|
|
|
using BTCPayServer.Data;
|
2020-02-24 18:43:28 +01:00
|
|
|
using BTCPayServer.Security;
|
|
|
|
using BTCPayServer.Security.APIKeys;
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2020-03-02 16:50:28 +01:00
|
|
|
using Microsoft.AspNetCore.Identity;
|
2020-02-24 18:43:28 +01:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
2020-03-20 14:03:28 +09:00
|
|
|
namespace BTCPayServer.Controllers.RestApi
|
2020-02-24 18:43:28 +01:00
|
|
|
{
|
|
|
|
[ApiController]
|
|
|
|
[Authorize(AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
|
|
|
|
public class ApiKeysController : ControllerBase
|
|
|
|
{
|
|
|
|
private readonly APIKeyRepository _apiKeyRepository;
|
2020-03-02 16:50:28 +01:00
|
|
|
private readonly UserManager<ApplicationUser> _userManager;
|
2020-02-24 18:43:28 +01:00
|
|
|
|
2020-03-02 16:50:28 +01:00
|
|
|
public ApiKeysController(APIKeyRepository apiKeyRepository, UserManager<ApplicationUser> userManager)
|
2020-02-24 18:43:28 +01:00
|
|
|
{
|
|
|
|
_apiKeyRepository = apiKeyRepository;
|
2020-03-02 16:50:28 +01:00
|
|
|
_userManager = userManager;
|
2020-02-24 18:43:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
[HttpGet("~/api/v1/api-keys/current")]
|
|
|
|
public async Task<ActionResult<ApiKeyData>> GetKey()
|
|
|
|
{
|
|
|
|
ControllerContext.HttpContext.GetAPIKey(out var apiKey);
|
|
|
|
var data = await _apiKeyRepository.GetKey(apiKey);
|
2020-03-02 16:50:28 +01:00
|
|
|
return Ok(FromModel(data));
|
|
|
|
}
|
2020-03-18 20:08:09 +09:00
|
|
|
|
2020-03-02 16:50:28 +01:00
|
|
|
[HttpDelete("~/api/v1/api-keys/current")]
|
|
|
|
public async Task<ActionResult<ApiKeyData>> RevokeKey()
|
|
|
|
{
|
|
|
|
ControllerContext.HttpContext.GetAPIKey(out var apiKey);
|
|
|
|
await _apiKeyRepository.Remove(apiKey, _userManager.GetUserId(User));
|
|
|
|
return Ok();
|
|
|
|
}
|
|
|
|
|
|
|
|
private static ApiKeyData FromModel(APIKeyData data)
|
|
|
|
{
|
|
|
|
return new ApiKeyData()
|
|
|
|
{
|
2020-03-20 14:01:51 +09:00
|
|
|
Permissions = Permission.ToPermissions(data.Permissions).ToArray(),
|
2020-03-02 16:50:28 +01:00
|
|
|
ApiKey = data.Id,
|
2020-03-20 20:00:05 +09:00
|
|
|
Label = data.Label ?? string.Empty
|
2020-03-02 16:50:28 +01:00
|
|
|
};
|
2020-02-24 18:43:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|