Add hotel team invitations, assisted account recovery and onboarding
This commit is contained in:
@@ -24,6 +24,11 @@ public class Hotel : TenantDocument
|
||||
}
|
||||
public class StaffUser : TenantDocument
|
||||
{
|
||||
public long Version {get;set;}
|
||||
public string SecurityStamp {get;set;}="";
|
||||
public string AccountLinkHash {get;set;}="";
|
||||
public string AccountLinkPurpose {get;set;}="";
|
||||
public DateTime? AccountLinkExpiresAt {get;set;}
|
||||
public string Email { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public string PasswordHash { get; set; } = "";
|
||||
|
||||
@@ -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." });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ public interface IStore
|
||||
Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument;
|
||||
Task Delete<T>(string hotel, string id) where T : TenantDocument;
|
||||
Task<StaffUser?> FindLogin(string email);
|
||||
Task<StaffUser?> FindAccountLink(string hash);
|
||||
Task<bool> TryInsertStaff(StaffUser user);
|
||||
Task<bool> ConsumeAccountLink(StaffUser user,long version,string hash);
|
||||
Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user);
|
||||
Task<List<Mailbox>> Mailboxes();
|
||||
Task SaveMailbox(Mailbox mailbox);
|
||||
@@ -45,6 +48,7 @@ public sealed class MongoStore : IStore
|
||||
}
|
||||
public async Task Initialize()
|
||||
{
|
||||
await Collection<StaffUser>().Indexes.CreateOneAsync(new CreateIndexModel<StaffUser>(Builders<StaffUser>.IndexKeys.Ascending(x=>x.AccountLinkHash)));
|
||||
foreach(var field in new[]{"ThreadKey","RecipientDay","DaySlot"})await Collection<AutoReplyClaim>().Indexes.CreateOneAsync(new CreateIndexModel<AutoReplyClaim>(Builders<AutoReplyClaim>.IndexKeys.Ascending(x=>x.HotelId).Ascending(field),new(){Unique=true}));
|
||||
await Collection<Conversation>().Indexes.CreateOneAsync(new CreateIndexModel<Conversation>(Builders<Conversation>.IndexKeys.Ascending(x=>x.HotelId).Ascending(x=>x.MailboxId).Ascending(x=>x.AutoReplyCheckedAt).Ascending(x=>x.ReceivedAt)));
|
||||
await Collection<PaymentRequest>().Indexes.CreateOneAsync(new CreateIndexModel<PaymentRequest>(Builders<PaymentRequest>.IndexKeys.Ascending(x=>x.HotelId).Ascending(x=>x.Reference),new(){Unique=true}));
|
||||
@@ -76,10 +80,19 @@ public sealed class MongoStore : IStore
|
||||
public async Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument
|
||||
{
|
||||
if (document.HotelId != hotel || document.Id != id) throw new InvalidOperationException("Invalid document scope.");
|
||||
var result = await Collection<T>().ReplaceOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id) & Builders<T>.Filter.Eq("Version", version), document);
|
||||
var versionFilter=Builders<T>.Filter.Eq("Version",version);
|
||||
if(typeof(T)==typeof(StaffUser)&&version==0)versionFilter|=Builders<T>.Filter.Exists("Version",false);
|
||||
var result = await Collection<T>().ReplaceOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id) & versionFilter, document);
|
||||
return result.ModifiedCount == 1;
|
||||
}
|
||||
public async Task Delete<T>(string hotel, string id) where T : TenantDocument => await Collection<T>().DeleteOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id));
|
||||
public async Task<StaffUser?> FindAccountLink(string hash)=>await Collection<StaffUser>().Find(x=>x.AccountLinkHash==hash&&x.AccountLinkExpiresAt>DateTime.UtcNow).FirstOrDefaultAsync();
|
||||
public async Task<bool> TryInsertStaff(StaffUser user){try{await Insert(user);return true;}catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return false;}}
|
||||
public async Task<bool> ConsumeAccountLink(StaffUser user,long version,string hash)
|
||||
{
|
||||
var filter=Scope<StaffUser>(user.HotelId)&Builders<StaffUser>.Filter.Eq(x=>x.Id,user.Id)&Builders<StaffUser>.Filter.Eq(x=>x.Version,version)&Builders<StaffUser>.Filter.Eq(x=>x.AccountLinkHash,hash)&Builders<StaffUser>.Filter.Gt(x=>x.AccountLinkExpiresAt,DateTime.UtcNow);
|
||||
return (await Collection<StaffUser>().ReplaceOneAsync(filter,user)).ModifiedCount==1;
|
||||
}
|
||||
public async Task<StaffUser?> FindLogin(string email) => await Collection<StaffUser>().Find(x => x.Email == email).FirstOrDefaultAsync();
|
||||
public async Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) => await Collection<OAuthRequest>().FindOneAndDeleteAsync(x => x.Id == id && x.HotelId == hotel && x.UserId == user && x.ExpiresAt > DateTime.UtcNow);
|
||||
public Task<List<Mailbox>> Mailboxes() => Collection<Mailbox>().Find(x => x.Status == "Connected").ToListAsync();
|
||||
@@ -167,6 +180,12 @@ public sealed class PreviewStore : IStore
|
||||
}
|
||||
}
|
||||
public async Task Delete<T>(string hotel, string id) where T : TenantDocument { if (await Get<T>(hotel, id) != null) rows.TryRemove(Key<T>(id), out _); }
|
||||
public Task<StaffUser?> FindAccountLink(string hash)=>Task.FromResult(rows.Where(x=>x.Key.StartsWith("StaffUser:")).Select(x=>Clone<StaffUser>(x.Value)).SingleOrDefault(x=>x.AccountLinkHash==hash&&x.AccountLinkExpiresAt>DateTime.UtcNow));
|
||||
public Task<bool> TryInsertStaff(StaffUser user){lock(gate){if(rows.Where(x=>x.Key.StartsWith("StaffUser:")).Select(x=>Clone<StaffUser>(x.Value)).Any(x=>x.Email==user.Email))return Task.FromResult(false);return Task.FromResult(rows.TryAdd(Key<StaffUser>(user.Id),Json(user)));}}
|
||||
public Task<bool> ConsumeAccountLink(StaffUser user,long version,string hash)
|
||||
{
|
||||
lock(gate){if(!rows.TryGetValue(Key<StaffUser>(user.Id),out var raw))return Task.FromResult(false);var old=Clone<StaffUser>(raw);if(old.HotelId!=user.HotelId||old.Version!=version||old.AccountLinkHash!=hash||old.AccountLinkExpiresAt<=DateTime.UtcNow||old.AccountLinkExpiresAt==null)return Task.FromResult(false);rows[Key<StaffUser>(user.Id)]=Json(user);return Task.FromResult(true);}
|
||||
}
|
||||
public Task<StaffUser?> FindLogin(string email) => Task.FromResult(rows.Where(x => x.Key.StartsWith("StaffUser:")).Select(x => Clone<StaffUser>(x.Value)).SingleOrDefault(x => x.Email == email));
|
||||
public Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) { lock(gate) { var x = rows.TryGetValue(Key<OAuthRequest>(id), out var raw) ? Clone<OAuthRequest>(raw) : null; if(x?.HotelId != hotel || x.UserId != user || x.ExpiresAt <= DateTime.UtcNow) return Task.FromResult<OAuthRequest?>(null); rows.TryRemove(Key<OAuthRequest>(id),out _); return Task.FromResult<OAuthRequest?>(x); } }
|
||||
public Task<List<Mailbox>> Mailboxes() => Task.FromResult(new List<Mailbox>());
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
namespace GuestOps.Web;
|
||||
public sealed record InviteInput(string Name,string Email);
|
||||
public sealed record AccountTokenInput(string Token);
|
||||
public sealed record AccountAcceptInput(string Token,string Password,string ConfirmPassword);
|
||||
public sealed record AccountLinkResult(string UserId,string Link,DateTime ExpiresAt);
|
||||
public sealed class AccountInvalid(string message):Exception(message);
|
||||
public sealed class AccountConflict(string message):Exception(message);
|
||||
public sealed class TeamAccounts(IStore store,IPasswordHasher<StaffUser> hasher,IConfiguration config)
|
||||
{
|
||||
public static object View(StaffUser user)=>new {user.Id,user.Name,user.Email,user.Role,user.Active,user.Version,pending=user.PasswordHash.Length==0,linkPurpose=user.AccountLinkPurpose,linkExpiresAt=user.AccountLinkExpiresAt};
|
||||
public static bool SessionValid(StaffUser user,string? stamp)=>user.Active&&user.SecurityStamp==(stamp??"");
|
||||
public static bool PasswordValid(string? password)=>password!=null&&password.Length>=14&&password.Length<=128;
|
||||
static string Hash(string token)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
string BaseUrl()
|
||||
{
|
||||
if(config.GetValue<bool>("Preview"))return "http://127.0.0.1:5173";
|
||||
var value=config["PublicUrl"];
|
||||
if(!Uri.TryCreate(value,UriKind.Absolute,out var uri)||uri.Scheme!="https"||uri.Port!=443||uri.IsLoopback||uri.UserInfo.Length>0||uri.AbsolutePath!="/"||uri.Query.Length>0||uri.Fragment.Length>0)throw new AccountInvalid("The administrator must configure the public HTTPS address before issuing account links.");
|
||||
return uri.GetLeftPart(UriPartial.Authority);
|
||||
}
|
||||
public async Task<AccountLinkResult> Invite(string hotel,InviteInput input)
|
||||
{
|
||||
if(!Input.Text(input.Name,2,100)||!Input.Text(input.Email,3,254))throw new AccountInvalid("Enter a staff name and email address.");
|
||||
var email=input.Email.Trim().ToLowerInvariant();if(!Input.Email(email)||email.Any(char.IsControl))throw new AccountInvalid("Enter one plain staff email address.");
|
||||
_=BaseUrl();
|
||||
var user=await store.FindLogin(email);
|
||||
if(user!=null&&(user.HotelId!=hotel||user.Role!="Staff"||user.PasswordHash.Length>0))throw new AccountInvalid("This email is unavailable for invitation. Contact the administrator.");
|
||||
if(user==null)
|
||||
{
|
||||
if((await store.List<StaffUser>(hotel)).Count>=50)throw new AccountInvalid("This hotel has reached the 50-account pilot limit. Contact the administrator.");
|
||||
user=new StaffUser{HotelId=hotel,Name=input.Name.Trim(),Email=email,Role="Staff",Active=false};
|
||||
if(!await store.TryInsertStaff(user))throw new AccountConflict("The account changed elsewhere. Refresh the team list.");
|
||||
}
|
||||
user.Name=input.Name.Trim();return await Issue(user,"Invite",TimeSpan.FromHours(48));
|
||||
}
|
||||
public Task<AccountLinkResult> ResetStaff(StaffUser user,long version)
|
||||
{
|
||||
if(user.Role!="Staff"||!user.Active||user.Version!=version||user.PasswordHash.Length==0)throw new AccountConflict("Only the current active staff account can receive a recovery link.");
|
||||
return Issue(user,"Reset",TimeSpan.FromMinutes(30));
|
||||
}
|
||||
public Task<AccountLinkResult> RecoverOwner(StaffUser user)
|
||||
{
|
||||
if(user.Role!="Owner"||!user.Active)throw new AccountInvalid("An active owner account is required.");return Issue(user,"Reset",TimeSpan.FromMinutes(30));
|
||||
}
|
||||
public Task<AccountLinkResult> Restore(StaffUser user,long version)
|
||||
{
|
||||
if(user.Role!="Staff"||user.Active||user.Version!=version||user.PasswordHash.Length==0)throw new AccountConflict("Only the current disabled staff account can be restored.");
|
||||
return Issue(user,"Restore",TimeSpan.FromHours(48));
|
||||
}
|
||||
async Task<AccountLinkResult> Issue(StaffUser user,string purpose,TimeSpan lifetime)
|
||||
{
|
||||
var root=BaseUrl();var token=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));var version=user.Version;
|
||||
user.AccountLinkHash=Hash(token);user.AccountLinkPurpose=purpose;user.AccountLinkExpiresAt=DateTime.UtcNow.Add(lifetime);user.Version++;
|
||||
if(!await store.Replace(user.HotelId,user.Id,version,user))throw new AccountConflict("The account changed elsewhere. Refresh and issue a new link.");
|
||||
return new(user.Id,root+"/account#token="+token,user.AccountLinkExpiresAt.Value);
|
||||
}
|
||||
public async Task<StaffUser?> Inspect(string? token)
|
||||
{
|
||||
if(token==null||!Regex.IsMatch(token,"^[A-F0-9]{64}$"))return null;
|
||||
var user=await store.FindAccountLink(Hash(token));
|
||||
if(user==null||user.AccountLinkExpiresAt<=DateTime.UtcNow||user.AccountLinkExpiresAt==null)return null;
|
||||
if(user.AccountLinkPurpose=="Invite"&&user.Role=="Staff"&&!user.Active&&user.PasswordHash.Length==0)return user;
|
||||
if(user.AccountLinkPurpose=="Restore"&&user.Role=="Staff"&&!user.Active&&user.PasswordHash.Length>0)return user;
|
||||
return user.AccountLinkPurpose=="Reset"&&user.Active&&user.PasswordHash.Length>0?user:null;
|
||||
}
|
||||
public async Task<bool> Accept(AccountAcceptInput input)
|
||||
{
|
||||
if(!PasswordValid(input.Password)||input.Password!=input.ConfirmPassword)throw new AccountInvalid("Use matching passwords of 14 to 128 characters.");
|
||||
var user=await Inspect(input.Token);if(user==null)return false;
|
||||
var hash=user.AccountLinkHash;var version=user.Version;
|
||||
user.PasswordHash=hasher.HashPassword(user,input.Password);user.Active=true;user.SecurityStamp=Guid.NewGuid().ToString("N");user.Version++;
|
||||
user.AccountLinkHash="";user.AccountLinkPurpose="";user.AccountLinkExpiresAt=null;
|
||||
return await store.ConsumeAccountLink(user,version,hash);
|
||||
}
|
||||
public async Task<bool> Disable(StaffUser user,long version)
|
||||
{
|
||||
if(user.Role!="Staff"||user.Version!=version)return false;
|
||||
user.Active=false;user.SecurityStamp=Guid.NewGuid().ToString("N");user.AccountLinkHash="";user.AccountLinkPurpose="";user.AccountLinkExpiresAt=null;user.Version++;
|
||||
return await store.Replace(user.HotelId,user.Id,version,user);
|
||||
}
|
||||
public async Task<bool> Revoke(StaffUser user,long version)
|
||||
{
|
||||
if(user.Role!="Staff"||user.Version!=version)return false;
|
||||
user.AccountLinkHash="";user.AccountLinkPurpose="";user.AccountLinkExpiresAt=null;user.Version++;
|
||||
return await store.Replace(user.HotelId,user.Id,version,user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
namespace GuestOps.Web;
|
||||
public static class TeamEndpoints
|
||||
{
|
||||
public static void Map(WebApplication app,RouteGroupBuilder api,bool preview)
|
||||
{
|
||||
app.MapPost("/api/account-links/inspect",async(AccountTokenInput input,TeamAccounts accounts,IStore store)=>
|
||||
{
|
||||
var user=await accounts.Inspect(input.Token);if(user==null)return Results.BadRequest(new {error="This link is invalid or has expired. Ask for a new link."});
|
||||
var hotel=await store.Get<Hotel>(user.HotelId,user.HotelId);
|
||||
return Results.Ok(new {user.Name,user.Email,purpose=user.AccountLinkPurpose,expiresAt=user.AccountLinkExpiresAt,hotelName=hotel?.Name});
|
||||
}).RequireRateLimiting("accounts");
|
||||
app.MapPost("/api/account-links/accept",async(AccountAcceptInput input,TeamAccounts accounts,IStore store,HttpContext c)=>
|
||||
{
|
||||
var user=await accounts.Inspect(input.Token);
|
||||
if(user==null||!await accounts.Accept(input))return Results.BadRequest(new {error="This link is invalid or has expired. Ask for a new link."});
|
||||
await store.Insert(new Activity{HotelId=user.HotelId,UserName=user.Name,Action=user.AccountLinkPurpose=="Invite"?"Accepted staff invitation":"Changed account password"});
|
||||
await c.SignOutAsync();return Results.Ok();
|
||||
}).RequireRateLimiting("accounts");
|
||||
var team=api.MapGroup("/team").RequireAuthorization("Owner");
|
||||
team.MapGet("/",async(HttpContext c,IStore store)=>Results.Ok((await store.List<StaffUser>(Session.Hotel(c))).Select(TeamAccounts.View)));
|
||||
team.MapPost("/invite",async(InviteInput input,HttpContext c,IStore store,TeamAccounts accounts)=>
|
||||
{
|
||||
var result=await accounts.Invite(Session.Hotel(c),input);await Session.Audit(store,c,"Issued a staff invitation link");return Results.Ok(result);
|
||||
}).RequireRateLimiting("accounts");
|
||||
team.MapPost("/{id}/{action}",async(string id,string action,VersionInput input,HttpContext c,IStore store,TeamAccounts accounts)=>
|
||||
{
|
||||
var user=await store.Get<StaffUser>(Session.Hotel(c),id);if(user==null)return Results.NotFound();
|
||||
if(user.Role!="Staff")return Results.BadRequest(new {error="Owner accounts are managed by the server administrator."});
|
||||
if(action is "reset" or "restore")
|
||||
{
|
||||
var result=action=="reset"?await accounts.ResetStaff(user,input.Version):await accounts.Restore(user,input.Version);
|
||||
await Session.Audit(store,c,action=="reset"?"Issued a staff password recovery link":"Issued a staff restoration link");return Results.Ok(result);
|
||||
}
|
||||
if(action is not ("disable" or "revoke"))return Results.NotFound();
|
||||
if(!(action=="disable"?await accounts.Disable(user,input.Version):await accounts.Revoke(user,input.Version)))return Input.Conflict();
|
||||
await Session.Audit(store,c,action=="disable"?"Disabled a staff account":"Revoked a staff account link");return Results.Ok();
|
||||
}).RequireRateLimiting("accounts");
|
||||
api.MapGet("/onboarding",async(HttpContext c,IStore store)=>
|
||||
{
|
||||
var id=Session.Hotel(c);var hotel=await store.Get<Hotel>(id,id);
|
||||
var knowledge=await store.List<KnowledgeEntry>(id);var mailboxes=await store.List<Mailbox>(id);var users=await store.List<StaffUser>(id);
|
||||
return Results.Ok(new {preview,steps=new[]{
|
||||
new {title="Check your hotel details",detail="Review the hotel name, timezone and email signature.",path="/settings",complete=hotel!=null&&hotel.Name.Length>=2&&hotel.Signature.Length>0,optional=false},
|
||||
new {title="Approve your guest answers",detail="Add current check-in, parking and breakfast information.",path="/knowledge",complete=knowledge.Any(x=>x.Approved),optional=false},
|
||||
new {title="Connect the hotel mailbox",detail="Connect Google and check that guest messages appear in the inbox.",path="/settings",complete=mailboxes.Any(x=>x.Status=="Connected"&&x.LastSyncAt!=null),optional=false},
|
||||
new {title="Invite your team",detail="Give each colleague their own account. Owners keep control of integrations and automation.",path="/team",complete=users.Any(x=>x.Role=="Staff"&&x.Active),optional=true},
|
||||
new {title="Test FAQ automation",detail="Review test results before enabling live replies. This checklist does not enable sending.",path="/automation",complete=hotel?.AutoReplyMode=="Test"||hotel?.AutoReplyMode=="Live",optional=true}
|
||||
}});
|
||||
}).RequireAuthorization("Owner");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user