first commit
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]/[action]")]
|
||||
public abstract class ApiControllerBase : ControllerBase
|
||||
{
|
||||
protected Guid UserId
|
||||
{
|
||||
get
|
||||
{
|
||||
var options = HttpContext.RequestServices.GetRequiredService<Microsoft.Extensions.Options.IOptions<SequenceAuth.Lib.SequenceAuthOptions>>().Value;
|
||||
return Guid.Parse(HttpContext.Items[options.UserIdItemKey]?.ToString() ?? throw new UnauthorizedAccessException());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SequenceAuth.Example.Features.Auth;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class AuthController(IMediator mediator) : ApiControllerBase
|
||||
{
|
||||
public record LoginRequest(string Username);
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||
{
|
||||
var result = await mediator.Send(new LoginCommand(request.Username));
|
||||
return Ok(result.User);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
await mediator.Send(new LogoutCommand());
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class SecureController : ApiControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public IActionResult GetData()
|
||||
{
|
||||
return Ok(new { Message = "This is protected data. You must have a valid sequence to see this." });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Features.Todos;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class TodoController(IMediator mediator) : ApiControllerBase
|
||||
{
|
||||
public record CreateTodoRequest(string Title);
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateTodoRequest request)
|
||||
{
|
||||
var result = await mediator.Send(new CreateTodoCommand(UserId, request.Title));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List([FromQuery] TodoStatus? status)
|
||||
{
|
||||
var result = await mediator.Send(new GetTodosQuery(UserId, status));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> ChangeStatus(Guid id, [FromQuery] TodoStatus status)
|
||||
{
|
||||
var result = await mediator.Send(new ChangeTodoStatusCommand(id, UserId, status));
|
||||
|
||||
return result.Outcome switch
|
||||
{
|
||||
ChangeTodoStatusOutcome.Success => Ok(result.Item),
|
||||
ChangeTodoStatusOutcome.NotFound => NotFound(),
|
||||
ChangeTodoStatusOutcome.Unauthorized => StatusCode(403), // No identity claims for Forbid() without auth scheme
|
||||
_ => StatusCode(500)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SequenceAuth.Example.Domain;
|
||||
|
||||
public record User(Guid Id, string Username);
|
||||
|
||||
public enum TodoStatus
|
||||
{
|
||||
Pending,
|
||||
InProgress,
|
||||
Completed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
public record TodoItem(Guid Id, Guid UserId, string Title, TodoStatus Status);
|
||||
@@ -0,0 +1,42 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Auth;
|
||||
|
||||
public record LoginCommand(string Username) : IRequest<LoginResult>;
|
||||
public record LoginResult(User User, string InitialSequence);
|
||||
|
||||
public class LoginCommandHandler(AppDbContext dbContext, ISequenceStore sequenceStore, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor, Microsoft.Extensions.Options.IOptions<SequenceAuth.Lib.SequenceAuthOptions> options) : IRequestHandler<LoginCommand, LoginResult>
|
||||
{
|
||||
public async Task<LoginResult> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userOpt = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == request.Username, cancellationToken);
|
||||
|
||||
var user = userOpt switch
|
||||
{
|
||||
null => await CreateUser(request.Username, cancellationToken),
|
||||
_ => userOpt
|
||||
};
|
||||
|
||||
var initialSequenceId = Guid.NewGuid().ToString("N");
|
||||
var sequenceData = new SequenceData(UserId: user.Id.ToString(), RequestsRemaining: 1000, State: SequenceState.Initialized, NextSequenceId: initialSequenceId);
|
||||
|
||||
await sequenceStore.SaveSequenceAsync(initialSequenceId, sequenceData);
|
||||
|
||||
httpContextAccessor.HttpContext?.Response.Headers.Append(options.Value.NextHeaderName, initialSequenceId);
|
||||
httpContextAccessor.HttpContext?.Response.Headers.Append(options.Value.RequestsRemainingHeaderName, "1000");
|
||||
|
||||
return new LoginResult(user, initialSequenceId);
|
||||
}
|
||||
|
||||
private async Task<User> CreateUser(string username, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = new User(Guid.NewGuid(), username);
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Auth;
|
||||
|
||||
public record LogoutCommand() : IRequest;
|
||||
|
||||
public class LogoutCommandHandler(ISequenceStore sequenceStore, IHttpContextAccessor httpContextAccessor, Microsoft.Extensions.Options.IOptions<SequenceAuthOptions> options) : IRequestHandler<LogoutCommand>
|
||||
{
|
||||
public async Task Handle(LogoutCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userIdStr = httpContextAccessor.HttpContext?.Items[options.Value.UserIdItemKey]?.ToString();
|
||||
var isUserIdPresent = string.IsNullOrEmpty(userIdStr);
|
||||
|
||||
_ = isUserIdPresent switch
|
||||
{
|
||||
false => await ProcessLogout(userIdStr!),
|
||||
true => 0
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<int> ProcessLogout(string userId)
|
||||
{
|
||||
await sequenceStore.InvalidateUserSessionsAsync(userId);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public enum ChangeTodoStatusOutcome { Success, NotFound, Unauthorized }
|
||||
|
||||
public record ChangeTodoStatusResult(ChangeTodoStatusOutcome Outcome, TodoItem? Item);
|
||||
|
||||
public record ChangeTodoStatusCommand(Guid TodoId, Guid UserId, TodoStatus NewStatus) : IRequest<ChangeTodoStatusResult>;
|
||||
|
||||
public class ChangeTodoStatusCommandHandler(AppDbContext dbContext) : IRequestHandler<ChangeTodoStatusCommand, ChangeTodoStatusResult>
|
||||
{
|
||||
public async Task<ChangeTodoStatusResult> Handle(ChangeTodoStatusCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var todo = await dbContext.Todos.FirstOrDefaultAsync(t => t.Id == request.TodoId, cancellationToken);
|
||||
|
||||
return todo switch
|
||||
{
|
||||
null => new ChangeTodoStatusResult(ChangeTodoStatusOutcome.NotFound, null),
|
||||
{ UserId: var userId } when userId != request.UserId => new ChangeTodoStatusResult(ChangeTodoStatusOutcome.Unauthorized, null),
|
||||
_ => await UpdateStatusAsync(todo, request.NewStatus, cancellationToken)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<ChangeTodoStatusResult> UpdateStatusAsync(TodoItem todo, TodoStatus newStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
var updatedTodo = todo with { Status = newStatus };
|
||||
|
||||
dbContext.Entry(todo).CurrentValues.SetValues(updatedTodo);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new ChangeTodoStatusResult(ChangeTodoStatusOutcome.Success, updatedTodo);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using MediatR;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public record CreateTodoCommand(Guid UserId, string Title) : IRequest<TodoItem>;
|
||||
|
||||
public class CreateTodoCommandHandler(AppDbContext dbContext) : IRequestHandler<CreateTodoCommand, TodoItem>
|
||||
{
|
||||
public async Task<TodoItem> Handle(CreateTodoCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var todo = new TodoItem(Guid.NewGuid(), request.UserId, request.Title, TodoStatus.Pending);
|
||||
dbContext.Todos.Add(todo);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return todo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public record GetTodosQuery(Guid UserId, TodoStatus? StatusFilter) : IRequest<List<TodoItem>>;
|
||||
|
||||
public class GetTodosQueryHandler(AppDbContext dbContext) : IRequestHandler<GetTodosQuery, List<TodoItem>>
|
||||
{
|
||||
public async Task<List<TodoItem>> Handle(GetTodosQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = dbContext.Todos.Where(t => t.UserId == request.UserId);
|
||||
|
||||
query = request.StatusFilter switch
|
||||
{
|
||||
null => query,
|
||||
var status => query.Where(t => t.Status == status)
|
||||
};
|
||||
|
||||
return await query.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
|
||||
namespace SequenceAuth.Example.Infrastructure;
|
||||
|
||||
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<TodoItem> Todos => Set<TodoItem>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<User>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Username).IsRequired();
|
||||
entity.HasIndex(e => e.Username).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<TodoItem>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Title).IsRequired();
|
||||
entity.Property(e => e.Status).HasConversion<string>();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace SequenceAuth.Example.Infrastructure;
|
||||
|
||||
public class KebabCaseParameterTransformer : IOutboundParameterTransformer
|
||||
{
|
||||
public string? TransformOutbound(object? value)
|
||||
{
|
||||
return value == null ? null : value.ToString()!.ToKebabCase();
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class StringExtension
|
||||
{
|
||||
[GeneratedRegex("([a-z0-9])([A-Z])", RegexOptions.Compiled)]
|
||||
private static partial Regex KebabCaseRule();
|
||||
|
||||
public static string ToKebabCase(this string input)
|
||||
=> KebabCaseRule().Replace(input, "$1-$2").ToLower().Trim('-');
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260612174016_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.TodoItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Todos");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.User", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Todos",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Title = table.Column<string>(type: "text", nullable: false),
|
||||
Status = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Todos", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Users",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Username = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Users", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_Username",
|
||||
table: "Users",
|
||||
column: "Username",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Todos");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
partial class AppDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.TodoItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Todos");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.User", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace SequenceAuth.Example.Options;
|
||||
|
||||
public record RedisOptions
|
||||
{
|
||||
public required string Configuration { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Scalar.AspNetCore;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
using SequenceAuth.Example.Options;
|
||||
using SequenceAuth.Lib;
|
||||
using StackExchange.Redis;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseParameterTransformer()));
|
||||
});
|
||||
|
||||
builder.Services.AddDbContext<AppDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection") ?? "Host=localhost;Database=sequencedb;Username=sequence_user;Password=sequence_password");
|
||||
});
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
|
||||
|
||||
var sequenceOptions = new SequenceAuthOptions();
|
||||
builder.Services.AddSequenceAuth(opts =>
|
||||
{
|
||||
opts.IgnoredPaths = sequenceOptions.IgnoredPaths.Concat(["/auth/login"]).ToHashSet();
|
||||
});
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(policy =>
|
||||
{
|
||||
policy.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders(sequenceOptions.NextHeaderName, sequenceOptions.RequestsRemainingHeaderName);
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.Configure<RedisOptions>(builder.Configuration.GetSection("RedisOptions"));
|
||||
|
||||
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
||||
ConnectionMultiplexer.Connect(sp.GetRequiredService<IOptions<RedisOptions>>().Value.Configuration));
|
||||
|
||||
builder.Services.AddSingleton<ISequenceStore, SequenceAuth.Example.RedisSequenceStore>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
await db.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
app.MapOpenApi();
|
||||
|
||||
app.MapScalarApiReference(options =>
|
||||
{
|
||||
options.Title = "SequenceAuth API";
|
||||
options.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
|
||||
});
|
||||
|
||||
app.MapGet("/", () => Results.Redirect("/scalar/v1"));
|
||||
|
||||
app.UseCors();
|
||||
app.UseMiddleware<SequenceAuthMiddleware>();
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
public partial class Program { }
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5064",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7215;http://localhost:5064",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using StackExchange.Redis;
|
||||
using System.Text.Json;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example;
|
||||
|
||||
public class RedisSequenceStore(IConnectionMultiplexer redis) : ISequenceStore
|
||||
{
|
||||
private readonly IDatabase _db = redis.GetDatabase();
|
||||
|
||||
public async Task<Option<SequenceData>> GetSequenceAsync(string sequenceId)
|
||||
{
|
||||
var value = await _db.StringGetAsync(sequenceId);
|
||||
|
||||
return ((string?)value) switch
|
||||
{
|
||||
null => Option<SequenceData>.None(),
|
||||
string str => ParseData(str)
|
||||
};
|
||||
}
|
||||
|
||||
private static Option<SequenceData> ParseData(string str)
|
||||
{
|
||||
var data = JsonSerializer.Deserialize<SequenceData>(str);
|
||||
return data switch
|
||||
{
|
||||
null => Option<SequenceData>.None(),
|
||||
_ => Option<SequenceData>.Some(data)
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<StoreOutcome> SaveSequenceAsync(string sequenceId, SequenceData data)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(data);
|
||||
_ = await _db.StringSetAsync(sequenceId, json);
|
||||
_ = await _db.SetAddAsync($"UserSessions:{data.UserId}", sequenceId);
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
|
||||
public async Task<StoreOutcome> InvalidateUserSessionsAsync(string userId)
|
||||
{
|
||||
var sessionKeys = await _db.SetMembersAsync($"UserSessions:{userId}");
|
||||
foreach(var key in sessionKeys)
|
||||
{
|
||||
var seqOpt = await GetSequenceAsync(key.ToString());
|
||||
_ = seqOpt.State switch
|
||||
{
|
||||
OptionState.Some => await UpdateToCompromisedAsync(key.ToString(), seqOpt.Value!),
|
||||
_ => StoreOutcome.Failure
|
||||
};
|
||||
}
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
|
||||
private async Task<StoreOutcome> UpdateToCompromisedAsync(string sequenceId, SequenceData data)
|
||||
{
|
||||
var compData = data with { State = SequenceState.Compromised };
|
||||
var json = JsonSerializer.Serialize(compData);
|
||||
_ = await _db.StringSetAsync(sequenceId, json);
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="14.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="2.13.17" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\lib\SequenceAuth.Lib.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@SequenceAuth.Example_HostAddress = http://localhost:5064
|
||||
|
||||
GET {{SequenceAuth.Example_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Port=5432;Database=sequencedb;Username=sequence_user;Password=sequence_password"
|
||||
},
|
||||
"RedisOptions": {
|
||||
"Configuration": "localhost:6379"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user