blob: 352ad18d0e3ecd87377974902aa591ec8f03b9c3 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
using System.Text;
using Microsoft.Extensions.Options;
namespace IOL.GreatOffice.Api.Endpoints.V1.ApiTokens;
public class CreateTokenRoute : RouteBaseSync.WithRequest<ApiAccessToken.ApiAccessTokenDto>.WithActionResult
{
private readonly AppDbContext _context;
private readonly AppConfiguration _configuration;
private readonly ILogger<CreateTokenRoute> _logger;
public CreateTokenRoute(AppDbContext context, VaultService vaultService, ILogger<CreateTokenRoute> logger) {
_context = context;
_configuration = vaultService.GetCurrentAppConfiguration();
_logger = logger;
}
/// <summary>
/// Create a new api token with the provided claims.
/// </summary>
/// <param name="request">The claims to set on the api token</param>
/// <returns></returns>
[ApiVersion(ApiSpecV1.VERSION_STRING)]
[HttpPost("~/v{version:apiVersion}/api-tokens/create")]
[ProducesResponseType(200, Type = typeof(string))]
[ProducesResponseType(404, Type = typeof(ErrorResult))]
public override ActionResult Handle(ApiAccessToken.ApiAccessTokenDto request) {
var user = _context.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id);
if (user == default) {
return NotFound(new ErrorResult("User does not exist"));
}
var token_entropy = _configuration.APP_AES_KEY;
if (token_entropy.IsNullOrWhiteSpace()) {
_logger.LogWarning("No token entropy is available, Basic auth is disabled");
return NotFound();
}
var access_token = new ApiAccessToken() {
Id = Guid.NewGuid(),
User = user,
ExpiryDate = request.ExpiryDate.ToUniversalTime(),
AllowCreate = request.AllowCreate,
AllowRead = request.AllowRead,
AllowDelete = request.AllowDelete,
AllowUpdate = request.AllowUpdate
};
_context.AccessTokens.Add(access_token);
_context.SaveChanges();
return Ok(Convert.ToBase64String(Encoding.UTF8.GetBytes(access_token.Id.ToString().EncryptWithAes(token_entropy))));
}
}
|