122 lines
6.8 KiB
C#
122 lines
6.8 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Npgsql;
|
|
using ShellcoreDB;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Diagnostics;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
var connectionString = builder.Configuration.GetConnectionString("Shellcore");
|
|
var serviceKey = builder.Configuration["ShellcoreServiceKey"];
|
|
if (string.IsNullOrWhiteSpace(connectionString))
|
|
throw new InvalidOperationException("ConnectionStrings:Shellcore is required.");
|
|
if (string.IsNullOrWhiteSpace(serviceKey))
|
|
throw new InvalidOperationException("ShellcoreServiceKey is required.");
|
|
|
|
builder.Services.AddSingleton(NpgsqlDataSource.Create(connectionString));
|
|
builder.Services.AddSingleton<Database>();
|
|
builder.Services.AddIdentityCore<IdentityAccount>(options =>
|
|
{
|
|
options.User.AllowedUserNameCharacters = "";
|
|
options.Password.RequiredLength = 12;
|
|
options.Password.RequiredUniqueChars = 1;
|
|
options.Password.RequireDigit = false;
|
|
options.Password.RequireLowercase = false;
|
|
options.Password.RequireUppercase = false;
|
|
options.Password.RequireNonAlphanumeric = false;
|
|
}).AddUserStore<IdentityAccountStore>();
|
|
builder.Services.AddSingleton(new SessionsLifetime(TimeSpan.FromDays(30)));
|
|
builder.Services.AddScoped<Sessions>(provider => new(provider.GetRequiredService<Database>(), provider.GetRequiredService<SessionsLifetime>().Value));
|
|
builder.Services.AddScoped<Auth>();
|
|
builder.Services.AddHttpClient<SteamVerifier>(client => client.Timeout = TimeSpan.FromSeconds(10));
|
|
builder.Services.AddScoped<SteamAuth>();
|
|
builder.Services.AddProblemDetails();
|
|
|
|
var app = builder.Build();
|
|
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
|
|
{
|
|
var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
|
|
var (status, code, message) = exception switch
|
|
{
|
|
SteamUnavailableException => (503, "steamUnavailable", "Steam authentication is unavailable."),
|
|
NpgsqlException => (503, "databaseUnavailable", "Authentication storage is unavailable."),
|
|
_ => (500, "internalError", "An unexpected server error occurred.")
|
|
};
|
|
if (exception is not null) app.Logger.LogError(exception, "Authentication request failed");
|
|
await Results.Problem(statusCode: status, title: message,
|
|
extensions: new Dictionary<string, object?> { ["success"] = false, ["error"] = new ApiError(code, message) })
|
|
.ExecuteAsync(context);
|
|
}));
|
|
|
|
var expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(serviceKey));
|
|
var internalApi = app.MapGroup("/internal");
|
|
internalApi.AddEndpointFilter(async (context, next) =>
|
|
{
|
|
var supplied = context.HttpContext.Request.Headers["X-Service-Key"].ToString();
|
|
var suppliedHash = SHA256.HashData(Encoding.UTF8.GetBytes(supplied));
|
|
if (string.IsNullOrEmpty(supplied) || !CryptographicOperations.FixedTimeEquals(expectedHash, suppliedHash))
|
|
return Results.Json(new Failure(false, new("unauthorized", "A valid service key is required.")), statusCode: 401);
|
|
return await next(context);
|
|
});
|
|
|
|
internalApi.MapPost("/auth/register", async (Credentials body, Auth auth, CancellationToken cancellationToken) =>
|
|
{
|
|
if (string.IsNullOrWhiteSpace(body.username) || body.username.Length > 32 || body.username != body.username.Trim())
|
|
return Results.Json(new Failure(false, new("invalidUsername", "username must be 1 to 32 characters without surrounding spaces.")), statusCode: 400);
|
|
if (string.IsNullOrWhiteSpace(body.password) || body.password.Length < 12 || body.password.Length > 1024)
|
|
return Results.Json(new Failure(false, new("invalidPassword", "password must be 12 to 1024 characters.")), statusCode: 400);
|
|
var account = await auth.Register(body.username, body.password, cancellationToken);
|
|
return account is null
|
|
? Results.Json(new Failure(false, new("usernameTaken", "This username is unavailable.")), statusCode: 409)
|
|
: Results.Json(new Success<AccountData>(true, account), statusCode: 201);
|
|
});
|
|
|
|
internalApi.MapPost("/auth/login", async (Credentials body, Auth auth, CancellationToken cancellationToken) =>
|
|
{
|
|
if (string.IsNullOrWhiteSpace(body.username) || string.IsNullOrEmpty(body.password))
|
|
return Results.Json(new Failure(false, new("invalidCredentials", "Invalid username or password.")), statusCode: 401);
|
|
var login = await auth.Login(body.username, body.password, cancellationToken);
|
|
return login is null
|
|
? Results.Json(new Failure(false, new("invalidCredentials", "Invalid username or password.")), statusCode: 401)
|
|
: Results.Json(new Success<LoginData>(true, login));
|
|
});
|
|
|
|
internalApi.MapPost("/auth/steam", async (SteamTicket body, SteamAuth steam, CancellationToken cancellationToken) =>
|
|
{
|
|
if (string.IsNullOrWhiteSpace(body.ticket))
|
|
return Results.Json(new Failure(false, new("invalidSteamTicket", "A valid Steam ticket is required.")), statusCode: 401);
|
|
if (body.username is not null &&
|
|
(string.IsNullOrWhiteSpace(body.username) || body.username.Length > 32 || body.username != body.username.Trim()))
|
|
return Results.Json(new Failure(false, new("invalidUsername", "username must be 1 to 32 characters without surrounding spaces.")), statusCode: 400);
|
|
var (login, error) = await steam.Authenticate(body.ticket, body.username, cancellationToken);
|
|
return error switch
|
|
{
|
|
null => Results.Json(new Success<LoginData>(true, login!)),
|
|
"usernameTaken" => Results.Json(new Failure(false, new(error, "This username is unavailable.")), statusCode: 409),
|
|
"usernameRequired" => Results.Json(new Failure(false, new(error, "Choose a username to create a Steam account.")), statusCode: 400),
|
|
"accountUnavailable" => Results.Json(new Failure(false, new(error, "This account is unavailable.")), statusCode: 403),
|
|
_ => Results.Json(new Failure(false, new("invalidSteamTicket", "Steam authentication failed.")), statusCode: 401)
|
|
};
|
|
});
|
|
|
|
internalApi.MapPost("/sessions/validate", async (SessionToken body, Sessions sessions, CancellationToken cancellationToken) =>
|
|
{
|
|
if (string.IsNullOrWhiteSpace(body.token))
|
|
return Results.Json(new Failure(false, new("invalidSession", "Session is invalid or expired.")), statusCode: 401);
|
|
var validation = await sessions.Validate(body.token, cancellationToken);
|
|
return validation is null
|
|
? Results.Json(new Failure(false, new("invalidSession", "Session is invalid or expired.")), statusCode: 401)
|
|
: Results.Json(new Success<ValidationData>(true, validation));
|
|
});
|
|
|
|
internalApi.MapPost("/sessions/revoke", async (SessionToken body, Sessions sessions, CancellationToken cancellationToken) =>
|
|
{
|
|
var revoked = !string.IsNullOrWhiteSpace(body.token) && await sessions.Revoke(body.token, cancellationToken);
|
|
return Results.Json(new Success<object>(true, new { revoked }));
|
|
});
|
|
|
|
app.Run();
|
|
|
|
public sealed record SessionsLifetime(TimeSpan Value);
|
|
public partial class Program { }
|