From a640703f2da8815dc26ad1600a6f206be1624379 Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Wed, 1 Jun 2022 22:10:32 +0200 Subject: feat: Initial after clean slate --- .../src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs (limited to 'server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs') diff --git a/server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs b/server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs new file mode 100644 index 0000000..e8abbf8 --- /dev/null +++ b/server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs @@ -0,0 +1,52 @@ +using System.Text; + +namespace IOL.GreatOffice.Api.Endpoints.V1.ApiTokens; + +public class CreateTokenRoute : RouteBaseSync.WithRequest.WithActionResult +{ + private readonly AppDbContext _context; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + + public CreateTokenRoute(AppDbContext context, IConfiguration configuration, ILogger logger) { + _context = context; + _configuration = configuration; + _logger = logger; + } + + /// + /// Create a new api token with the provided claims. + /// + /// The claims to set on the api token + /// + [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.GetValue("TOKEN_ENTROPY"); + if (token_entropy.IsNullOrWhiteSpace()) { + _logger.LogWarning("No token entropy is available in env:TOKEN_ENTROPY, 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)))); + } +} -- cgit v1.3