diff options
| author | ivarlovlie <git@ivarlovlie.no> | 2023-02-25 13:15:44 +0100 |
|---|---|---|
| committer | ivarlovlie <git@ivarlovlie.no> | 2023-02-25 13:15:44 +0100 |
| commit | 900bb5e845c3ad44defbd427cae3d44a4a43321f (patch) | |
| tree | df3d96a93771884add571e82336c29fc3d9c7a1c /code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs | |
| download | greatoffice-900bb5e845c3ad44defbd427cae3d44a4a43321f.tar.xz greatoffice-900bb5e845c3ad44defbd427cae3d44a4a43321f.zip | |
feat: Initial commit
Diffstat (limited to 'code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs')
| -rw-r--r-- | code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs b/code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs new file mode 100644 index 0000000..163ddb6 --- /dev/null +++ b/code/api/src/Endpoints/V1/ApiTokens/CreateTokenRoute.cs @@ -0,0 +1,58 @@ +using System.Text; + +namespace IOL.GreatOffice.Api.Endpoints.V1.ApiTokens; + +public class CreateTokenRoute : RouteBaseSync.WithRequest<CreateTokenRoute.Payload>.WithActionResult +{ + private readonly MainAppDatabase _database; + private readonly AppConfiguration _configuration; + private readonly ILogger<CreateTokenRoute> _logger; + + public CreateTokenRoute(MainAppDatabase database, VaultService vaultService, ILogger<CreateTokenRoute> logger) { + _database = database; + _configuration = vaultService.GetCurrentAppConfiguration(); + _logger = logger; + } + + public class Payload + { + public DateTime ExpiryDate { get; set; } + public bool AllowRead { get; set; } + public bool AllowCreate { get; set; } + public bool AllowUpdate { get; set; } + public bool AllowDelete { get; set; } + } + + /// <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")] + public override ActionResult Handle(Payload request) { + var user = _database.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id); + if (user == default) { + return NotFound(new KnownProblemModel("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 accessToken = new ApiAccessToken() { + User = user, + ExpiryDate = request.ExpiryDate.ToUniversalTime(), + AllowCreate = request.AllowCreate, + AllowRead = request.AllowRead, + AllowDelete = request.AllowDelete, + AllowUpdate = request.AllowUpdate + }; + + _database.AccessTokens.Add(accessToken); + _database.SaveChanges(); + return Ok(Convert.ToBase64String(Encoding.UTF8.GetBytes(accessToken.Id.ToString().EncryptWithAes(token_entropy)))); + } +}
\ No newline at end of file |
