Build private multi-hotel web foundation with MongoDB, Gmail import and Linux deployment

This commit is contained in:
wolf-demon
2026-09-09 14:16:34 +01:00
parent dec97954c9
commit 49d02be623
37 changed files with 2598 additions and 2 deletions
+184
View File
@@ -0,0 +1,184 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.RateLimiting;
using GuestOps.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); builder.Logging.AddConsole();
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);
builder.Logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning);
var preview = builder.Configuration.GetValue<bool>("Preview");
if (preview && !builder.Environment.IsDevelopment()) throw new InvalidOperationException("Preview mode is Development-only.");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024);
var protection = builder.Services.AddDataProtection().SetApplicationName("GuestOps-Web");
var keyPath = builder.Configuration["Keys:Path"];
if (!preview && string.IsNullOrWhiteSpace(keyPath)) throw new InvalidOperationException("Keys:Path must point to a persistent private directory.");
if (keyPath != null) protection.PersistKeysToFileSystem(new DirectoryInfo(keyPath));
builder.Services.AddSingleton<IStore>(s => preview ? new PreviewStore() : new MongoStore(s.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton<IPasswordHasher<StaffUser>, PasswordHasher<StaffUser>>();
builder.Services.AddHttpClient<GoogleMailbox>(c => c.Timeout = TimeSpan.FromSeconds(25));
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always;
o.ExpireTimeSpan = TimeSpan.FromHours(8); o.SlidingExpiration = false;
o.Events.OnRedirectToLogin = c => { c.Response.StatusCode = 401; return Task.CompletedTask; };
o.Events.OnRedirectToAccessDenied = c => { c.Response.StatusCode = 403; return Task.CompletedTask; };
o.Events.OnValidatePrincipal = async c =>
{
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();
};
});
builder.Services.AddAuthorization(o => o.AddPolicy("Owner", p => p.RequireRole("Owner")));
builder.Services.AddAntiforgery(o => { o.HeaderName = "X-CSRF-TOKEN"; o.Cookie.Name = "guestops.csrf"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Strict; o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; });
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = 429;
o.AddPolicy("login", context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
});
var app = builder.Build();
var store = app.Services.GetRequiredService<IStore>();
await store.Initialize();
if (args.Contains("--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 (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" };
user.PasswordHash = app.Services.GetRequiredService<IPasswordHasher<StaffUser>>().HashPassword(user, password);
await store.Insert(hotel); await store.Insert(user);
Console.WriteLine("Hotel and owner account created."); return;
}
app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["Referrer-Policy"] = "same-origin";
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";
try { await next(); }
catch (AntiforgeryValidationException) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = "Your session needs refreshing. Reload the page and try again." }); }
catch (Exception ex)
{
app.Logger.LogError("Request failed ({Type}), trace {Trace}", ex.GetType().Name, ctx.TraceIdentifier);
if (!ctx.Response.HasStarted) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsJsonAsync(new { error = "The request could not be completed. Please try again.", trace = ctx.TraceIdentifier }); }
}
});
app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter();
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && !HttpMethods.IsGet(ctx.Request.Method) && !HttpMethods.IsHead(ctx.Request.Method))
await ctx.RequestServices.GetRequiredService<IAntiforgery>().ValidateRequestAsync(ctx);
await next();
});
app.MapGet("/health", () => Results.Ok(new { status = "ready" }));
app.MapGet("/api/session", (HttpContext c, IAntiforgery csrf) => Results.Ok(new
{
preview, csrfToken = csrf.GetAndStoreTokens(c).RequestToken,
user = c.User.Identity?.IsAuthenticated == true ? new { id = c.User.FindFirstValue(ClaimTypes.NameIdentifier), name = c.User.Identity.Name, role = c.User.FindFirstValue(ClaimTypes.Role), hotelId = c.User.FindFirstValue("hotel") } : null
}));
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." });
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;
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();
}).RequireRateLimiting("login");
app.MapPost("/api/auth/logout", async (HttpContext c, CancellationToken _) => { await c.SignOutAsync(); return Results.Ok(); }).RequireAuthorization();
if (preview) app.MapPost("/api/preview/start", async (HttpContext c, CancellationToken _) => { var user = await Demo.Seed(store); await Session.SignIn(c, user); return Results.Ok(); }).RequireRateLimiting("login");
var api = app.MapGroup("/api").RequireAuthorization();
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) =>
{
if (!Input.Text(input.Name, 2, 120) || !Input.Text(input.Signature, 0, 2000)) return Results.BadRequest(new { error = "Enter a hotel name and a signature under 2,000 characters." });
try { _ = TimeZoneInfo.FindSystemTimeZoneById(input.Timezone); } catch { return Results.BadRequest(new { error = "Choose a valid timezone." }); }
var hotel = await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c)); if (hotel == null) return Results.NotFound();
hotel.Name = input.Name.Trim(); hotel.Signature = input.Signature; hotel.Timezone = input.Timezone; hotel.Version = input.Version + 1;
if (!await store.Replace(hotel.HotelId, hotel.Id, input.Version, hotel)) return Input.Conflict();
await Session.Audit(store, c, "Updated hotel settings"); return Results.Ok(hotel);
}).RequireAuthorization("Owner");
api.MapGet("/conversations", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Conversation>(Session.Hotel(c))).OrderByDescending(x => x.ReceivedAt)));
api.MapPut("/conversations/{id}/draft", async (string id, DraftInput input, HttpContext c) =>
{
if (!Input.Text(input.Draft, 0, 20000)) return Results.BadRequest(new { error = "Draft must be under 20,000 characters." });
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Draft = input.Draft; item.Version = input.Version + 1; if (item.Status != "Completed") item.Status = input.Draft.Length > 0 ? "DraftReady" : "NeedsAttention";
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, "Saved a reply draft"); return Results.Ok(item);
});
api.MapPut("/conversations/{id}/status", async (string id, StatusInput input, HttpContext c) =>
{
if (input.Status is not ("Completed" or "NeedsAttention")) return Results.BadRequest();
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Status = input.Status; item.Version = input.Version + 1;
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, input.Status == "Completed" ? "Resolved a conversation" : "Reopened a conversation"); return Results.Ok(item);
});
api.MapGet("/knowledge", async (HttpContext c, CancellationToken _) => Results.Ok(await store.List<KnowledgeEntry>(Session.Hotel(c))));
api.MapPost("/knowledge", async (KnowledgeInput input, HttpContext c) =>
{
if (!Input.Knowledge(input)) return Results.BadRequest(new { error = "Enter a title and answer within the allowed lengths." });
var item = new KnowledgeEntry { HotelId = Session.Hotel(c), Title = input.Title, Category = input.Category, Answer = input.Answer, Keywords = input.Keywords, Approved = input.Approved };
await store.Insert(item); await Session.Audit(store, c, "Added a hotel knowledge entry"); return Results.Ok(item);
}).RequireAuthorization("Owner");
api.MapPut("/knowledge/{id}", async (string id, KnowledgeInput input, HttpContext c) =>
{
if (!Input.Knowledge(input)) return Results.BadRequest();
var item = await store.Get<KnowledgeEntry>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Title = input.Title; item.Category = input.Category; item.Answer = input.Answer; item.Keywords = input.Keywords; item.Approved = input.Approved; item.Version = input.Version + 1;
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, "Updated hotel knowledge"); return Results.Ok(item);
}).RequireAuthorization("Owner");
api.MapGet("/activity", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Activity>(Session.Hotel(c))).OrderByDescending(x => x.At).Take(100)));
api.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google) => Results.Ok(new { configured = !preview && google.Configured, items = (await store.List<Mailbox>(Session.Hotel(c))).Select(x => new { x.Id, x.Email, x.Status, x.LastSyncAt, x.SyncError }) }));
api.MapPost("/integrations/google/connect", async (HttpContext c, GoogleMailbox google) =>
{
if (preview || !google.Configured) return Results.BadRequest(new { error = "Google connection has not been configured by the administrator." });
var state = new OAuthRequest { Id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), HotelId = Session.Hotel(c), UserId = c.User.FindFirstValue(ClaimTypes.NameIdentifier)!, ExpiresAt = DateTime.UtcNow.AddMinutes(10) };
await store.Insert(state); return Results.Ok(new { url = google.AuthorizationUrl(state.Id) });
}).RequireAuthorization("Owner");
api.MapGet("/integrations/google/callback", async (HttpContext c, GoogleMailbox google) =>
{
if (preview) return Results.BadRequest();
var state = await store.ConsumeOAuth(c.Request.Query["state"].ToString(), Session.Hotel(c), c.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
if (state == null) return Results.BadRequest(new { error = "The connection request expired. Start again from Settings." });
if (c.Request.Query.ContainsKey("error")) return Results.Redirect("/settings?google=cancelled");
try { await google.Connect(Session.Hotel(c), c.Request.Query["code"].ToString()); await Session.Audit(store, c, "Connected Google mailbox"); }
catch { return Results.Redirect("/settings?google=failed"); }
return Results.Redirect("/settings?google=connected");
}).RequireAuthorization("Owner");
app.UseDefaultFiles(); app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
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 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
{
public static readonly string DummyHash = new PasswordHasher<StaffUser>().HashPassword(new(), Convert.ToHexString(RandomNumberGenerator.GetBytes(32)));
public static bool Text(string? s, int min, int max) => s != null && s.Trim().Length >= min && s.Length <= max;
public static bool Email(string s) => System.Net.Mail.MailAddress.TryCreate(s, out var address) && address.Address == s;
public static bool Knowledge(KnowledgeInput s) => Text(s.Title, 2, 120) && Text(s.Answer, 2, 5000) && Text(s.Category, 1, 50) && Text(s.Keywords, 0, 300);
public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." });
}
}