using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// A new company user.
/// The sign-in name.
/// The name shown.
/// The e-mail address.
/// A person or a technical user for the API.
/// The role codes.
/// The per-user flags.
public sealed record NewCompanyUser(string UserName, string DisplayName, string? Email, UserKind Kind, IReadOnlyList Roles, UserFlags Flags);
///
/// Company users (users, SPEC ยง7.1): created by instance accounts or by company users holding
/// company.users.manage, who can never give roles above their own permissions.
///
public sealed class UserService(IUnitOfWorkFactory factory, AccountSecurity security, PermissionService permissions, RoleService roles, ISecurityAuditLog audit)
{
/// Lists the users of a company.
/// The company.
/// Cancellation.
/// The users by name.
public async Task> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository().ListAsync(Query.For().OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false)).Items;
}
/// Finds a user by sign-in name.
/// The company.
/// The name, in any case.
/// Cancellation.
/// The user, or .
public async Task FindByNameAsync(string companyCode, string userName, CancellationToken cancellationToken = default)
{
if (!UserNames.IsValid(userName))
{
return null;
}
var name = UserNames.Normalize(userName);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository().FindAsync(Query.For().Where(u => u.UserName == name), cancellationToken).ConfigureAwait(false);
}
/// Finds a user.
/// The company.
/// The identifier.
/// Cancellation.
/// The user, or .
public async Task GetAsync(string companyCode, long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// Creates a user with a temporary password (people) or none (technical users).
/// Who acts.
/// The company.
/// The user.
/// Cancellation.
/// The user and its temporary password ( for technical users).
public async Task<(CompanyUser User, string? TemporaryPassword)> CreateAsync(
Actor actor, string companyCode, NewCompanyUser request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
var user = new CompanyUser
{
UserName = UserNames.Normalize(request.UserName),
DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.UserName.Trim() : request.DisplayName.Trim(),
Email = string.IsNullOrWhiteSpace(request.Email) ? null : request.Email.Trim(),
Kind = request.Kind,
IsActive = true,
OwnCustomersOnly = request.Flags.OwnCustomersOnly,
CanSeeCosts = request.Flags.CanSeeCosts,
CanExport = request.Flags.CanExport,
CanUseApi = request.Kind == UserKind.Technical || request.Flags.CanUseApi,
TotpRequired = security.Options.TotpRequiredForUsers,
};
var password = request.Kind == UserKind.Human ? security.IssueTemporaryPassword(user) : null;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["user_name_taken"]);
}
user.Id = await users.InsertAsync(user, ct).ConfigureAwait(false);
await AssignRolesAsync(unitOfWork, actor, user.Id, request.Roles, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.created", actor.UserName, companyCode, user.UserName, new { roles = request.Roles, kind = request.Kind.ToString() }), cancellationToken)
.ConfigureAwait(false);
return (user, password);
}
/// Replaces the roles of a user.
/// Who acts.
/// The company.
/// The user.
/// The role codes.
/// Cancellation.
/// A task.
public async Task SetRolesAsync(Actor actor, string companyCode, long userId, IReadOnlyList roleCodes, CancellationToken cancellationToken = default)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => AssignRolesAsync(unitOfWork, actor, userId, roleCodes, ct), cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.roles-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), new { roles = roleCodes }), cancellationToken)
.ConfigureAwait(false);
}
/// Grants or denies single permissions to a user over its roles. Denials win.
/// Who acts.
/// The company.
/// The user.
/// Permission code and whether it is allowed.
/// Cancellation.
/// A task.
public async Task SetOverridesAsync(Actor actor, string companyCode, long userId, IReadOnlyDictionary overrides, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(overrides);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
if (!await permissions.CoversAsync(actor, overrides.Where(o => o.Value).Select(o => o.Key), cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot grant permissions it does not hold.");
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var old in (await repository.ListAsync(Query.For().Where(o => o.UserId == userId), ct).ConfigureAwait(false)).Items)
{
await repository.DeleteAsync(old.Id, ct).ConfigureAwait(false);
}
foreach (var (code, allowed) in overrides)
{
await repository.InsertAsync(new UserPermissionOverride { UserId = userId, Permission = code, Allowed = allowed }, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.overrides-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), overrides), cancellationToken)
.ConfigureAwait(false);
}
/// Changes name, e-mail, flags and state of a user.
/// Who acts.
/// The company.
/// The user.
/// The name.
/// The e-mail.
/// The flags.
/// Whether it can sign in.
/// Cancellation.
/// A task.
public async Task UpdateAsync(
Actor actor, string companyCode, long userId, string displayName, string? email, UserFlags flags, bool isActive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(flags);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
await ChangeAsync(actor, companyCode, userId, "user.updated", user =>
{
user.DisplayName = displayName.Trim();
user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
user.OwnCustomersOnly = flags.OwnCustomersOnly;
user.CanSeeCosts = flags.CanSeeCosts;
user.CanExport = flags.CanExport;
user.CanUseApi = user.Kind == UserKind.Technical || flags.CanUseApi;
user.IsActive = isActive;
}, cancellationToken).ConfigureAwait(false);
}
/// Gives a user a new temporary password.
/// Who acts.
/// The company.
/// The user.
/// Cancellation.
/// The temporary password.
public async Task ResetPasswordAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default)
{
string? password = null;
await ChangeAsync(actor, companyCode, userId, "user.password-reset", user =>
{
if (user.Kind == UserKind.Technical)
{
throw new ValidationFailedException(["technical_user_has_no_password"]);
}
password = security.IssueTemporaryPassword(user);
}, cancellationToken).ConfigureAwait(false);
return password!;
}
/// Turns off the two-step verification of a user who lost the phone.
/// Who acts.
/// The company.
/// The user.
/// Cancellation.
/// A task.
public Task ResetTotpAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, companyCode, userId, "user.totp-reset", AccountSecurity.ResetTotp, cancellationToken);
/// Saves a user changed by the sign-in flow.
/// The company.
/// The user.
/// Cancellation.
/// A task.
public async Task SaveAsync(string companyCode, CompanyUser user, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(user);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private async Task ChangeAsync(Actor actor, string companyCode, long userId, string action, Action change, CancellationToken cancellationToken)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository();
var user = await users.GetAsync(userId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No user has this identifier.");
change(user);
await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent(action, actor.UserName, companyCode, user.UserName), cancellationToken).ConfigureAwait(false);
}
private async Task AssignRolesAsync(IUnitOfWork unitOfWork, Actor actor, long userId, IReadOnlyList roleCodes, CancellationToken cancellationToken)
{
var codes = roleCodes.Select(r => r.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).ToArray();
var found = codes.Length == 0
? []
: (await unitOfWork.Repository().ListAsync(Query.For().Where(r => codes.Contains(r.Code)), cancellationToken).ConfigureAwait(false)).Items;
if (found.Count != codes.Length)
{
throw new ValidationFailedException(["role_unknown"]);
}
var roleIds = found.Select(r => r.Id).ToArray();
var patterns = roleIds.Length == 0
? []
: (await unitOfWork.Repository().ListAsync(Query.For().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission);
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot assign roles above its own permissions.");
}
var userRoles = unitOfWork.Repository();
foreach (var old in (await userRoles.ListAsync(Query.For().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items)
{
await userRoles.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var roleId in roleIds)
{
await userRoles.InsertAsync(new UserRole { UserId = userId, RoleId = roleId }, cancellationToken).ConfigureAwait(false);
}
}
}