btcpayserver/BTCPayServer/Controllers/GreenField/ApiKeysController.cs

81 lines
2.9 KiB
C#
Raw Normal View History

using System.Threading.Tasks;
2020-03-19 11:11:15 +01:00
using System.Linq;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
2020-03-27 04:55:21 +01:00
using BTCPayServer.Security.GreenField;
2020-03-27 06:17:31 +01:00
using NBitcoin.DataEncoders;
using NBitcoin;
2020-03-27 04:58:45 +01:00
namespace BTCPayServer.Controllers.GreenField
{
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.GreenfieldAPIKeys)]
public class ApiKeysController : ControllerBase
{
private readonly APIKeyRepository _apiKeyRepository;
private readonly UserManager<ApplicationUser> _userManager;
public ApiKeysController(APIKeyRepository apiKeyRepository, UserManager<ApplicationUser> userManager)
{
_apiKeyRepository = apiKeyRepository;
_userManager = userManager;
}
[HttpGet("~/api/v1/api-keys/current")]
public async Task<ActionResult<ApiKeyData>> GetKey()
{
2020-03-23 21:18:02 +01:00
if (!ControllerContext.HttpContext.GetAPIKey(out var apiKey))
{
return NotFound();
}
var data = await _apiKeyRepository.GetKey(apiKey);
return Ok(FromModel(data));
}
2020-03-18 12:08:09 +01:00
2020-03-27 06:17:31 +01:00
[HttpPost("~/api/v1/api-keys")]
[Authorize(Policy = Policies.Unrestricted, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<ActionResult<ApiKeyData>> CreateKey(CreateApiKeyRequest request)
{
if (request is null)
return BadRequest();
var key = new APIKeyData()
{
Id = Encoders.Hex.EncodeData(RandomUtils.GetBytes(20)),
Type = APIKeyType.Permanent,
UserId = _userManager.GetUserId(User),
Label = request.Label
};
key.Permissions = string.Join(";", request.Permissions.Select(p => p.ToString()).Distinct().ToArray());
await _apiKeyRepository.CreateKey(key);
return Ok(FromModel(key));
}
[HttpDelete("~/api/v1/api-keys/current")]
[Authorize(Policy = Policies.Unrestricted, AuthenticationSchemes = AuthenticationSchemes.GreenfieldAPIKeys)]
2020-03-27 06:17:31 +01:00
public async Task<IActionResult> RevokeKey()
{
2020-03-23 21:18:02 +01:00
if (!ControllerContext.HttpContext.GetAPIKey(out var apiKey))
{
return NotFound();
}
await _apiKeyRepository.Remove(apiKey, _userManager.GetUserId(User));
return Ok();
}
private static ApiKeyData FromModel(APIKeyData data)
{
return new ApiKeyData()
{
Permissions = Permission.ToPermissions(data.Permissions).ToArray(),
ApiKey = data.Id,
Label = data.Label ?? string.Empty
};
}
}
}