Add hotel team invitations, assisted account recovery and onboarding

This commit is contained in:
wolf-demon
2026-09-15 17:08:13 +01:00
parent 5a93c35b18
commit 7fcf51c900
14 changed files with 377 additions and 18 deletions
+23 -8
View File
@@ -12,7 +12,8 @@ using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
var bootstrap = args.Contains("--bootstrap");
var builder = WebApplication.CreateBuilder(args.Where(arg => arg != "--bootstrap").ToArray());
var recoverOwner = args.Contains("--recover-owner");
var builder = WebApplication.CreateBuilder(args.Where(arg => arg != "--bootstrap" && arg != "--recover-owner").ToArray());
if (builder.Configuration["Pms:ConfigFile"] is { Length: > 0 } pmsConfigFile) builder.Configuration.AddJsonFile(pmsConfigFile,optional:false,reloadOnChange:false);
if (builder.Configuration["Payments:ConfigFile"] is { Length: > 0 } paymentConfigFile) builder.Configuration.AddJsonFile(paymentConfigFile,optional:false,reloadOnChange:false);
builder.Logging.ClearProviders(); builder.Logging.AddConsole();
@@ -35,6 +36,7 @@ builder.Services.AddTransient<PmsWork>();
builder.Services.AddHttpClient<NmiInvoices>(c=>c.Timeout=TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler{AllowAutoRedirect=false});
builder.Services.AddTransient<PaymentWork>();
builder.Services.AddTransient<AutoReplyWork>();
builder.Services.AddTransient<TeamAccounts>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
@@ -46,7 +48,7 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
{
var hotel = c.Principal?.FindFirstValue("hotel"); var id = c.Principal?.FindFirstValue(ClaimTypes.NameIdentifier);
var user = hotel == null || id == null ? null : await c.HttpContext.RequestServices.GetRequiredService<IStore>().Get<StaffUser>(hotel, id);
if (user == null || !user.Active || user.Role != c.Principal!.FindFirstValue(ClaimTypes.Role)) c.RejectPrincipal();
if (user == null || !TeamAccounts.SessionValid(user,c.Principal?.FindFirstValue("security_stamp")) || user.Role != c.Principal!.FindFirstValue(ClaimTypes.Role)) c.RejectPrincipal();
};
});
builder.Services.AddAuthorization(o => o.AddPolicy("Owner", p => p.RequireRole("Owner")));
@@ -65,18 +67,26 @@ builder.Services.AddRateLimiter(o =>
o.RejectionStatusCode = 429;
o.AddPolicy("pms", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
o.AddPolicy("ai", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 6, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
o.AddPolicy("accounts", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
o.AddPolicy("login", context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
});
var app = builder.Build();
app.UseForwardedHeaders();
var store = app.Services.GetRequiredService<IStore>();
await store.Initialize();
if(recoverOwner)
{
var email=Environment.GetEnvironmentVariable("RECOVERY_EMAIL")?.Trim().ToLowerInvariant()??"";
var user=await store.FindLogin(email);if(user==null)throw new InvalidOperationException("An active owner account is required.");
var recovery=await app.Services.GetRequiredService<TeamAccounts>().RecoverOwner(user);
Console.WriteLine("Private single-use recovery link (expires in 30 minutes). Share only with the verified account owner:");Console.WriteLine(recovery.Link);return;
}
if (bootstrap)
{
var email = Environment.GetEnvironmentVariable("BOOTSTRAP_EMAIL")?.Trim().ToLowerInvariant() ?? "";
var password = Environment.GetEnvironmentVariable("BOOTSTRAP_PASSWORD") ?? "";
var hotelName = Environment.GetEnvironmentVariable("BOOTSTRAP_HOTEL") ?? "";
if (!Input.Email(email) || password.Length < 14 || hotelName.Length < 2) throw new InvalidOperationException("Set BOOTSTRAP_EMAIL, BOOTSTRAP_PASSWORD (14+ characters), and BOOTSTRAP_HOTEL.");
if (!Input.Email(email) || !TeamAccounts.PasswordValid(password) || hotelName.Length < 2) throw new InvalidOperationException("Set BOOTSTRAP_EMAIL, BOOTSTRAP_PASSWORD (14 to 128 characters), and BOOTSTRAP_HOTEL.");
if (await store.FindLogin(email) != null) throw new InvalidOperationException("Account already exists; bootstrap does not reset credentials.");
var hotel = new Hotel { Name = hotelName }; hotel.HotelId = hotel.Id;
var user = new StaffUser { HotelId = hotel.Id, Email = email, Name = "Hotel owner" };
@@ -87,10 +97,12 @@ if (bootstrap)
app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["Referrer-Policy"] = "same-origin";
ctx.Response.Headers["Referrer-Policy"] = "no-referrer";
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'";
if (ctx.Request.Path.StartsWithSegments("/api")) ctx.Response.Headers.CacheControl = "no-store";
if (ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/account")) ctx.Response.Headers.CacheControl = "no-store";
try { await next(); }
catch (AccountInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (AccountConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (PaymentInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (PaymentConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (PmsInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
@@ -117,11 +129,11 @@ app.MapGet("/api/session", (HttpContext c, IAntiforgery csrf) => Results.Ok(new
}));
app.MapPost("/api/auth/login", async (LoginInput input, HttpContext c, IPasswordHasher<StaffUser> hasher) =>
{
if (input.Email.Length > 254 || input.Password.Length > 256) return Results.BadRequest(new { error = "Invalid credentials." });
if (input.Email == null || input.Password == null || input.Email.Length > 254 || input.Password.Length > 256) return Results.BadRequest(new { error = "Invalid credentials." });
var user = await store.FindLogin(input.Email.Trim().ToLowerInvariant());
// Verify a dummy hash too so unknown accounts do not have a fast password path.
var checkUser = user ?? new StaffUser();
var hash = user?.PasswordHash ?? Input.DummyHash;
var hash = string.IsNullOrEmpty(user?.PasswordHash) ? Input.DummyHash : user.PasswordHash;
if (hasher.VerifyHashedPassword(checkUser, hash, input.Password) == PasswordVerificationResult.Failed || user?.Active != true)
return Results.Json(new { error = "Email or password is incorrect." }, statusCode: 401);
await Session.SignIn(c, user); return Results.Ok();
@@ -132,6 +144,7 @@ var api = app.MapGroup("/api").RequireAuthorization();
PmsEndpoints.Map(api,preview);
PaymentEndpoints.Map(api,preview);
AutoReplyEndpoints.Map(api,preview);
TeamEndpoints.Map(app,api,preview);
api.MapGet("/hotel", async (HttpContext c, CancellationToken _) => Results.Ok(await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c))));
api.MapPut("/hotel", async (SettingsInput input, HttpContext c) =>
{
@@ -271,7 +284,7 @@ namespace GuestOps.Web
public static class Session
{
public static string Hotel(HttpContext c) => c.User.FindFirstValue("hotel") ?? throw new InvalidOperationException("Missing hotel membership");
public static Task SignIn(HttpContext c, StaffUser u) => c.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, u.Id), new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.Role, u.Role), new Claim("hotel", u.HotelId) }, CookieAuthenticationDefaults.AuthenticationScheme)));
public static Task SignIn(HttpContext c, StaffUser u) => c.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, u.Id), new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.Role, u.Role), new Claim("hotel", u.HotelId), new Claim("security_stamp", u.SecurityStamp) }, CookieAuthenticationDefaults.AuthenticationScheme)));
public static Task Audit(IStore store, HttpContext c, string action) => store.Insert(new Activity { HotelId = Hotel(c), UserName = c.User.Identity?.Name ?? "Staff", Action = action });
}
public static class Input
@@ -283,3 +296,5 @@ namespace GuestOps.Web
public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." });
}
}