Skip to content

Commit

Permalink
Add endpoint to generate single-event tokens from an event key
Browse files Browse the repository at this point in the history
  • Loading branch information
NixFey committed Dec 24, 2024
1 parent d847063 commit d19a814
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 3 deletions.
65 changes: 65 additions & 0 deletions FiMAdminApi/Endpoints/AvTokenEndpoints.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Asp.Versioning.Builder;
using FiMAdminApi.Data;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace FiMAdminApi.Endpoints;

public static class AvTokenEndpoints
{
public static WebApplication RegisterAvTokenEndpoints(this WebApplication app, ApiVersionSet vs)
{
var eventsCreateGroup = app.MapGroup("/api/v{apiVersion:apiVersion}/av-token")
.WithApiVersionSet(vs).HasApiVersion(1).WithTags("AV Tokens")
.AllowAnonymous();

eventsCreateGroup.MapPost("", CreateAvToken)
.WithSummary("Create Token for AV System")
.WithDescription(
"Will return a token with limited permissions for a specific event, valid until the event's end date");

return app;
}

private static async Task<Results<Ok<CreateAvTokenResponse>, ProblemHttpResult>> CreateAvToken(
[FromBody] CreateAvTokenRequest request,
[FromServices] IConfiguration configuration,
[FromServices] DataContext dbContext)
{
var escapedEventKey = request.EventKey.Replace("%", "\\%").Replace("_", "\\_");
var evt = await dbContext.Events.FirstOrDefaultAsync(e =>
EF.Functions.ILike(e.Key, escapedEventKey) &&
e.StartTime < DateTime.UtcNow && e.EndTime > DateTime.UtcNow);
if (evt is null) return TypedResults.Problem("Unable to authenticate at this time with the given event key");

var jwtSecret = configuration["Auth:JwtSecret"] ??
throw new ApplicationException("Unable to get JWT secret from configuration");

List<Claim> claims = [new Claim("eventName", evt.Name), new Claim("eventKey", evt.Key)];
if (evt.Code is not null) claims.Add(new Claim("eventCode", evt.Code));

var maxAllowableExpiry = DateTime.UtcNow.AddDays(7);

var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(
jwtSecret));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "https://admin.fimav.us/av-token",
claims: claims,
// 7 days or when the event ends, whichever is sooner
expires: evt.EndTime > maxAllowableExpiry ? maxAllowableExpiry : evt.EndTime,
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);

return TypedResults.Ok(new CreateAvTokenResponse(jwt));
}

public record CreateAvTokenRequest(string EventKey);

public record CreateAvTokenResponse(string AccessToken);
}
2 changes: 1 addition & 1 deletion FiMAdminApi/Infrastructure/ApiStartupExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public static IEndpointRouteBuilder UseApiDocumentation(this IEndpointRouteBuild
<link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css">
</head>
<body>
<elements-api apiDescriptionUrl="/openapi/v1.json" router="hash" basePath="/docs"/>
<elements-api apiDescriptionUrl="/openapi/v1.json" router="hash"/>
</body>
</html>
""";
Expand Down
3 changes: 2 additions & 1 deletion FiMAdminApi/Infrastructure/SerializerContext.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Collections.Specialized;
using System.Text.Json;
using System.Text.Json.Serialization;
using FiMAdminApi.Data.Models;
Expand All @@ -25,6 +24,8 @@ namespace FiMAdminApi.Infrastructure;
[JsonSerializable(typeof(TruckRoute))]
[JsonSerializable(typeof(TruckRoutesEndpoints.CreateTruckRoute))]
[JsonSerializable(typeof(TruckRoutesEndpoints.EditTruckRoute))]
[JsonSerializable(typeof(AvTokenEndpoints.CreateAvTokenRequest))]
[JsonSerializable(typeof(AvTokenEndpoints.CreateAvTokenResponse))]
public partial class SerializerContext : JsonSerializerContext
{
}
3 changes: 2 additions & 1 deletion FiMAdminApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
.RegisterEventsEndpoints(globalVs)
.RegisterTruckRoutesEndpoints(globalVs)
.RegisterEventSyncEndpoints(globalVs)
.RegisterMatchesEndpoints(globalVs);
.RegisterMatchesEndpoints(globalVs)
.RegisterAvTokenEndpoints(globalVs);

app.Run();
6 changes: 6 additions & 0 deletions FiMAdminApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,11 @@
"AuthId": "BADDATA",
"AuthSecret": "ExqeZK3Gbo9v95YnqmsiADzESo9HNgyhIOYSMyRpqJqYv13EazNRaDIPPJuOXrQp"
}
},
"Sync": {
"Secret": ""
},
"Auth": {
"JwtSecret": ""
}
}

0 comments on commit d19a814

Please sign in to comment.