summaryrefslogtreecommitdiffstats
path: root/server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs
diff options
context:
space:
mode:
authorivarlovlie <git@ivarlovlie.no>2022-06-01 22:10:32 +0200
committerivarlovlie <git@ivarlovlie.no>2022-06-01 22:10:32 +0200
commita640703f2da8815dc26ad1600a6f206be1624379 (patch)
treedbda195fb5783d16487e557e06471cf848b75427 /server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs
downloadgreatoffice-a640703f2da8815dc26ad1600a6f206be1624379.tar.xz
greatoffice-a640703f2da8815dc26ad1600a6f206be1624379.zip
feat: Initial after clean slate
Diffstat (limited to 'server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs')
-rw-r--r--server/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs52
1 files changed, 52 insertions, 0 deletions
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<ApiAccessToken.ApiAccessTokenDto>.WithActionResult
+{
+ private readonly AppDbContext _context;
+ private readonly IConfiguration _configuration;
+ private readonly ILogger<CreateTokenRoute> _logger;
+
+ public CreateTokenRoute(AppDbContext context, IConfiguration configuration, ILogger<CreateTokenRoute> logger) {
+ _context = context;
+ _configuration = configuration;
+ _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.GetValue<string>("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))));
+ }
+}