House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- Services, controllers and jobs take their dependencies through primary constructors and use them directly; where a method already named a local after a dependency, the dependency takes its type's name. - Every async method takes a CancellationToken last and passes it down to MongoDB, HTTP and the job queue. The setup claim is still given back when a request is cancelled. - The federation and media options are read through IOptionsMonitor. - The Mastodon entities keep sending "" for empty strings, and every model field where null means something says so. - The inbox's 503 with Retry-After, which other servers retry, is the one server error left, and says why. - Arasaka.HouseRules.Analyzers checks all of this in every build, here and in PrivaPub.ClientModels as decePubClient builds it. Checked against GoToSocial in the pasture: 64 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -6,14 +6,11 @@ namespace PrivaPub.Services
|
||||
{
|
||||
// The configuration as appsettings has it now. Builds before 2026-10-17 copied it into Mongo on first boot and read that
|
||||
// copy forever after, so a changed SMTP account or language list never took; the copy is no longer read.
|
||||
public class AppConfigurationService
|
||||
public class AppConfigurationService(
|
||||
IOptionsMonitor<AppConfiguration> appConfiguration)
|
||||
{
|
||||
readonly IOptionsMonitor<AppConfiguration> _appConfiguration;
|
||||
public AppConfiguration AppConfiguration => appConfiguration.CurrentValue;
|
||||
|
||||
public AppConfigurationService(IOptionsMonitor<AppConfiguration> appConfiguration) => _appConfiguration = appConfiguration;
|
||||
|
||||
public AppConfiguration AppConfiguration => _appConfiguration.CurrentValue;
|
||||
|
||||
public Task Init() => Task.CompletedTask;
|
||||
public Task Init(CancellationToken token = default) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -16,46 +16,32 @@ namespace PrivaPub.Services.ClientToServer.Private
|
||||
{
|
||||
public interface IPrivateAvatarUsersService
|
||||
{
|
||||
Task<WebResult> UpdateAvatar(UpdateAvatarForm form);
|
||||
Task<WebResult> InsertAvatar(InsertAvatarForm form);
|
||||
Task<WebResult> UpdateAvatar(UpdateAvatarForm form, CancellationToken token = default);
|
||||
Task<WebResult> InsertAvatar(InsertAvatarForm form, CancellationToken token = default);
|
||||
Task<WebResult> GetRootAvatars(string rootUserId, CancellationToken token);
|
||||
}
|
||||
|
||||
public class PrivateAvatarUsersService : IPrivateAvatarUsersService
|
||||
public class PrivateAvatarUsersService(
|
||||
ILocalActorService localActors,
|
||||
IOutboxPublisher outbox,
|
||||
DbEntities dbEntities,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PrivateAvatarUsersService> logger) : IPrivateAvatarUsersService
|
||||
{
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IOutboxPublisher _outbox;
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<PrivateAvatarUsersService> _logger;
|
||||
|
||||
public PrivateAvatarUsersService(ILocalActorService localActors,
|
||||
IOutboxPublisher outbox,
|
||||
DbEntities dbEntities,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PrivateAvatarUsersService> logger)
|
||||
{
|
||||
_localActors = localActors;
|
||||
_outbox = outbox;
|
||||
_dbEntities = dbEntities;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<WebResult> InsertAvatar(InsertAvatarForm form)
|
||||
public async Task<WebResult> InsertAvatar(InsertAvatarForm form, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var userName = form.UserName?.Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrEmpty(userName) || !userName.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'))
|
||||
return result.Invalidate(_localizer["The username may contain only letters, digits and underscores."]);
|
||||
return result.Invalidate(localizer["The username may contain only letters, digits and underscores."]);
|
||||
|
||||
if (await _localActors.IsUserNameTaken(userName, default))
|
||||
return result.Invalidate(_localizer["The username '{0}' is already taken.", userName]);
|
||||
if (await localActors.IsUserNameTaken(userName, default))
|
||||
return result.Invalidate(localizer["The username '{0}' is already taken.", userName]);
|
||||
|
||||
if (!await IsValidRootUser(form.RootId))
|
||||
return result.Invalidate(_localizer["You can't do this action because of your account status."]);
|
||||
if (!await IsValidRootUser(form.RootId, token))
|
||||
return result.Invalidate(localizer["You can't do this action because of your account status."]);
|
||||
|
||||
var (privateKey, publicKey) = Keys.NewKeyPair();
|
||||
var newAvatar = new Avatar
|
||||
@@ -68,53 +54,53 @@ namespace PrivaPub.Services.ClientToServer.Private
|
||||
PrivateKey = privateKey,
|
||||
PublicKey = publicKey,
|
||||
SigningKey = Federation.Signing.IntegrityProofs.NewSeed(),
|
||||
Domain = _localActors.BaseAddress
|
||||
Domain = localActors.BaseAddress
|
||||
};
|
||||
newAvatar.Emojis = PrivaPub.Domain.Content.LocalEmojis.OfProfile(newAvatar);
|
||||
newAvatar.ID = (string)newAvatar.GenerateNewID();
|
||||
if (!await _localActors.TryReserveUserName(userName, LocalActorKind.Person, newAvatar.ID, default))
|
||||
return result.Invalidate(_localizer["The username '{0}' is already taken.", userName]);
|
||||
if (!await localActors.TryReserveUserName(userName, LocalActorKind.Person, newAvatar.ID, default))
|
||||
return result.Invalidate(localizer["The username '{0}' is already taken.", userName]);
|
||||
if (form.Settings is { IsDefault: false })
|
||||
Apply(newAvatar.Settings, form.Settings);
|
||||
|
||||
var actor = _localActors.FromAvatar(newAvatar);
|
||||
var actor = localActors.FromAvatar(newAvatar);
|
||||
newAvatar.Url = actor.Uri;
|
||||
newAvatar.InboxURL = actor.Inbox;
|
||||
newAvatar.OutboxURL = actor.Outbox;
|
||||
|
||||
await DB.Default.SaveAsync(newAvatar);
|
||||
await DB.Default.SaveAsync(new RootToAvatar { RootId = form.RootId, AvatarId = newAvatar.ID });
|
||||
await DB.Default.SaveAsync(newAvatar, token);
|
||||
await DB.Default.SaveAsync(new RootToAvatar { RootId = form.RootId, AvatarId = newAvatar.ID }, token);
|
||||
|
||||
result.Data = ToView(newAvatar);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(InsertAvatar)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(InsertAvatar)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> UpdateAvatar(UpdateAvatarForm form)
|
||||
public async Task<WebResult> UpdateAvatar(UpdateAvatarForm form, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
if (!await IsValidRootUser(form.RootId))
|
||||
return result.Invalidate(_localizer["You can't do this action because of your account status."]);
|
||||
if (!await IsValidRootUser(form.RootId, token))
|
||||
return result.Invalidate(localizer["You can't do this action because of your account status."]);
|
||||
|
||||
var owns = await _dbEntities.RootToAvatars
|
||||
var owns = await dbEntities.RootToAvatars
|
||||
.Match(ra => ra.RootId == form.RootId && ra.AvatarId == form.AvatarId)
|
||||
.ExecuteAnyAsync();
|
||||
.ExecuteAnyAsync(token);
|
||||
if (!owns)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var avatar = await _dbEntities.Avatars.MatchID(form.AvatarId).ExecuteFirstAsync();
|
||||
var avatar = await dbEntities.Avatars.MatchID(form.AvatarId).ExecuteFirstAsync(token);
|
||||
if (avatar == default || avatar.DeletionAt.HasValue)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
// a suspended persona's actor stays as it was until the suspension is lifted (R6)
|
||||
if (avatar.SuspendedAt.HasValue)
|
||||
return result.Invalidate(_localizer["This persona is suspended."], StatusCodes.Status403Forbidden);
|
||||
return result.Invalidate(localizer["This persona is suspended."], StatusCodes.Status403Forbidden);
|
||||
|
||||
avatar.Name = form.Name;
|
||||
avatar.Biography = form.Biography;
|
||||
@@ -124,16 +110,16 @@ namespace PrivaPub.Services.ClientToServer.Private
|
||||
if (form.Settings != default)
|
||||
Apply(avatar.Settings ??= new(), form.Settings);
|
||||
avatar.UpdatedAt = DateTime.UtcNow;
|
||||
await DB.Default.SaveAsync(avatar);
|
||||
await _outbox.PublishProfile(_localActors.FromAvatar(avatar), default);
|
||||
await DB.Default.SaveAsync(avatar, token);
|
||||
await outbox.PublishProfile(localActors.FromAvatar(avatar), default);
|
||||
|
||||
result.Data = ToView(avatar);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(UpdateAvatar)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(UpdateAvatar)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,27 +128,27 @@ namespace PrivaPub.Services.ClientToServer.Private
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var avatarIds = (await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId).ExecuteAsync(token))
|
||||
var avatarIds = (await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId).ExecuteAsync(token))
|
||||
.Select(ra => ra.AvatarId)
|
||||
.ToList();
|
||||
var avatars = avatarIds.Count == 0
|
||||
? new List<Avatar>()
|
||||
: await _dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token);
|
||||
: await dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token);
|
||||
result.Data = avatars.Select(ToView).ToList();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(GetRootAvatars)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(GetRootAvatars)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
async ValueTask<bool> IsValidRootUser(string rootUserId) =>
|
||||
async ValueTask<bool> IsValidRootUser(string rootUserId, CancellationToken token = default) =>
|
||||
!string.IsNullOrEmpty(rootUserId)
|
||||
&& await _dbEntities.RootUsers.MatchID(rootUserId)
|
||||
&& await dbEntities.RootUsers.MatchID(rootUserId)
|
||||
.Match(ru => !ru.DeletedAt.HasValue && !ru.IsBanned)
|
||||
.ExecuteAnyAsync();
|
||||
.ExecuteAnyAsync(token);
|
||||
|
||||
// The client API carries only the theme; the rest (discoverable, locked, quote policy…) is set through the Mastodon API
|
||||
// and must survive an edit made here.
|
||||
@@ -183,7 +169,7 @@ namespace PrivaPub.Services.ClientToServer.Private
|
||||
{
|
||||
Id = avatar.ID,
|
||||
Url = avatar.Url,
|
||||
Handle = _localActors.FromAvatar(avatar).Handle,
|
||||
Handle = localActors.FromAvatar(avatar).Handle,
|
||||
Name = avatar.Name,
|
||||
UserName = avatar.UserName,
|
||||
Biography = avatar.Biography,
|
||||
|
||||
@@ -3,25 +3,18 @@ using PrivaPub.StaticServices;
|
||||
|
||||
namespace PrivaPub.Services.ClientToServer.Public
|
||||
{
|
||||
public class DataService : IDataService
|
||||
public class DataService(
|
||||
DbEntities dbCollections,
|
||||
AppConfigurationService appConfigurationService) : IDataService
|
||||
{
|
||||
readonly DbEntities DbEntities;
|
||||
readonly AppConfigurationService AppConfigurationService;
|
||||
|
||||
public DataService(DbEntities dbCollections, AppConfigurationService appConfigurationService)
|
||||
{
|
||||
DbEntities = dbCollections;
|
||||
AppConfigurationService = appConfigurationService;
|
||||
}
|
||||
|
||||
// the build's ref (its tag, or the branch a manual deploy ran from), as /build.json and NodeInfo name it
|
||||
public string GetCurrentVersion() =>
|
||||
string.IsNullOrEmpty(BuildInfo.Ref) ? BuildInfo.Commit : BuildInfo.Ref;
|
||||
|
||||
public async Task<IEnumerable<Language>> GetLanguages(CancellationToken cancellationToken)
|
||||
{
|
||||
return (await DbEntities.Languages
|
||||
.Match(l => AppConfigurationService.AppConfiguration.SupportedLanguages.Contains(l.International2Code))
|
||||
return (await dbCollections.Languages
|
||||
.Match(l => appConfigurationService.AppConfiguration.SupportedLanguages.Contains(l.International2Code))
|
||||
.ExecuteAsync(cancellationToken)).OrderBy(l => l.NativeName).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,26 +17,20 @@ namespace PrivaPub.Services
|
||||
// Sends the code that proves a login owns the address it asked for. The code exists only in the email; the row keeps its
|
||||
// hash. An address another login has verified meanwhile gets nothing, so the answer to the request never told whether
|
||||
// the address was taken, and no stranger's inbox receives a code it didn't ask for twice.
|
||||
public class EmailVerificationJob : IJobHandler
|
||||
public class EmailVerificationJob(
|
||||
IMailer mailer,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<EmailVerificationJob> logger) : IJobHandler
|
||||
{
|
||||
public const string Host = "email";
|
||||
|
||||
readonly IMailer _mailer;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<EmailVerificationJob> _logger;
|
||||
|
||||
public EmailVerificationJob(IMailer mailer, IStringLocalizer<GenericRes> localizer, ILogger<EmailVerificationJob> logger)
|
||||
{
|
||||
_mailer = mailer;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public JobKind Kind => JobKind.SendEmailVerification;
|
||||
public int Concurrency => 1;
|
||||
public int MaxAttempts => 3;
|
||||
public int PerHostLimit => 1;
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0011", Justification = "A six-digit code with its leading zeros, not a number shown to a reader.")]
|
||||
public static string NewCode() => RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6");
|
||||
|
||||
public async Task<JobOutcome> Handle(Job job, CancellationToken token)
|
||||
@@ -57,15 +51,15 @@ namespace PrivaPub.Services
|
||||
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(v => v.CodeHash, RecoveryJob.Hash(code)).ExecuteAsync(token);
|
||||
try
|
||||
{
|
||||
await _mailer.Send(pending.Email, _localizer["PrivaPub - Confirm your email address"],
|
||||
string.Format(_localizer[
|
||||
await mailer.Send(pending.Email, localizer["PrivaPub - Confirm your email address"],
|
||||
string.Format(localizer[
|
||||
"Hello,\n\nThe PrivaPub login {0} asked to use this address. If it was you, enter this code within an hour:\n\n{1}\n\nIf it was not you, ignore this email: the address is not used."],
|
||||
user.UserName, code), token);
|
||||
return JobOutcome.Done;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex, "The verification email could not be sent");
|
||||
logger.LogWarning(ex, "The verification email could not be sent");
|
||||
return JobOutcome.Retry("smtp");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,42 +30,24 @@ namespace PrivaPub.Services
|
||||
Task<WebResult> GetInvitation(string invitationCode, string invitationPassword, CancellationToken token);
|
||||
}
|
||||
|
||||
public class GroupUsersService : IGroupUsersService
|
||||
public class GroupUsersService(
|
||||
DbEntities dbEntities,
|
||||
IPasswordHasher passwordHasher,
|
||||
ILocalActorService localActors,
|
||||
IDeliveryService delivery,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<GroupUsersService> logger,
|
||||
Domain.Media.IMediaProxy mediaProxy) : IGroupUsersService
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IPasswordHasher _passwordHasher;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IDeliveryService _delivery;
|
||||
readonly Domain.Media.IMediaProxy _proxy;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<GroupUsersService> _logger;
|
||||
|
||||
public GroupUsersService(DbEntities dbEntities,
|
||||
IPasswordHasher passwordHasher,
|
||||
ILocalActorService localActors,
|
||||
IDeliveryService delivery,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<GroupUsersService> logger,
|
||||
Domain.Media.IMediaProxy proxy)
|
||||
{
|
||||
_proxy = proxy;
|
||||
_dbEntities = dbEntities;
|
||||
_passwordHasher = passwordHasher;
|
||||
_localActors = localActors;
|
||||
_delivery = delivery;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<WebResult> GetGroups(string rootUserId, string avatarId, CancellationToken token)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
if (!await OwnsAvatar(rootUserId, avatarId, token))
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var groups = await _dbEntities.Groups
|
||||
var groups = await dbEntities.Groups
|
||||
.Match(g => !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == avatarId))
|
||||
.ExecuteAsync(token);
|
||||
result.Data = groups.Select(g => ToView(g, avatarId)).ToList();
|
||||
@@ -73,8 +55,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetGroups)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetGroups)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,11 +66,11 @@ namespace PrivaPub.Services
|
||||
try
|
||||
{
|
||||
if (!await OwnsAvatar(rootUserId, form.AvatarId, token))
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var userName = form.UserName.ToLowerInvariant();
|
||||
if (await _localActors.IsUserNameTaken(userName, token))
|
||||
return result.Invalidate(_localizer["The username '{0}' is already taken.", userName]);
|
||||
if (await localActors.IsUserNameTaken(userName, token))
|
||||
return result.Invalidate(localizer["The username '{0}' is already taken.", userName]);
|
||||
|
||||
var (privateKey, publicKey) = Keys.NewKeyPair();
|
||||
var group = new GroupEntity
|
||||
@@ -96,7 +78,7 @@ namespace PrivaPub.Services
|
||||
UserName = userName,
|
||||
Name = form.Name,
|
||||
Description = form.Description,
|
||||
Domain = _localActors.BaseAddress,
|
||||
Domain = localActors.BaseAddress,
|
||||
PrivateKey = privateKey,
|
||||
PublicKey = publicKey,
|
||||
Kind = form.IsCommunity ? GroupKind.Community : GroupKind.Circle,
|
||||
@@ -105,13 +87,13 @@ namespace PrivaPub.Services
|
||||
ManuallyApprovesMembers = form.ManuallyApprovesMembers,
|
||||
OwnerAvatarId = form.AvatarId,
|
||||
InvitationCode = NewInvitationCode(),
|
||||
HashedInvitationPassword = string.IsNullOrEmpty(form.InvitationPassword) ? default : _passwordHasher.Hash(form.InvitationPassword),
|
||||
HashedInvitationPassword = string.IsNullOrEmpty(form.InvitationPassword) ? default : passwordHasher.Hash(form.InvitationPassword),
|
||||
Members = new() { new GroupMember { AvatarId = form.AvatarId, Role = GroupRole.Owner } }
|
||||
};
|
||||
group.ID = (string)group.GenerateNewID();
|
||||
if (!await _localActors.TryReserveUserName(userName, LocalActorKind.Group, group.ID, token))
|
||||
return result.Invalidate(_localizer["The username '{0}' is already taken.", userName]);
|
||||
var actor = _localActors.FromGroup(group);
|
||||
if (!await localActors.TryReserveUserName(userName, LocalActorKind.Group, group.ID, token))
|
||||
return result.Invalidate(localizer["The username '{0}' is already taken.", userName]);
|
||||
var actor = localActors.FromGroup(group);
|
||||
group.Url = actor.Uri;
|
||||
group.InboxURL = actor.Inbox;
|
||||
group.OutboxURL = actor.Outbox;
|
||||
@@ -122,8 +104,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(InsertGroup)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(InsertGroup)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +116,7 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var group = await ManagedGroup(rootUserId, form.AvatarId, form.GroupId, token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
if (form.Name != default)
|
||||
group.Name = form.Name;
|
||||
@@ -149,7 +131,7 @@ namespace PrivaPub.Services
|
||||
if (form.RemoveInvitationPassword)
|
||||
group.HashedInvitationPassword = default;
|
||||
else if (!string.IsNullOrEmpty(form.InvitationPassword))
|
||||
group.HashedInvitationPassword = _passwordHasher.Hash(form.InvitationPassword);
|
||||
group.HashedInvitationPassword = passwordHasher.Hash(form.InvitationPassword);
|
||||
if (form.RegenerateInvitationCode)
|
||||
group.InvitationCode = NewInvitationCode();
|
||||
group.UpdatedAt = DateTime.UtcNow;
|
||||
@@ -160,8 +142,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(UpdateGroup)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(UpdateGroup)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,21 +153,21 @@ namespace PrivaPub.Services
|
||||
try
|
||||
{
|
||||
if (!await OwnsAvatar(rootUserId, form.AvatarId, token))
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var group = await _dbEntities.Groups
|
||||
var group = await dbEntities.Groups
|
||||
.Match(g => g.InvitationCode == form.InvitationCode && !g.DeletionAt.HasValue)
|
||||
.ExecuteFirstAsync(token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Invalid invitation."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Invalid invitation."], StatusCodes.Status404NotFound);
|
||||
|
||||
if (!string.IsNullOrEmpty(group.HashedInvitationPassword))
|
||||
{
|
||||
var (verified, _) = string.IsNullOrEmpty(form.InvitationPassword)
|
||||
? (false, false)
|
||||
: _passwordHasher.Check(group.HashedInvitationPassword, form.InvitationPassword);
|
||||
: passwordHasher.Check(group.HashedInvitationPassword, form.InvitationPassword);
|
||||
if (!verified)
|
||||
return result.Invalidate(_localizer["Invalid password."], StatusCodes.Status406NotAcceptable);
|
||||
return result.Invalidate(localizer["Invalid password."], StatusCodes.Status406NotAcceptable);
|
||||
}
|
||||
|
||||
if (!group.Members.Any(m => !m.IsForeign && m.AvatarId == form.AvatarId))
|
||||
@@ -201,8 +183,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(JoinGroup)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(JoinGroup)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,8 +192,8 @@ namespace PrivaPub.Services
|
||||
// followers (so /groupies and /flock agree) and gets its posts in the home timeline.
|
||||
async Task FollowAsMember(GroupEntity group, string avatarId, CancellationToken token)
|
||||
{
|
||||
var persona = await _localActors.FindById(LocalActorKind.Person, avatarId, token);
|
||||
var target = _localActors.FromGroup(group);
|
||||
var persona = await localActors.FindById(LocalActorKind.Person, avatarId, token);
|
||||
var target = localActors.FromGroup(group);
|
||||
if (persona == default)
|
||||
return;
|
||||
await DB.Default.Update<Follower>()
|
||||
@@ -239,20 +221,20 @@ namespace PrivaPub.Services
|
||||
try
|
||||
{
|
||||
if (!await OwnsAvatar(rootUserId, form.AvatarId, token))
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var group = await _dbEntities.Groups.MatchID(form.GroupId).ExecuteFirstAsync(token);
|
||||
var group = await dbEntities.Groups.MatchID(form.GroupId).ExecuteFirstAsync(token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
if (group.OwnerAvatarId == form.AvatarId)
|
||||
return result.Invalidate(_localizer["The owner cannot leave the group."]);
|
||||
return result.Invalidate(localizer["The owner cannot leave the group."]);
|
||||
|
||||
group.Members.RemoveAll(m => !m.IsForeign && m.AvatarId == form.AvatarId);
|
||||
group.UpdatedAt = DateTime.UtcNow;
|
||||
await DB.Default.SaveAsync(group, token);
|
||||
// leaving is unfollowing, as joining was following
|
||||
var groupUri = _localActors.FromGroup(group).Uri;
|
||||
var personaUri = (await _localActors.FindById(LocalActorKind.Person, form.AvatarId, token))?.Uri;
|
||||
var groupUri = localActors.FromGroup(group).Uri;
|
||||
var personaUri = (await localActors.FindById(LocalActorKind.Person, form.AvatarId, token))?.Uri;
|
||||
await DB.Default.DeleteAsync<Models.Social.Following>(f => f.AvatarId == form.AvatarId && f.TargetActorURI == groupUri);
|
||||
if (personaUri != default)
|
||||
await DB.Default.DeleteAsync<Follower>(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group && f.ActorURI == personaUri);
|
||||
@@ -260,8 +242,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(LeaveGroup)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(LeaveGroup)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,13 +254,13 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var group = await ManagedGroup(rootUserId, form.AvatarId, form.GroupId, token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var follower = await _dbEntities.Followers
|
||||
var follower = await dbEntities.Followers
|
||||
.Match(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group && f.ActorURI == form.MemberActorURI)
|
||||
.ExecuteFirstAsync(token);
|
||||
if (follower == default)
|
||||
return result.Invalidate(_localizer["Request not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Request not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
follower.IsAccepted = true;
|
||||
await DB.Default.SaveAsync(follower, token);
|
||||
@@ -288,7 +270,7 @@ namespace PrivaPub.Services
|
||||
await DB.Default.SaveAsync(group, token);
|
||||
}
|
||||
|
||||
var actor = _localActors.FromGroup(group);
|
||||
var actor = localActors.FromGroup(group);
|
||||
var follow = new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
["id"] = follower.FollowActivityURI,
|
||||
@@ -297,13 +279,13 @@ namespace PrivaPub.Services
|
||||
["object"] = actor.Uri
|
||||
};
|
||||
var accept = ActivityPubRenderer.Accept(actor, follow, $"accept-{follower.ID}-{DateTime.UtcNow.Ticks}");
|
||||
await _delivery.Enqueue(actor, new[] { follower.InboxURL }, accept, token);
|
||||
await delivery.Enqueue(actor, new[] { follower.InboxURL }, accept, token: token);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(ApproveMember)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(ApproveMember)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,12 +294,12 @@ namespace PrivaPub.Services
|
||||
var result = new WebResult();
|
||||
var group = string.IsNullOrEmpty(invitationCode)
|
||||
? default
|
||||
: await _dbEntities.Groups.Match(g => g.InvitationCode == invitationCode && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
: await dbEntities.Groups.Match(g => g.InvitationCode == invitationCode && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Invalid invitation."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Invalid invitation."], StatusCodes.Status404NotFound);
|
||||
if (!string.IsNullOrEmpty(group.HashedInvitationPassword)
|
||||
&& (string.IsNullOrEmpty(invitationPassword) || !_passwordHasher.Check(group.HashedInvitationPassword, invitationPassword).verified))
|
||||
return result.Invalidate(_localizer["Invalid password."], StatusCodes.Status406NotAcceptable);
|
||||
&& (string.IsNullOrEmpty(invitationPassword) || !passwordHasher.Check(group.HashedInvitationPassword, invitationPassword).verified))
|
||||
return result.Invalidate(localizer["Invalid password."], StatusCodes.Status406NotAcceptable);
|
||||
result.Data = group;
|
||||
return result;
|
||||
}
|
||||
@@ -331,31 +313,31 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var group = await ManagedGroup(rootUserId, avatarId, groupId, token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var members = new List<ViewGroupMember>();
|
||||
foreach (var member in group.Members)
|
||||
{
|
||||
if (member.IsForeign)
|
||||
{
|
||||
var foreign = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == member.AvatarId).ExecuteFirstAsync(token);
|
||||
var foreign = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == member.AvatarId).ExecuteFirstAsync(token);
|
||||
members.Add(Remote(member.AvatarId, foreign, member.Role, member.JoinedAt, pending: false));
|
||||
continue;
|
||||
}
|
||||
if (await _localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } local)
|
||||
if (await localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } local)
|
||||
members.Add(new ViewGroupMember
|
||||
{
|
||||
ActorUri = local.Uri, Handle = local.Handle, Name = local.Name ?? local.UserName, PictureUrl = local.PictureURL,
|
||||
IsLocal = true, Role = member.Role.ToString().ToLowerInvariant(), Since = member.JoinedAt
|
||||
});
|
||||
}
|
||||
var asking = await _dbEntities.Followers
|
||||
var asking = await dbEntities.Followers
|
||||
.Match(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group && !f.IsAccepted)
|
||||
.Sort(f => f.CreationDate, Order.Ascending)
|
||||
.ExecuteAsync(token);
|
||||
foreach (var request in asking.Where(r => members.All(m => m.ActorUri != r.ActorURI)))
|
||||
{
|
||||
var foreign = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == request.ActorURI).ExecuteFirstAsync(token);
|
||||
var foreign = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == request.ActorURI).ExecuteFirstAsync(token);
|
||||
members.Add(Remote(request.ActorURI, foreign, GroupRole.Member, request.CreationDate, pending: true));
|
||||
}
|
||||
result.Data = members;
|
||||
@@ -363,8 +345,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetMembers)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetMembers)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,7 +356,7 @@ namespace PrivaPub.Services
|
||||
ActorUri = actorUri,
|
||||
Handle = foreign == default ? actorUri : $"{foreign.UserName}@{foreign.Domain}",
|
||||
Name = foreign?.Name ?? foreign?.UserName,
|
||||
PictureUrl = _proxy.Wrap(foreign?.PictureURL),
|
||||
PictureUrl = mediaProxy.Wrap(foreign?.PictureURL),
|
||||
IsPending = pending,
|
||||
Role = role.ToString().ToLowerInvariant(),
|
||||
Since = since
|
||||
@@ -388,20 +370,20 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var group = await ManagedGroup(rootUserId, form.AvatarId, form.GroupId, token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
var request = await _dbEntities.Followers
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
var request = await dbEntities.Followers
|
||||
.Match(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group && f.ActorURI == form.MemberActorURI && !f.IsAccepted)
|
||||
.ExecuteFirstAsync(token);
|
||||
if (request == default)
|
||||
return result.Invalidate(_localizer["Request not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Request not found."], StatusCodes.Status404NotFound);
|
||||
await DB.Default.DeleteAsync<Follower>(request.ID);
|
||||
await RejectFollow(group, request, token);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RejectMember)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RejectMember)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,27 +396,27 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var group = await ManagedGroup(rootUserId, form.AvatarId, form.GroupId, token);
|
||||
if (group == default)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
var localMember = await _localActors.FindByUri(form.MemberActorURI, token);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
var localMember = await localActors.FindByUri(form.MemberActorURI, token);
|
||||
var member = group.Members.FirstOrDefault(m => localMember is { Kind: LocalActorKind.Person }
|
||||
? !m.IsForeign && m.AvatarId == localMember.Id
|
||||
: m.IsForeign && m.AvatarId == form.MemberActorURI);
|
||||
if (member == default)
|
||||
return result.Invalidate(_localizer["Member not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Member not found."], StatusCodes.Status404NotFound);
|
||||
if (member.Role == GroupRole.Owner)
|
||||
return result.Invalidate(_localizer["The owner cannot leave the group."]);
|
||||
return result.Invalidate(localizer["The owner cannot leave the group."]);
|
||||
|
||||
group.Members.Remove(member);
|
||||
group.UpdatedAt = DateTime.UtcNow;
|
||||
await DB.Default.SaveAsync(group, token);
|
||||
var follower = await _dbEntities.Followers
|
||||
var follower = await dbEntities.Followers
|
||||
.Match(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group && f.ActorURI == form.MemberActorURI)
|
||||
.ExecuteFirstAsync(token);
|
||||
if (follower != default)
|
||||
await DB.Default.DeleteAsync<Follower>(follower.ID);
|
||||
if (localMember is { Kind: LocalActorKind.Person })
|
||||
{
|
||||
var groupUri = _localActors.FromGroup(group).Uri;
|
||||
var groupUri = localActors.FromGroup(group).Uri;
|
||||
await DB.Default.DeleteAsync<Models.Social.Following>(f => f.AvatarId == localMember.Id && f.TargetActorURI == groupUri);
|
||||
}
|
||||
else if (follower != default)
|
||||
@@ -443,8 +425,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RemoveMember)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RemoveMember)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,7 +434,7 @@ namespace PrivaPub.Services
|
||||
{
|
||||
if (string.IsNullOrEmpty(follower.InboxURL))
|
||||
return;
|
||||
var actor = _localActors.FromGroup(group);
|
||||
var actor = localActors.FromGroup(group);
|
||||
var follow = new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
["id"] = follower.FollowActivityURI,
|
||||
@@ -462,14 +444,14 @@ namespace PrivaPub.Services
|
||||
};
|
||||
var reject = ActivityPubRenderer.Accept(actor, follow, $"reject-{follower.ID}-{DateTime.UtcNow.Ticks}");
|
||||
reject["type"] = "Reject";
|
||||
await _delivery.Enqueue(actor, new[] { follower.InboxURL }, reject, token);
|
||||
await delivery.Enqueue(actor, new[] { follower.InboxURL }, reject, token: token);
|
||||
}
|
||||
|
||||
async Task<GroupEntity> ManagedGroup(string rootUserId, string avatarId, string groupId, CancellationToken token)
|
||||
{
|
||||
if (!await OwnsAvatar(rootUserId, avatarId, token))
|
||||
return default;
|
||||
var group = await _dbEntities.Groups.MatchID(groupId).ExecuteFirstAsync(token);
|
||||
var group = await dbEntities.Groups.MatchID(groupId).ExecuteFirstAsync(token);
|
||||
if (group == default || group.DeletionAt.HasValue)
|
||||
return default;
|
||||
var role = group.Members.FirstOrDefault(m => !m.IsForeign && m.AvatarId == avatarId)?.Role;
|
||||
@@ -479,7 +461,7 @@ namespace PrivaPub.Services
|
||||
// a suspended persona does nothing in its groups (R6)
|
||||
async Task<bool> OwnsAvatar(string rootUserId, string avatarId, CancellationToken token) =>
|
||||
!string.IsNullOrEmpty(rootUserId) && !string.IsNullOrEmpty(avatarId) && !Domain.Moderation.Restrictions.IsSuspended(avatarId)
|
||||
&& await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token);
|
||||
&& await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token);
|
||||
|
||||
static PostingPolicy? Policy(string value) => value?.ToLowerInvariant() switch
|
||||
{
|
||||
@@ -493,7 +475,7 @@ namespace PrivaPub.Services
|
||||
|
||||
ViewGroup ToView(GroupEntity group, string avatarId)
|
||||
{
|
||||
var actor = _localActors.FromGroup(group);
|
||||
var actor = localActors.FromGroup(group);
|
||||
var isManager = group.Members.Any(m => !m.IsForeign && m.AvatarId == avatarId && m.Role is GroupRole.Owner or GroupRole.Moderator);
|
||||
return new ViewGroup
|
||||
{
|
||||
|
||||
@@ -7,44 +7,44 @@ namespace PrivaPub.Services
|
||||
{
|
||||
public interface IRootUsersService
|
||||
{
|
||||
Task<WebResult> LoginAsync(LoginForm loginForm);
|
||||
Task<WebResult> LoginAsync(LoginForm loginForm, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> SignUpAsync(LoginForm signUpForm);
|
||||
Task<WebResult> SignUpAsync(LoginForm signUpForm, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> BanUserAsync(UsersIds usersIds);
|
||||
Task<WebResult> BanUserAsync(UsersIds usersIds, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> UnbanUserAsync(UsersIds usersIds);
|
||||
Task<WebResult> UnbanUserAsync(UsersIds usersIds, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> RemoveUserAsync(UsersIds usersIds);
|
||||
Task<WebResult> RemoveSelfAsync(string rootId, string password);
|
||||
Task<WebResult> RemoveUserAsync(UsersIds usersIds, CancellationToken token = default);
|
||||
Task<WebResult> RemoveSelfAsync(string rootId, string password, CancellationToken token = default);
|
||||
|
||||
/// <summary>Whether a login's password is this one, after the same hashing whatever the answer.</summary>
|
||||
Task<bool> PasswordMatches(string rootId, string password);
|
||||
Task<bool> PasswordMatches(string rootId, string password, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId);
|
||||
Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default);
|
||||
Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId);
|
||||
Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host);
|
||||
Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> IsValidRecoveryCode(string recoveryCode);
|
||||
Task<WebResult> IsValidRecoveryCode(string recoveryCode, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm);
|
||||
Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> AccountAsync(string rootId);
|
||||
Task<WebResult> AccountAsync(string rootId, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form);
|
||||
Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> VerifyEmailAsync(string rootId, string code);
|
||||
Task<WebResult> VerifyEmailAsync(string rootId, string code, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> RemoveEmailAsync(string rootId, string password);
|
||||
Task<WebResult> RemoveEmailAsync(string rootId, string password, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> TotpSetupAsync(string rootId, string password);
|
||||
Task<WebResult> TotpSetupAsync(string rootId, string password, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> TotpEnableAsync(string rootId, string code);
|
||||
Task<WebResult> TotpEnableAsync(string rootId, string code, CancellationToken token = default);
|
||||
|
||||
Task<WebResult> TotpDisableAsync(string rootId, string password, string code);
|
||||
Task<WebResult> TotpDisableAsync(string rootId, string password, string code, CancellationToken token = default);
|
||||
}
|
||||
}
|
||||
@@ -16,22 +16,15 @@ namespace PrivaPub.Services
|
||||
|
||||
// The server's one way to send an email: through the SMTP account in appsettings (AppConfiguration:EmailConfiguration),
|
||||
// read as it is now. Only jobs call it, so nobody waits on SMTP.
|
||||
public class Mailer : IMailer
|
||||
public class Mailer(
|
||||
IOptionsMonitor<AppConfiguration> app,
|
||||
Domain.Instance.IInstanceSettings settings) : IMailer
|
||||
{
|
||||
readonly IOptionsMonitor<AppConfiguration> _app;
|
||||
readonly Domain.Instance.IInstanceSettings _settings;
|
||||
|
||||
public Mailer(IOptionsMonitor<AppConfiguration> app, Domain.Instance.IInstanceSettings settings)
|
||||
{
|
||||
_app = app;
|
||||
_settings = settings;
|
||||
}
|
||||
|
||||
public async Task Send(string to, string subject, string body, CancellationToken token)
|
||||
{
|
||||
var email = _app.CurrentValue.EmailConfiguration;
|
||||
var email = app.CurrentValue.EmailConfiguration;
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress(_settings.Current.Title, email.SmtpUsername));//the server's name, as its administrator set it
|
||||
message.From.Add(new MailboxAddress(settings.Current.Title, email.SmtpUsername));//the server's name, as its administrator set it
|
||||
message.To.Add(MailboxAddress.Parse(to));
|
||||
message.Subject = subject;
|
||||
message.Body = new TextPart("plain") { Text = body };
|
||||
|
||||
@@ -52,7 +52,7 @@ namespace PrivaPub.Services
|
||||
["object"] = actor.Uri,
|
||||
["to"] = new JsonArray(ActivityPubRenderer.Public),
|
||||
["cc"] = new JsonArray(actor.Followers)
|
||||
}, token);
|
||||
}, token: token);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,46 +64,33 @@ namespace PrivaPub.Services
|
||||
// announcements, the feeds it read, its featured hashtags, endorsements, notes and dismissed suggestions, its media)
|
||||
// goes with it. Its link to its login stays, so the login keeps no other
|
||||
// trace than that.
|
||||
public class PersonaRemoval : IPersonaRemoval
|
||||
public class PersonaRemoval(
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IDeliveryService delivery,
|
||||
IMediaService mediaService,
|
||||
IGroupRemoval groups,
|
||||
IOpenIddictTokenManager openIddictTokenManager,
|
||||
IOpenIddictAuthorizationManager authorizations) : IPersonaRemoval
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IDeliveryService _delivery;
|
||||
readonly IMediaService _media;
|
||||
readonly IGroupRemoval _groups;
|
||||
readonly IOpenIddictTokenManager _tokens;
|
||||
readonly IOpenIddictAuthorizationManager _authorizations;
|
||||
|
||||
public PersonaRemoval(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery, IMediaService media, IGroupRemoval groups,
|
||||
IOpenIddictTokenManager tokens, IOpenIddictAuthorizationManager authorizations)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
_delivery = delivery;
|
||||
_media = media;
|
||||
_groups = groups;
|
||||
_tokens = tokens;
|
||||
_authorizations = authorizations;
|
||||
}
|
||||
|
||||
public async Task<bool> Remove(string avatarId, CancellationToken token)
|
||||
{
|
||||
var avatar = string.IsNullOrEmpty(avatarId) ? default : await _dbEntities.Avatars.MatchID(avatarId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
var avatar = string.IsNullOrEmpty(avatarId) ? default : await dbEntities.Avatars.MatchID(avatarId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (avatar == default)
|
||||
return false;
|
||||
var now = DateTime.UtcNow;
|
||||
// nothing acts as it while it goes
|
||||
await _tokens.RevokeBySubjectAsync(avatar.ID, token);
|
||||
await _authorizations.RevokeBySubjectAsync(avatar.ID, token);
|
||||
await Domain.Social.WebPush.Forget(new[] { avatar.ID });//its Web Push subscriptions with its tokens (R9)
|
||||
await openIddictTokenManager.RevokeBySubjectAsync(avatar.ID, token);
|
||||
await authorizations.RevokeBySubjectAsync(avatar.ID, token);
|
||||
await Domain.Social.WebPush.Forget(new[] { avatar.ID }, token);//its Web Push subscriptions with its tokens (R9)
|
||||
Streams.CloseFor(avatar.ID);
|
||||
|
||||
foreach (var group in await _dbEntities.Groups.Match(g => g.OwnerAvatarId == avatar.ID && !g.DeletionAt.HasValue).ExecuteAsync(token))
|
||||
await _groups.Remove(group.ID, token);
|
||||
var persona = _localActors.FromAvatar(avatar);
|
||||
var followed = (await _dbEntities.Followings.Match(f => f.AvatarId == avatar.ID && !f.TargetIsLocal).ExecuteAsync(token))
|
||||
foreach (var group in await dbEntities.Groups.Match(g => g.OwnerAvatarId == avatar.ID && !g.DeletionAt.HasValue).ExecuteAsync(token))
|
||||
await groups.Remove(group.ID, token);
|
||||
var persona = localActors.FromAvatar(avatar);
|
||||
var followed = (await dbEntities.Followings.Match(f => f.AvatarId == avatar.ID && !f.TargetIsLocal).ExecuteAsync(token))
|
||||
.Select(f => f.TargetActorURI);
|
||||
await ActorDeletion.Announce(persona, followed, _dbEntities, _delivery, token);
|
||||
await ActorDeletion.Announce(persona, followed, dbEntities, delivery, token);
|
||||
await DB.Default.Update<Avatar>().MatchID(avatar.ID).Modify(a => a.DeletionAt, now).ExecuteAsync(token);
|
||||
await Empty(avatar.ID, now, token);
|
||||
await DB.Default.DeleteAsync<PersonaListMember>(m => m.AvatarId == avatar.ID);
|
||||
@@ -125,7 +112,7 @@ namespace PrivaPub.Services
|
||||
// nothing of it publishes later, and none of its files stays served: its posts' media, its pictures and what its
|
||||
// scheduled posts held
|
||||
await DB.Default.DeleteAsync<ScheduledStatus>(s => s.AvatarId == avatar.ID);
|
||||
await _media.Trash(m => m.OwnerAvatarId == avatar.ID, "persona removed", token);
|
||||
await mediaService.Trash(m => m.OwnerAvatarId == avatar.ID, "persona removed", token);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -153,26 +140,18 @@ namespace PrivaPub.Services
|
||||
// with the persona that owns it): a Delete of the group's actor to its followers and its members elsewhere, its name kept
|
||||
// reserved while its documents answer 410, and the personas here that followed or joined it no longer do. The posts made
|
||||
// in it stay their authors'.
|
||||
public class GroupRemoval : IGroupRemoval
|
||||
public class GroupRemoval(
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IDeliveryService delivery) : IGroupRemoval
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IDeliveryService _delivery;
|
||||
|
||||
public GroupRemoval(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
_delivery = delivery;
|
||||
}
|
||||
|
||||
public async Task<bool> Remove(string groupId, CancellationToken token)
|
||||
{
|
||||
var group = string.IsNullOrEmpty(groupId) ? default : await _dbEntities.Groups.MatchID(groupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
var group = string.IsNullOrEmpty(groupId) ? default : await dbEntities.Groups.MatchID(groupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (group == default)
|
||||
return false;
|
||||
var actor = _localActors.FromGroup(group);
|
||||
await ActorDeletion.Announce(actor, group.Members.Where(m => m.IsForeign).Select(m => m.AvatarId), _dbEntities, _delivery, token);
|
||||
var actor = localActors.FromGroup(group);
|
||||
await ActorDeletion.Announce(actor, group.Members.Where(m => m.IsForeign).Select(m => m.AvatarId), dbEntities, delivery, token);
|
||||
await DB.Default.Update<GroupEntity>().MatchID(group.ID).Modify(g => g.DeletionAt, DateTime.UtcNow).ExecuteAsync(token);
|
||||
await DB.Default.DeleteAsync<Following>(f => f.TargetActorURI == actor.Uri);
|
||||
await DB.Default.DeleteAsync<Follower>(f => f.LocalActorId == group.ID && f.LocalActorKind == LocalActorKind.Group);
|
||||
|
||||
@@ -35,35 +35,22 @@ namespace PrivaPub.Services
|
||||
Task<WebResult> GetDms(string rootUserId, string avatarId, string dmGroupId, CancellationToken token);
|
||||
}
|
||||
|
||||
public class PostsService : IPostsService
|
||||
public class PostsService(
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IStatusService statuses,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PostsService> logger) : IPostsService
|
||||
{
|
||||
const int PageSize = 50;
|
||||
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IStatusService _statuses;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<PostsService> _logger;
|
||||
|
||||
public PostsService(DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IStatusService statuses,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PostsService> logger)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
_statuses = statuses;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<WebResult> InsertPost(string rootUserId, InsertPostForm form, CancellationToken token)
|
||||
{
|
||||
var author = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (author == default)
|
||||
return new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return await Answer(() => _statuses.Publish(author, new StatusDraft
|
||||
return new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return await Answer(() => statuses.Publish(author, new StatusDraft
|
||||
{
|
||||
Text = form.Text,
|
||||
Title = form.Title,
|
||||
@@ -75,15 +62,15 @@ namespace PrivaPub.Services
|
||||
Latitude = form.Latitude,
|
||||
Longitude = form.Longitude,
|
||||
RangeKm = form.RangeKm
|
||||
}, token), nameof(InsertPost));
|
||||
}, token), nameof(InsertPost), token);
|
||||
}
|
||||
|
||||
public async Task<WebResult> DeletePost(string rootUserId, DeletePostForm form, CancellationToken token)
|
||||
{
|
||||
var author = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (author == default)
|
||||
return new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
var result = await Answer(() => _statuses.Remove(author, form.PostId, token), nameof(DeletePost));
|
||||
return new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
var result = await Answer(() => statuses.Remove(author, form.PostId, token), nameof(DeletePost), token);
|
||||
result.Data = default;
|
||||
return result;
|
||||
}
|
||||
@@ -92,14 +79,14 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var author = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (author == default)
|
||||
return new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return await Answer(() => _statuses.Edit(author, form.PostId, new StatusDraft
|
||||
return new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return await Answer(() => statuses.Edit(author, form.PostId, new StatusDraft
|
||||
{
|
||||
Text = form.Text,
|
||||
Title = form.Title,
|
||||
SpoilerText = form.SpoilerText,
|
||||
Sensitive = form.HasContentWarning
|
||||
}, token), nameof(UpdatePost));
|
||||
}, token), nameof(UpdatePost), token);
|
||||
}
|
||||
|
||||
public async Task<WebResult> GetPosts(string rootUserId, string avatarId, string groupId, CancellationToken token)
|
||||
@@ -109,18 +96,18 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var avatar = await OwnedAvatar(rootUserId, avatarId, token);
|
||||
if (avatar == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var query = _dbEntities.Posts;
|
||||
var query = dbEntities.Posts;
|
||||
if (string.IsNullOrEmpty(groupId))
|
||||
query.Match(p => p.GroupUserId == avatar.Id && p.Visibility != PostVisibility.Direct);
|
||||
else
|
||||
{
|
||||
var isMember = await _dbEntities.Groups
|
||||
var isMember = await dbEntities.Groups
|
||||
.Match(g => g.ID == groupId && g.Members.Any(m => !m.IsForeign && m.AvatarId == avatar.Id))
|
||||
.ExecuteAnyAsync(token);
|
||||
if (!isMember)
|
||||
return result.Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound);
|
||||
query.Match(p => p.GroupId == groupId);
|
||||
}
|
||||
|
||||
@@ -130,8 +117,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetPosts)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetPosts)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,17 +126,17 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var author = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (author == default)
|
||||
return new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
if (string.IsNullOrEmpty(form.DmGroupId) && form.Recipients.Count == 0)
|
||||
return new WebResult().Invalidate(_localizer["At least one recipient is required."]);
|
||||
return await Answer(() => _statuses.Publish(author, new StatusDraft
|
||||
return new WebResult().Invalidate(localizer["At least one recipient is required."]);
|
||||
return await Answer(() => statuses.Publish(author, new StatusDraft
|
||||
{
|
||||
Text = form.Text,
|
||||
Sensitive = form.HasContentWarning,
|
||||
Visibility = PostVisibility.Direct,
|
||||
ConversationId = form.DmGroupId,
|
||||
Recipients = form.Recipients
|
||||
}, token), nameof(InsertDm));
|
||||
}, token), nameof(InsertDm), token);
|
||||
}
|
||||
|
||||
public async Task<WebResult> GetDms(string rootUserId, string avatarId, string dmGroupId, CancellationToken token)
|
||||
@@ -159,11 +146,11 @@ namespace PrivaPub.Services
|
||||
{
|
||||
var avatar = await OwnedAvatar(rootUserId, avatarId, token);
|
||||
if (avatar == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
if (string.IsNullOrEmpty(dmGroupId))
|
||||
{
|
||||
var groups = await _dbEntities.DmGroups
|
||||
var groups = await dbEntities.DmGroups
|
||||
.Match(g => !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == avatar.Id))
|
||||
.Sort(g => g.UpdatedAt, Order.Descending)
|
||||
.ExecuteAsync(token);
|
||||
@@ -176,13 +163,13 @@ namespace PrivaPub.Services
|
||||
return result;
|
||||
}
|
||||
|
||||
var isMember = await _dbEntities.DmGroups
|
||||
var isMember = await dbEntities.DmGroups
|
||||
.Match(g => g.ID == dmGroupId && g.Members.Any(m => !m.IsForeign && m.AvatarId == avatar.Id))
|
||||
.ExecuteAnyAsync(token);
|
||||
if (!isMember)
|
||||
return result.Invalidate(_localizer["Conversation not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Conversation not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
var dms = await _dbEntities.Posts
|
||||
var dms = await dbEntities.Posts
|
||||
.Match(p => p.ConversationId == dmGroupId && p.Visibility == PostVisibility.Direct)
|
||||
.Match(VisibilityPolicy.IsShown)
|
||||
.Sort(p => p.CreationDate, Order.Descending)
|
||||
@@ -193,8 +180,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetDms)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetDms)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,9 +192,9 @@ namespace PrivaPub.Services
|
||||
var result = new WebResult();
|
||||
var viewer = await OwnedAvatar(rootUserId, avatarId, token);
|
||||
if (viewer == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
if (latitude is < -90 or > 90 || longitude is < -180 or > 180)
|
||||
return result.Invalidate(_localizer["Invalid model."]);
|
||||
return result.Invalidate(localizer["Invalid model."]);
|
||||
|
||||
var query = new MongoDB.Bson.BsonDocument
|
||||
{
|
||||
@@ -229,21 +216,21 @@ namespace PrivaPub.Services
|
||||
return result;
|
||||
}
|
||||
|
||||
async Task<WebResult> Answer(Func<Task<StatusOutcome>> action, string operation)
|
||||
async Task<WebResult> Answer(Func<Task<StatusOutcome>> action, string operation, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var outcome = await action();
|
||||
if (!outcome.Ok)
|
||||
return result.Invalidate(_localizer[outcome.Error], outcome.Status);
|
||||
return result.Invalidate(localizer[outcome.Error], outcome.Status);
|
||||
result.Data = ToView(outcome.Post);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "{Service}.{Operation}", nameof(PostsService), operation);
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, "{Service}.{Operation}", nameof(PostsService), operation);
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,10 +248,10 @@ namespace PrivaPub.Services
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootUserId) || string.IsNullOrEmpty(avatarId))
|
||||
return default;
|
||||
if (!await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
|
||||
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
|
||||
return default;
|
||||
// a suspended persona does nothing through the client API either (R6)
|
||||
return await _localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
|
||||
return await localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
|
||||
}
|
||||
|
||||
static ViewPost ToView(PostEntity post) => new()
|
||||
|
||||
@@ -18,21 +18,14 @@ namespace PrivaPub.Services
|
||||
// Sends a password recovery link. Every request queues one of these, for an account that exists or not, so the answer
|
||||
// to the request and its timing say nothing; SMTP's slowness and failures happen here, where nobody waits on them.
|
||||
// The code exists only in the email: the database keeps its hash, for an hour. Only a verified address is written to.
|
||||
public class RecoveryJob : IJobHandler
|
||||
public class RecoveryJob(
|
||||
IMailer mailer,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<RecoveryJob> logger) : IJobHandler
|
||||
{
|
||||
public const string Host = "recovery";
|
||||
public static readonly TimeSpan CodeLifetime = TimeSpan.FromHours(1);
|
||||
|
||||
readonly IMailer _mailer;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<RecoveryJob> _logger;
|
||||
|
||||
public RecoveryJob(IMailer mailer, IStringLocalizer<GenericRes> localizer, ILogger<RecoveryJob> logger)
|
||||
{
|
||||
_mailer = mailer;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public JobKind Kind => JobKind.SendRecovery;
|
||||
public int Concurrency => 1;
|
||||
@@ -55,15 +48,15 @@ namespace PrivaPub.Services
|
||||
await DB.Default.SaveAsync(new EmailRecovery { RootUserId = user.ID, CodeHash = Hash(code), ExpiresAt = DateTime.UtcNow + CodeLifetime }, token);
|
||||
try
|
||||
{
|
||||
await _mailer.Send(user.Email, _localizer["PrivaPub - Password recovery link"],
|
||||
string.Format(_localizer[
|
||||
await mailer.Send(user.Email, localizer["PrivaPub - Password recovery link"],
|
||||
string.Format(localizer[
|
||||
"Hello,\n\nSomeone asked to reset the password of the PrivaPub login {0}. If it was you, open this link within an hour:\n{1}\n\nIf it was not you, ignore this email: nothing changes."],
|
||||
user.UserName, $"{payload.Host}/password-recovery?rc={code}"), token);
|
||||
return JobOutcome.Done;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex, "The recovery email could not be sent");
|
||||
logger.LogWarning(ex, "The recovery email could not be sent");
|
||||
return JobOutcome.Retry("smtp");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,24 +6,19 @@ using System.Globalization;
|
||||
|
||||
namespace PrivaPub.Services
|
||||
{
|
||||
public class RequestLocalizationOptionsService
|
||||
public class RequestLocalizationOptionsService(
|
||||
AppConfigurationService appConfigurationService)
|
||||
{
|
||||
RequestLocalizationOptions RequestLocalizationOptions { get; set; }
|
||||
readonly AppConfigurationService AppConfigurationService;
|
||||
|
||||
public RequestLocalizationOptionsService(AppConfigurationService appConfigurationService)
|
||||
{
|
||||
AppConfigurationService = appConfigurationService;
|
||||
}
|
||||
|
||||
public async Task<RequestLocalizationOptions> Get()
|
||||
public async Task<RequestLocalizationOptions> Get(CancellationToken token = default)
|
||||
{
|
||||
if (RequestLocalizationOptions != default) return RequestLocalizationOptions;
|
||||
if (AppConfigurationService.AppConfiguration == default)
|
||||
await AppConfigurationService.Init();
|
||||
if (appConfigurationService.AppConfiguration == default)
|
||||
await appConfigurationService.Init(token);
|
||||
|
||||
RequestLocalizationOptions = new RequestLocalizationOptions();
|
||||
var cultures = AppConfigurationService
|
||||
var cultures = appConfigurationService
|
||||
.AppConfiguration
|
||||
.SupportedLanguages
|
||||
.Select(sl => new CultureInfo(sl))
|
||||
|
||||
@@ -14,30 +14,22 @@ namespace PrivaPub.Services
|
||||
// is deleted (PersonaRemoval: each group it owns, a Delete of the actor to everyone who follows it and everyone it
|
||||
// follows, its posts emptied, its name kept reserved and its documents answering 410). The root's sessions end first, so
|
||||
// nothing acts as it while it goes, and it keeps only a deleted-{id} name.
|
||||
public class RootRemoval : IRootRemoval
|
||||
public class RootRemoval(
|
||||
DbEntities dbEntities,
|
||||
IRootSessions sessions,
|
||||
IPersonaRemoval personas) : IRootRemoval
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IRootSessions _sessions;
|
||||
readonly IPersonaRemoval _personas;
|
||||
|
||||
public RootRemoval(DbEntities dbEntities, IRootSessions sessions, IPersonaRemoval personas)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_sessions = sessions;
|
||||
_personas = personas;
|
||||
}
|
||||
|
||||
public async Task<bool> Remove(string rootId, CancellationToken token)
|
||||
{
|
||||
var root = await _dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var root = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (root == default)
|
||||
return false;
|
||||
await _sessions.Revoke(root.ID, token);
|
||||
await sessions.Revoke(root.ID, token);
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
var avatarIds = (await _dbEntities.RootToAvatars.Match(ra => ra.RootId == root.ID).ExecuteAsync(token)).Select(ra => ra.AvatarId).ToList();
|
||||
var avatarIds = (await dbEntities.RootToAvatars.Match(ra => ra.RootId == root.ID).ExecuteAsync(token)).Select(ra => ra.AvatarId).ToList();
|
||||
foreach (var avatarId in avatarIds)
|
||||
await _personas.Remove(avatarId, token);
|
||||
await personas.Remove(avatarId, token);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(root.ID)
|
||||
.Modify(u => u.UserName, $"deleted-{root.ID}")//unique, so a second deletion never collides with the first
|
||||
|
||||
@@ -18,21 +18,12 @@ namespace PrivaPub.Services
|
||||
// and the Mastodon API tokens and authorizations of each of its personas, with their Web Push subscriptions. Used when its password is changed or
|
||||
// recovered, when it signs out everywhere and when it is deleted. End signs out one session only: the device that
|
||||
// asked (its Mastodon tokens it revokes itself).
|
||||
public class RootSessions : IRootSessions
|
||||
public class RootSessions(
|
||||
DbEntities dbEntities,
|
||||
IOpenIddictTokenManager openIddictTokenManager,
|
||||
IOpenIddictAuthorizationManager authorizations,
|
||||
AuthTokenManager authTokens) : IRootSessions
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IOpenIddictTokenManager _tokens;
|
||||
readonly IOpenIddictAuthorizationManager _authorizations;
|
||||
readonly AuthTokenManager _authTokens;
|
||||
|
||||
public RootSessions(DbEntities dbEntities, IOpenIddictTokenManager tokens, IOpenIddictAuthorizationManager authorizations, AuthTokenManager authTokens)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_tokens = tokens;
|
||||
_authorizations = authorizations;
|
||||
_authTokens = authTokens;
|
||||
}
|
||||
|
||||
public async Task Revoke(string rootId, CancellationToken token)
|
||||
{
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
@@ -40,14 +31,14 @@ namespace PrivaPub.Services
|
||||
.Modify(u => u.SessionStamp, Guid.NewGuid().ToString("N"))
|
||||
.Modify(u => u.EndedSessions, new List<EndedSession>())//the new stamp ends those too
|
||||
.ExecuteAsync(token);
|
||||
var links = await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId).ExecuteAsync(token);
|
||||
var links = await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId).ExecuteAsync(token);
|
||||
foreach (var link in links)
|
||||
{
|
||||
await _tokens.RevokeBySubjectAsync(link.AvatarId, token);
|
||||
await _authorizations.RevokeBySubjectAsync(link.AvatarId, token);
|
||||
await openIddictTokenManager.RevokeBySubjectAsync(link.AvatarId, token);
|
||||
await authorizations.RevokeBySubjectAsync(link.AvatarId, token);
|
||||
}
|
||||
// their Web Push subscriptions go with their tokens (R9)
|
||||
await Domain.Social.WebPush.Forget(links.Select(l => l.AvatarId).ToList());
|
||||
await Domain.Social.WebPush.Forget(links.Select(l => l.AvatarId).ToList(), token);
|
||||
}
|
||||
|
||||
// remembered as long as one of its tokens could still be valid; the ones that have expired are forgotten meanwhile
|
||||
@@ -58,7 +49,7 @@ namespace PrivaPub.Services
|
||||
.Modify(b => b.PullFilter(u => u.EndedSessions, s => s.Until < now))
|
||||
.ExecuteAsync(token);
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
.Modify(b => b.Push(u => u.EndedSessions, new EndedSession { Sid = sessionId, Until = now + _authTokens.Lifetime }))
|
||||
.Modify(b => b.Push(u => u.EndedSessions, new EndedSession { Sid = sessionId, Until = now + authTokens.Lifetime }))
|
||||
.ExecuteAsync(token);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,53 +20,32 @@ using System.Text.Json;
|
||||
|
||||
namespace PrivaPub.Services
|
||||
{
|
||||
public class RootUsersService : IRootUsersService
|
||||
public class RootUsersService(
|
||||
IJobQueue jobs,
|
||||
IRootSessions sessions,
|
||||
IRootRemoval removal,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<RootUsersService> logger,
|
||||
IPasswordHasher passwordHasher,
|
||||
DbEntities dbEntities,
|
||||
AppConfigurationService appConfigurationService) : IRootUsersService
|
||||
{
|
||||
readonly DbEntities DbEntities;
|
||||
readonly IPasswordHasher PasswordHasher;
|
||||
readonly IStringLocalizer Localizer;
|
||||
readonly ILogger<RootUsersService> Logger;
|
||||
readonly AppConfigurationService AppConfigurationService;
|
||||
readonly IJobQueue Jobs;
|
||||
readonly IRootSessions Sessions;
|
||||
readonly IRootRemoval Removal;
|
||||
|
||||
public RootUsersService(
|
||||
IJobQueue jobs,
|
||||
IRootSessions sessions,
|
||||
IRootRemoval removal,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<RootUsersService> logger,
|
||||
IPasswordHasher passwordHasher,
|
||||
DbEntities dbEntities,
|
||||
AppConfigurationService appConfigurationService)
|
||||
{
|
||||
Jobs = jobs;
|
||||
Sessions = sessions;
|
||||
Removal = removal;
|
||||
DbEntities = dbEntities;
|
||||
PasswordHasher = passwordHasher;
|
||||
Localizer = localizer;
|
||||
Logger = logger;
|
||||
AppConfigurationService = appConfigurationService;
|
||||
}
|
||||
|
||||
public const string NoMatch = "That username and password do not match.";
|
||||
static string _decoy;
|
||||
|
||||
// a hash nobody's password matches, so an unknown login costs the same hashing as a wrong password
|
||||
string Decoy => _decoy ??= PasswordHasher.Hash(Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)));
|
||||
string Decoy => _decoy ??= passwordHasher.Hash(Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)));
|
||||
|
||||
public async Task<WebResult> SignUpAsync(LoginForm signUpForm)
|
||||
public async Task<WebResult> SignUpAsync(LoginForm signUpForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
signUpForm.UserName = signUpForm.UserName.ToLower();
|
||||
if (await DbEntities.RootUsers.Match(u => u.UserName == signUpForm.UserName).ExecuteAnyAsync())
|
||||
return result.Invalidate(Localizer["Username '{0}' already taken.", signUpForm.UserName]);
|
||||
if (await dbEntities.RootUsers.Match(u => u.UserName == signUpForm.UserName).ExecuteAnyAsync(token))
|
||||
return result.Invalidate(localizer["Username '{0}' already taken.", signUpForm.UserName]);
|
||||
|
||||
var signUpPasswordHashed = PasswordHasher.Hash(signUpForm.Password);
|
||||
var signUpPasswordHashed = passwordHasher.Hash(signUpForm.Password);
|
||||
var newUser = new RootUser
|
||||
{
|
||||
UserName = signUpForm.UserName,
|
||||
@@ -74,7 +53,7 @@ namespace PrivaPub.Services
|
||||
};
|
||||
|
||||
var cultureLanguage = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
|
||||
var language = await DbEntities.Languages.Match(l => l.International2Code == cultureLanguage).ExecuteFirstAsync();
|
||||
var language = await dbEntities.Languages.Match(l => l.International2Code == cultureLanguage).ExecuteFirstAsync(token);
|
||||
newUser.Settings = new RootUserSettings
|
||||
{
|
||||
LanguageCode = language?.International2Code ?? "en",
|
||||
@@ -86,7 +65,7 @@ namespace PrivaPub.Services
|
||||
PreferSystemTheming = signUpForm.PreferSystemTheming,
|
||||
ThemeIsDarkMode = signUpForm.ThemeIsDarkMode
|
||||
};
|
||||
await DB.Default.SaveAsync(newUser);
|
||||
await DB.Default.SaveAsync(newUser, token);
|
||||
|
||||
result.Data = (newUser, ToViewSettings(newUser.Settings));
|
||||
|
||||
@@ -94,12 +73,12 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SignUpAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SignUpAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> LoginAsync(LoginForm loginForm)
|
||||
public async Task<WebResult> LoginAsync(LoginForm loginForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
@@ -107,33 +86,33 @@ namespace PrivaPub.Services
|
||||
// One answer, after the same work, whether the login is unknown, deleted or the password wrong: sign-in must not
|
||||
// tell anyone which logins exist. Only someone who knows the password learns the login is banned.
|
||||
loginForm.UserName = loginForm.UserName.ToLower();
|
||||
var user = await DbEntities.RootUsers.Match(u => u.UserName == loginForm.UserName && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, needsUpgrade) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, loginForm.Password);
|
||||
var user = await dbEntities.RootUsers.Match(u => u.UserName == loginForm.UserName && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, needsUpgrade) = passwordHasher.Check(user?.HashedPassword ?? Decoy, loginForm.Password);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer[NoMatch]);
|
||||
return result.Invalidate(localizer[NoMatch]);
|
||||
if (user.IsBanned)
|
||||
return result.Invalidate(Localizer["User '{0}' banned.", user.UserName]);
|
||||
return result.Invalidate(localizer["User '{0}' banned.", user.UserName]);
|
||||
// only a correct password learns that two-factor is on: it is asked for with a 428
|
||||
if (user.Totp?.EnabledAt != default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(loginForm.OneTimeCode))
|
||||
return result.Invalidate(Localizer[TwoFactor.CodeNeeded], StatusCodes.Status428PreconditionRequired);
|
||||
return result.Invalidate(localizer[TwoFactor.CodeNeeded], StatusCodes.Status428PreconditionRequired);
|
||||
if (!await TwoFactor.Consume(user, loginForm.OneTimeCode, CancellationToken.None))
|
||||
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
|
||||
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
|
||||
}
|
||||
|
||||
// hashed again at today's iterations; matched on the old hash, so two sign-ins at once never undo each other
|
||||
if (needsUpgrade)
|
||||
{
|
||||
var oldHash = user.HashedPassword;
|
||||
user.HashedPassword = PasswordHasher.Hash(loginForm.Password);
|
||||
user.HashedPassword = passwordHasher.Hash(loginForm.Password);
|
||||
await DB.Default.Update<RootUser>()
|
||||
.Match(u => u.ID == user.ID && u.HashedPassword == oldHash)
|
||||
.Modify(u => u.HashedPassword, user.HashedPassword)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
}
|
||||
|
||||
var userSettingsResult = await GetUserSettingsAsync(user.ID, loginForm);
|
||||
var userSettingsResult = await GetUserSettingsAsync(user.ID, loginForm, token);
|
||||
var userSettings = (ViewUserSettings)userSettingsResult.Data;
|
||||
|
||||
result.Data = (user, userSettings);
|
||||
@@ -142,27 +121,27 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(LoginAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(LoginAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId)
|
||||
public async Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var isSupportedLanguage = AppConfigurationService.AppConfiguration.SupportedLanguages.Contains(userSettings.LanguageCode);
|
||||
var isSupportedLanguage = appConfigurationService.AppConfiguration.SupportedLanguages.Contains(userSettings.LanguageCode);
|
||||
if (!isSupportedLanguage)
|
||||
return result.Invalidate(Localizer["Language code '{0}' unsupported.", userSettings.LanguageCode]);
|
||||
return result.Invalidate(localizer["Language code '{0}' unsupported.", userSettings.LanguageCode]);
|
||||
|
||||
var languageCodeExists = await DbEntities.Languages
|
||||
.Match(l => l.International2Code == userSettings.LanguageCode).ExecuteAnyAsync();
|
||||
var languageCodeExists = await dbEntities.Languages
|
||||
.Match(l => l.International2Code == userSettings.LanguageCode).ExecuteAnyAsync(token);
|
||||
if (!languageCodeExists)
|
||||
return result.Invalidate(Localizer["Language code '{0}' doesn't exist.", userSettings.LanguageCode]);
|
||||
return result.Invalidate(localizer["Language code '{0}' doesn't exist.", userSettings.LanguageCode]);
|
||||
|
||||
var language = await DbEntities.Languages.Match(l => l.International2Code == userSettings.LanguageCode)
|
||||
.ExecuteFirstAsync();
|
||||
var language = await dbEntities.Languages.Match(l => l.International2Code == userSettings.LanguageCode)
|
||||
.ExecuteFirstAsync(token);
|
||||
_ = await DB.Default.Update<RootUser>()
|
||||
.MatchID(userId)
|
||||
.Modify(u => u.Settings.LanguageCode, language.International2Code)
|
||||
@@ -175,98 +154,98 @@ namespace PrivaPub.Services
|
||||
.Modify(u => u.Settings.IconsThemeIndexColour, userSettings.IconsThemeIndexColour)
|
||||
.Modify(u => u.Settings.SavedAt, DateTime.UtcNow)
|
||||
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserSettingsAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserSettingsAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId)
|
||||
public async Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.Match(u => u.ID == userId && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var user = await dbEntities.RootUsers.Match(u => u.ID == userId && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
|
||||
if (user == null)
|
||||
return result.Invalidate(Localizer["Username '{0}' not found.", userId]);
|
||||
return result.Invalidate(localizer["Username '{0}' not found.", userId]);
|
||||
|
||||
var (verified, needsUpgrade) = PasswordHasher.Check(user.HashedPassword, userPasswordForm.OldPassword);
|
||||
var (verified, needsUpgrade) = passwordHasher.Check(user.HashedPassword, userPasswordForm.OldPassword);
|
||||
|
||||
if (!verified)
|
||||
return result.Invalidate(Localizer["Wrong password."]);
|
||||
return result.Invalidate(localizer["Wrong password."]);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(user.ID)
|
||||
.Modify(u => u.HashedPassword, PasswordHasher.Hash(userPasswordForm.NewPassword))
|
||||
.Modify(u => u.HashedPassword, passwordHasher.Hash(userPasswordForm.NewPassword))
|
||||
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
// whoever else is signed in may be why the password changed: every session ends, and the caller gets a new one
|
||||
await Sessions.Revoke(user.ID, CancellationToken.None);
|
||||
user = await DbEntities.RootUsers.MatchID(user.ID).ExecuteFirstAsync();
|
||||
await sessions.Revoke(user.ID, CancellationToken.None);
|
||||
user = await dbEntities.RootUsers.MatchID(user.ID).ExecuteFirstAsync(token);
|
||||
result.Data = (user, ToViewSettings(user.Settings));
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserPasswordAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserPasswordAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> RemoveUserAsync(UsersIds usersIds)
|
||||
public async Task<WebResult> RemoveUserAsync(UsersIds usersIds, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var removed = 0;
|
||||
foreach (var id in usersIds.UserIdList.Distinct())
|
||||
if (await Removal.Remove(id, CancellationToken.None))
|
||||
if (await removal.Remove(id, CancellationToken.None))
|
||||
removed++;
|
||||
if (removed == 0)
|
||||
return result.Invalidate(Localizer["User already deleted."]);
|
||||
return result.Invalidate(localizer["User already deleted."]);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveUserAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveUserAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// A root deletes itself only with its password, so a stolen session cannot.
|
||||
public async Task<WebResult> RemoveSelfAsync(string rootId, string password)
|
||||
public async Task<WebResult> RemoveSelfAsync(string rootId, string password, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer[NoMatch], StatusCodes.Status403Forbidden);
|
||||
await Removal.Remove(user.ID, CancellationToken.None);
|
||||
return result.Invalidate(localizer[NoMatch], StatusCodes.Status403Forbidden);
|
||||
await removal.Remove(user.ID, CancellationToken.None);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveSelfAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveSelfAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// what can't be undone asks for the password again (a persona's or a group's deletion, by its login or an administrator)
|
||||
public async Task<bool> PasswordMatches(string rootId, string password)
|
||||
public async Task<bool> PasswordMatches(string rootId, string password, CancellationToken token = default)
|
||||
{
|
||||
var user = string.IsNullOrEmpty(rootId) ? default : await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
var user = string.IsNullOrEmpty(rootId) ? default : await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
return user?.HashedPassword != default && verified;
|
||||
}
|
||||
|
||||
public async Task<WebResult> BanUserAsync(UsersIds usersIds)
|
||||
public async Task<WebResult> BanUserAsync(UsersIds usersIds, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
@@ -274,18 +253,18 @@ namespace PrivaPub.Services
|
||||
await DB.Default.Update<RootUser>()
|
||||
.Match(u => usersIds.UserIdList.Contains(u.ID))
|
||||
.Modify(u => u.IsBanned, true)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(BanUserAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(BanUserAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> UnbanUserAsync(UsersIds usersIds)
|
||||
public async Task<WebResult> UnbanUserAsync(UsersIds usersIds, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
@@ -293,25 +272,25 @@ namespace PrivaPub.Services
|
||||
await DB.Default.Update<RootUser>()
|
||||
.Match(u => usersIds.UserIdList.Contains(u.ID))
|
||||
.Modify(u => u.IsBanned, false)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UnbanUserAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UnbanUserAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default)
|
||||
public async Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(userId).ExecuteFirstAsync();
|
||||
var user = await dbEntities.RootUsers.MatchID(userId).ExecuteFirstAsync(token);
|
||||
if (user == default)
|
||||
return result.Invalidate(Localizer["User not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["User not found."], StatusCodes.Status404NotFound);
|
||||
|
||||
if (loginForm != default && loginForm.ThemeIsDarkMode != user.Settings.ThemeIsDarkMode)
|
||||
{
|
||||
@@ -319,7 +298,7 @@ namespace PrivaPub.Services
|
||||
await DB.Default.Update<RootUser>()
|
||||
.MatchID(userId)
|
||||
.Modify(u => u.Settings.ThemeIsDarkMode, loginForm.ThemeIsDarkMode)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
}
|
||||
|
||||
result.Data = ToViewSettings(user.Settings);
|
||||
@@ -327,8 +306,8 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(GetUserSettingsAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(GetUserSettingsAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,72 +315,72 @@ namespace PrivaPub.Services
|
||||
|
||||
// The same answer, after the same work, whether the account exists, has an email or can be written to: recovery must
|
||||
// not tell anyone which logins or addresses exist. RecoveryJob does the rest, out of the request.
|
||||
public async Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host)
|
||||
public async Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var userName = passwordRecoveryForm.UserName?.ToLowerInvariant();
|
||||
var user = passwordRecoveryForm.IsEmailDisabled
|
||||
? await DbEntities.RootUsers.Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync()
|
||||
: await DbEntities.RootUsers.Match(u => u.Email == passwordRecoveryForm.Email && u.IsEmailValidated && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
await Jobs.Enqueue(JobKind.SendRecovery, JsonSerializer.Serialize(new RecoveryPayload(user?.ID, host)), RecoveryJob.Host,
|
||||
? await dbEntities.RootUsers.Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync(token)
|
||||
: await dbEntities.RootUsers.Match(u => u.Email == passwordRecoveryForm.Email && u.IsEmailValidated && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
await jobs.Enqueue(JobKind.SendRecovery, JsonSerializer.Serialize(new RecoveryPayload(user?.ID, host)), RecoveryJob.Host,
|
||||
dedupeKey: default, CancellationToken.None);
|
||||
result.Data = Localizer[RecoverySent].Value;
|
||||
result.Data = (string)localizer[RecoverySent];
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SetupAndSendRecoveryEmail)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SetupAndSendRecoveryEmail)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
Task<EmailRecovery> LiveRecovery(string recoveryCode)
|
||||
Task<EmailRecovery> LiveRecovery(string recoveryCode, CancellationToken token = default)
|
||||
{
|
||||
var hash = RecoveryJob.Hash(recoveryCode);
|
||||
var now = DateTime.UtcNow;
|
||||
return DbEntities.EmailRecoveries.Match(er => er.CodeHash == hash && er.ExpiresAt > now).ExecuteFirstAsync();
|
||||
return dbEntities.EmailRecoveries.Match(er => er.CodeHash == hash && er.ExpiresAt > now).ExecuteFirstAsync(token);
|
||||
}
|
||||
|
||||
public async Task<WebResult> IsValidRecoveryCode(string recoveryCode)
|
||||
public async Task<WebResult> IsValidRecoveryCode(string recoveryCode, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
result.Data = await LiveRecovery(recoveryCode) != default;
|
||||
result.Data = await LiveRecovery(recoveryCode, token) != default;
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// A recovered password ends every session the root had: whoever had them may be why it was recovered.
|
||||
public async Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm)
|
||||
public async Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var recovery = await LiveRecovery(newPasswordForm.RecoveryCode);
|
||||
var recovery = await LiveRecovery(newPasswordForm.RecoveryCode, token);
|
||||
var user = recovery == default ? default
|
||||
: await DbEntities.RootUsers.MatchID(recovery.RootUserId).Match(u => u.DeletedAt == null && !u.IsBanned).ExecuteFirstAsync();
|
||||
: await dbEntities.RootUsers.MatchID(recovery.RootUserId).Match(u => u.DeletedAt == null && !u.IsBanned).ExecuteFirstAsync(token);
|
||||
if (user == default)
|
||||
return result.Invalidate(Localizer["Invalid recovery code."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Invalid recovery code."], StatusCodes.Status404NotFound);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(user.ID)
|
||||
.Modify(u => u.HashedPassword, PasswordHasher.Hash(newPasswordForm.NewPassword))
|
||||
.Modify(u => u.HashedPassword, passwordHasher.Hash(newPasswordForm.NewPassword))
|
||||
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
await DB.Default.DeleteAsync<EmailRecovery>(er => er.RootUserId == user.ID);
|
||||
await Sessions.Revoke(user.ID, CancellationToken.None);
|
||||
await sessions.Revoke(user.ID, CancellationToken.None);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(ChangePassword)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(ChangePassword)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,16 +400,16 @@ namespace PrivaPub.Services
|
||||
public const string EmailCodeSent = "If that address can be used, a code is on its way to it. It works for one hour.";
|
||||
public const string EmailCodeInvalid = "That code is not valid.";
|
||||
|
||||
public async Task<WebResult> AccountAsync(string rootId)
|
||||
public async Task<WebResult> AccountAsync(string rootId, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (user == default)
|
||||
return result.Invalidate(Localizer["User not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["User not found."], StatusCodes.Status404NotFound);
|
||||
var now = DateTime.UtcNow;
|
||||
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync();
|
||||
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync(token);
|
||||
result.Data = new ViewAccount
|
||||
{
|
||||
UserName = user.UserName,
|
||||
@@ -445,22 +424,22 @@ namespace PrivaPub.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(AccountAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(AccountAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// Only with the password, so a stolen session can't move recovery to its own inbox. The answer is the same sentence
|
||||
// whether or not the address is free; EmailVerificationJob sends the code, or nothing when another login holds it.
|
||||
public async Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form)
|
||||
public async Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, form.Password ?? string.Empty);
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, form.Password ?? string.Empty);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
|
||||
await DB.Default.DeleteAsync<EmailVerification>(v => v.RootUserId == user.ID);
|
||||
var pending = new EmailVerification
|
||||
@@ -469,94 +448,94 @@ namespace PrivaPub.Services
|
||||
Email = form.Email.Trim().ToLowerInvariant(),
|
||||
ExpiresAt = DateTime.UtcNow + EmailVerification.Lifetime
|
||||
};
|
||||
await DB.Default.SaveAsync(pending);
|
||||
await Jobs.Enqueue(JobKind.SendEmailVerification, JsonSerializer.Serialize(new EmailVerificationPayload(pending.ID)),
|
||||
await DB.Default.SaveAsync(pending, token);
|
||||
await jobs.Enqueue(JobKind.SendEmailVerification, JsonSerializer.Serialize(new EmailVerificationPayload(pending.ID)),
|
||||
EmailVerificationJob.Host, dedupeKey: default, CancellationToken.None);
|
||||
result.Data = Localizer[EmailCodeSent].Value;
|
||||
result.Data = (string)localizer[EmailCodeSent];
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RequestEmailChangeAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RequestEmailChangeAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// One answer for every failure (wrong, expired, five tries spent, or the address verified by another login meanwhile)
|
||||
public async Task<WebResult> VerifyEmailAsync(string rootId, string code)
|
||||
public async Task<WebResult> VerifyEmailAsync(string rootId, string code, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync();
|
||||
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync(token);
|
||||
if (pending == default || string.IsNullOrEmpty(pending.CodeHash))
|
||||
return result.Invalidate(Localizer[EmailCodeInvalid]);
|
||||
return result.Invalidate(localizer[EmailCodeInvalid]);
|
||||
if (pending.CodeHash != RecoveryJob.Hash(code?.Trim()))
|
||||
{
|
||||
if (pending.Attempts + 1 >= EmailVerification.MaxAttempts)
|
||||
await DB.Default.DeleteAsync<EmailVerification>(pending.ID);
|
||||
else
|
||||
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(b => b.Inc(v => v.Attempts, 1)).ExecuteAsync();
|
||||
return result.Invalidate(Localizer[EmailCodeInvalid]);
|
||||
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(b => b.Inc(v => v.Attempts, 1)).ExecuteAsync(token);
|
||||
return result.Invalidate(localizer[EmailCodeInvalid]);
|
||||
}
|
||||
await DB.Default.DeleteAsync<EmailVerification>(pending.ID);
|
||||
if (await DbEntities.RootUsers.Match(u => u.Email == pending.Email && u.IsEmailValidated && u.ID != rootId && u.DeletedAt == null).ExecuteAnyAsync())
|
||||
return result.Invalidate(Localizer[EmailCodeInvalid]);
|
||||
if (await dbEntities.RootUsers.Match(u => u.Email == pending.Email && u.IsEmailValidated && u.ID != rootId && u.DeletedAt == null).ExecuteAnyAsync(token))
|
||||
return result.Invalidate(localizer[EmailCodeInvalid]);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
.Modify(u => u.Email, pending.Email)
|
||||
.Modify(u => u.IsEmailValidated, true)
|
||||
.Modify(u => u.UpdatedAt, now)
|
||||
.ExecuteAsync();
|
||||
return await AccountAsync(rootId);
|
||||
.ExecuteAsync(token);
|
||||
return await AccountAsync(rootId, token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(VerifyEmailAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(VerifyEmailAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
// Two-factor sign-in (TwoFactor): set up with the password, turned on by the app's first code (which also proves the
|
||||
// app holds the secret), turned off with the password and a code. Turning it on ends every other session.
|
||||
public async Task<WebResult> TotpSetupAsync(string rootId, string password)
|
||||
public async Task<WebResult> TotpSetupAsync(string rootId, string password, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
if (user.Totp?.EnabledAt != default)
|
||||
return result.Invalidate(Localizer["Two-factor sign-in is on already: turn it off first."], StatusCodes.Status409Conflict);
|
||||
return result.Invalidate(localizer["Two-factor sign-in is on already: turn it off first."], StatusCodes.Status409Conflict);
|
||||
|
||||
var secret = TwoFactor.NewSecret();
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
.Modify(u => u.Totp, new RootTotp { PendingSecret = secret, PendingSince = DateTime.UtcNow })
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
var uri = TwoFactor.OtpAuthUri(secret, user.UserName);
|
||||
result.Data = new ViewTotpSetup { Secret = secret, OtpAuthUri = uri, QrDataUri = TwoFactor.QrDataUri(uri) };
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpSetupAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpSetupAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> TotpEnableAsync(string rootId, string code)
|
||||
public async Task<WebResult> TotpEnableAsync(string rootId, string code, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (user?.Totp is not { EnabledAt: null, PendingSecret: not null } pending || pending.PendingSince < DateTime.UtcNow.AddHours(-1))
|
||||
return result.Invalidate(Localizer["Set up two-factor sign-in again: that setup expired."], StatusCodes.Status409Conflict);
|
||||
return result.Invalidate(localizer["Set up two-factor sign-in again: that setup expired."], StatusCodes.Status409Conflict);
|
||||
if (TwoFactor.Step(pending.PendingSecret, code) is not { } step)
|
||||
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
|
||||
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
|
||||
|
||||
var codes = TwoFactor.NewRecoveryCodes();
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
@@ -567,66 +546,66 @@ namespace PrivaPub.Services
|
||||
LastStep = step,
|
||||
RecoveryCodeHashes = codes.Select(TwoFactor.HashRecovery).ToList()
|
||||
})
|
||||
.ExecuteAsync();
|
||||
await Sessions.Revoke(rootId, CancellationToken.None);
|
||||
user = await DbEntities.RootUsers.MatchID(rootId).ExecuteFirstAsync();
|
||||
.ExecuteAsync(token);
|
||||
await sessions.Revoke(rootId, CancellationToken.None);
|
||||
user = await dbEntities.RootUsers.MatchID(rootId).ExecuteFirstAsync(token);
|
||||
result.Data = (user, ToViewSettings(user.Settings), codes);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpEnableAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpEnableAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> TotpDisableAsync(string rootId, string password, string code)
|
||||
public async Task<WebResult> TotpDisableAsync(string rootId, string password, string code, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
if (user.Totp?.EnabledAt == default)
|
||||
return await AccountAsync(rootId);
|
||||
return await AccountAsync(rootId, token);
|
||||
if (!await TwoFactor.Consume(user, code, CancellationToken.None))
|
||||
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
|
||||
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId).Modify(u => u.Totp, null).ExecuteAsync();
|
||||
return await AccountAsync(rootId);
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId).Modify(u => u.Totp, null).ExecuteAsync(token);
|
||||
return await AccountAsync(rootId, token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpDisableAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpDisableAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebResult> RemoveEmailAsync(string rootId, string password)
|
||||
public async Task<WebResult> RemoveEmailAsync(string rootId, string password, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
|
||||
if (user?.HashedPassword == default || !verified)
|
||||
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
|
||||
|
||||
await DB.Default.Update<RootUser>().MatchID(rootId)
|
||||
.Modify(u => u.Email, null)
|
||||
.Modify(u => u.IsEmailValidated, false)
|
||||
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.ExecuteAsync();
|
||||
.ExecuteAsync(token);
|
||||
await DB.Default.DeleteAsync<EmailVerification>(v => v.RootUserId == rootId);
|
||||
await DB.Default.DeleteAsync<EmailRecovery>(r => r.RootUserId == rootId);
|
||||
return await AccountAsync(rootId);
|
||||
return await AccountAsync(rootId, token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveEmailAsync)}()");
|
||||
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveEmailAsync)}()");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user