From c2f439d1e99695be24db91a73b808768498dadbf Mon Sep 17 00:00:00 2001 From: thepra Date: Tue, 10 Nov 2026 08:11:11 +0100 Subject: [PATCH] Every failure the server answers with names its own error code Each refusal and failure the client API sends now starts with a code no other failure uses, such as "[ERR0030006] That code is not valid.", so a screenshot or a report points at the exact place it came from. Nothing another program reads changes: ActivityPub, the Mastodon API's errors, sign-in tokens and the error kinds decePubClient branches on stay as they were. The house-rules checks move to 1.1.0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd --- CLAUDE.md | 37 ++++++++ Directory.Build.props | 4 +- .../ClientToServer/AdminController.cs | 24 ++--- .../ClientToServer/BackupController.cs | 16 ++-- .../ClientToServer/DataController.cs | 2 +- .../ClientToServer/DomainBlockController.cs | 2 +- .../ClientToServer/EmojiAdminController.cs | 10 +-- .../ClientToServer/GroupController.cs | 8 +- .../ClientToServer/InstanceAdminController.cs | 26 +++--- .../ClientToServer/ModeratorController.cs | 8 +- .../PersonaArchiveController.cs | 10 +-- .../ClientToServer/PostController.cs | 2 +- .../ClientToServer/PrivateAvatarController.cs | 22 ++--- .../ClientToServer/RootUserController.cs | 76 ++++++++-------- .../ClientToServer/SocialController.cs | 2 +- .../Domain/Moderation/AccountModeration.cs | 14 +-- PrivaPub/Domain/Social/FollowService.cs | 12 +-- PrivaPub/Domain/Timelines/TimelineService.cs | 6 +- PrivaPub/ErrUtility.cs | 6 ++ PrivaPub/PrivaPub.csproj | 1 + .../Private/IPrivateAvatarUsersService.cs | 22 ++--- PrivaPub/Services/GroupUsersService.cs | 60 ++++++------- PrivaPub/Services/JwtEvents.cs | 4 +- PrivaPub/Services/PostsService.cs | 30 +++---- PrivaPub/Services/RootUsersService.cs | 88 +++++++++---------- 25 files changed, 268 insertions(+), 224 deletions(-) create mode 100644 PrivaPub/ErrUtility.cs diff --git a/CLAUDE.md b/CLAUDE.md index e0d608d..ca88995 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1105,6 +1105,43 @@ same rules. Applied to PrivaPub: (HR0009). - Numbers shown to a reader go through formatting helpers (HR0011). The ISO week key (`InstanceDescriber.Week`) and the six-digit email code (`EmailVerificationJob.NewCode`) are identifiers, and say so. +- **Error codes** (HR0012, HR0013): every `WebResult` failure the server answers with starts with a code no other + failure uses, `[ERR0030006] …`, through `ErrUtility.ToCodedError` (namespace `PrivaPub`; `HouseRulesCodedErrors` is on + in `PrivaPub.csproj` only). The code goes in the message, the text a person reads in decePubClient. Nothing + machine-read changes: `WebResult.ErrorCode` (the `FailureCodes` decePubClient branches on), ActivityPub responses, + OpenIddict's own errors and the Mastodon API's `{"error": …}` bodies don't come from `WebResult`. A helper that + builds failures takes an `int errorCode` (`EmojiAdminController.Refused`, `InstanceAdminController.Refused`), called + with a literal. Each file owns a block of 1000; a new file takes the next free one (31000): + + | Codes | File | + |---|---| + | 10000–10999 | `Controllers/ClientToServer/AdminController` | + | 11000–11999 | `Controllers/ClientToServer/BackupController` | + | 12000–12999 | `Controllers/ClientToServer/DataController` | + | 13000–13999 | `Controllers/ClientToServer/DomainBlockController` | + | 14000–14999 | `Controllers/ClientToServer/EmojiAdminController` | + | 15000–15999 | `Controllers/ClientToServer/GroupController` | + | 16000–16999 | `Controllers/ClientToServer/InstanceAdminController` | + | 17000–17999 | `Controllers/ClientToServer/ModeratorController` | + | 18000–18999 | `Controllers/ClientToServer/PersonaArchiveController` | + | 19000–19999 | `Controllers/ClientToServer/PostController` | + | 20000–20999 | `Controllers/ClientToServer/PrivateAvatarController` | + | 21000–21999 | `Controllers/ClientToServer/RootUserController` | + | 22000–22999 | `Controllers/ClientToServer/SocialController` | + | 23000–23999 | `Domain/Moderation/AccountModeration` | + | 24000–24999 | `Domain/Social/FollowService` | + | 25000–25999 | `Domain/Timelines/TimelineService` | + | 26000–26999 | `Services/ClientToServer/Private/IPrivateAvatarUsersService` | + | 27000–27999 | `Services/GroupUsersService` | + | 28000–28999 | `Services/JwtEvents` | + | 29000–29999 | `Services/PostsService` | + | 30000–30999 | `Services/RootUsersService` | + +- **Passwords** (HR0311): only the owner of a login chooses its password (sign-up, change, e-mailed recovery code). The + one place an operator types a password is the shell's `PrivaPub admin create-root`, meant for the operator's own + first login. +- **Spreadsheets** (HR0319): none, and none by default. +- **Not applicable here:** the markup rules (HR0107, HR0108, HR0320) belong to decePubClient, which has its own section. - **Routes** are constants in `PrivaPub/ApiPaths.cs` (HR0305): one nested class per controller, `GET_`/`POST_`/…, `_M_` when the template has parameters, `Prefix` for a controller's own `[Route]`. The values are the frozen routes above, never changed by a rename. decePubClient keeps its own `APIs` class (owner, 2026-11-10: kept separate). diff --git a/Directory.Build.props b/Directory.Build.props index 6a0cabc..500b098 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,11 +9,11 @@ true PrivaPub.ClientModels - $(WarningsAsErrors);HR0001;HR0002;HR0003;HR0004;HR0005;HR0006;HR0007;HR0008;HR0009;HR0010;HR0011;HR0101;HR0102;HR0103;HR0104;HR0105;HR0106;HR0201 + $(WarningsAsErrors);HR0001;HR0002;HR0003;HR0004;HR0005;HR0006;HR0007;HR0008;HR0009;HR0010;HR0011;HR0012;HR0013;HR0101;HR0102;HR0103;HR0104;HR0105;HR0106;HR0107;HR0108;HR0201 - + diff --git a/PrivaPub/Controllers/ClientToServer/AdminController.cs b/PrivaPub/Controllers/ClientToServer/AdminController.cs index 41b7552..4844d8b 100644 --- a/PrivaPub/Controllers/ClientToServer/AdminController.cs +++ b/PrivaPub/Controllers/ClientToServer/AdminController.cs @@ -76,7 +76,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(10001.ToCodedError(localizer["Something went wrong."]))); } } @@ -110,7 +110,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(10002.ToCodedError(localizer["Something went wrong."]))); } } @@ -136,7 +136,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(10003.ToCodedError(localizer["Something went wrong."]))); } } @@ -183,9 +183,9 @@ namespace PrivaPub.Controllers.ClientToServer public async Task Role(string id, RootRoleForm form, CancellationToken token) { if (!ModelState.IsValid || !RootUser.TryParseRole(form.Role, out var role)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity)); + return UnprocessableEntity(new WebResult().Invalidate(10004.ToCodedError(localizer["Unknown role."]), StatusCodes.Status422UnprocessableEntity)); if (id == User.GetUserId()) - return Conflict(new WebResult().Invalidate(localizer["You can't change your own role."], StatusCodes.Status409Conflict)); + return Conflict(new WebResult().Invalidate(10005.ToCodedError(localizer["You can't change your own role."]), StatusCodes.Status409Conflict)); var root = await DB.Default.Find().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token); if (root == default) return NotFound(); @@ -193,7 +193,7 @@ namespace PrivaPub.Controllers.ClientToServer if (was == role) return Ok((await Views(new List { root }, token))[0]); if (was == RootRole.Admin && !await OtherAdministrators(root.ID, token)) - return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict)); + return Conflict(new WebResult().Invalidate(10006.ToCodedError(localizer["The last administrator can't be demoted."]), StatusCodes.Status409Conflict)); root.SetRole(role); await DB.Default.Update().MatchID(root.ID).Modify(u => u.Policies, root.Policies).Modify(u => u.UpdatedAt, root.UpdatedAt) .ExecuteAsync(CancellationToken.None); @@ -202,7 +202,7 @@ namespace PrivaPub.Controllers.ClientToServer { root.SetRole(was); await DB.Default.Update().MatchID(root.ID).Modify(u => u.Policies, root.Policies).ExecuteAsync(CancellationToken.None); - return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict)); + return Conflict(new WebResult().Invalidate(10007.ToCodedError(localizer["The last administrator can't be demoted."]), StatusCodes.Status409Conflict)); } if (role == RootRole.Admin) await ServerSetup.Seal(root.ID, default);//an administrator exists: the client's setup is closed @@ -221,7 +221,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task ResetTotp(string id, CancellationToken token) { if (id == User.GetUserId()) - return Conflict(new WebResult().Invalidate(localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict)); + return Conflict(new WebResult().Invalidate(10008.ToCodedError(localizer["Turn your own two-factor sign-in off from your account."]), StatusCodes.Status409Conflict)); var root = await DB.Default.Find().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token); if (root == default) return NotFound(); @@ -236,9 +236,9 @@ namespace PrivaPub.Controllers.ClientToServer public async Task DeletePersona(string id, AdminPasswordForm form, [FromServices] IPersonaRemoval personas, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(10009.ToCodedError(localizer["Invalid model."]))); if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token)) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(10010.ToCodedError(localizer[Services.RootUsersService.NoMatch]), StatusCodes.Status403Forbidden)); var avatar = await dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token); if (avatar == default) return NotFound(); @@ -253,9 +253,9 @@ namespace PrivaPub.Controllers.ClientToServer public async Task DeleteGroup(string id, AdminPasswordForm form, [FromServices] IGroupRemoval groups, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(10011.ToCodedError(localizer["Invalid model."]))); if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token)) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(10012.ToCodedError(localizer[Services.RootUsersService.NoMatch]), StatusCodes.Status403Forbidden)); var group = await dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token); if (group == default) return NotFound(); diff --git a/PrivaPub/Controllers/ClientToServer/BackupController.cs b/PrivaPub/Controllers/ClientToServer/BackupController.cs index d6ee715..3a172af 100644 --- a/PrivaPub/Controllers/ClientToServer/BackupController.cs +++ b/PrivaPub/Controllers/ClientToServer/BackupController.cs @@ -64,7 +64,7 @@ namespace PrivaPub.Controllers.ClientToServer if (admin == default) return Forbid(); if (await MaintenanceLock.Current(token) is { } held) - return Conflict(new WebResult().Invalidate(localizer["A {0} is running.", held.What])); + return Conflict(new WebResult().Invalidate(11001.ToCodedError(localizer["A {0} is running.", held.What]))); await log.Write(admin.ID, Models.AdminActions.BackupCreate, Models.AdminTargets.Backup, default, "manual", token: token); _ = Task.Run(async () => { @@ -91,7 +91,7 @@ namespace PrivaPub.Controllers.ClientToServer if (admin == default) return Forbid(); if (RestoreMarker.Read(backups.Root) is { } waiting && (waiting.Backup == id || waiting.PreRestore == id)) - return Conflict(new WebResult().Invalidate(localizer["A restore waits for this backup."])); + return Conflict(new WebResult().Invalidate(11002.ToCodedError(localizer["A restore waits for this backup."]))); if (!backups.Delete(id)) return NotFound(); await log.Write(admin.ID, Models.AdminActions.BackupDelete, Models.AdminTargets.Backup, id, id, token: token); @@ -106,7 +106,7 @@ namespace PrivaPub.Controllers.ClientToServer if (admin == default) return Forbid(); if (!PasswordHolds(admin, form.Password)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Wrong password."])); + return UnprocessableEntity(new WebResult().Invalidate(11003.ToCodedError(localizer["Wrong password."]))); if (backups.Find(id) == default) return NotFound(); var (ticket, expires) = transfers.Ticket(id); @@ -187,10 +187,10 @@ namespace PrivaPub.Controllers.ClientToServer if (await Administrator(token) == default) return Forbid(); if (await MaintenanceLock.Current(token) is { What: "restore" }) - return Conflict(new WebResult().Invalidate(localizer["A {0} is running.", "restore"])); + return Conflict(new WebResult().Invalidate(11004.ToCodedError(localizer["A {0} is running.", "restore"]))); var (backup, error) = await transfers.Finish(id, token); if (backup == default) - return UnprocessableEntity(new WebResult().Invalidate(error)); + return UnprocessableEntity(new WebResult().Invalidate(11005.ToCodedError(error))); return Ok(View(backup, 0, ServerBackup.CodeMigration())); } @@ -210,12 +210,12 @@ namespace PrivaPub.Controllers.ClientToServer if (admin == default) return Forbid(); if (!PasswordHolds(admin, form.Password)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Wrong password."])); + return UnprocessableEntity(new WebResult().Invalidate(11006.ToCodedError(localizer["Wrong password."]))); if (!string.Equals(form.Host?.Trim(), HostName, StringComparison.OrdinalIgnoreCase)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Type this server's host to restore it."])); + return UnprocessableEntity(new WebResult().Invalidate(11007.ToCodedError(localizer["Type this server's host to restore it."]))); var refused = await ServerRestore.Request(backups.Context(), id, admin.UserName, token); if (refused != default) - return UnprocessableEntity(new WebResult().Invalidate(refused)); + return UnprocessableEntity(new WebResult().Invalidate(11008.ToCodedError(refused))); logger.LogWarning("{Admin} asked to restore {Backup}", admin.UserName, id); await log.Write(admin.ID, Models.AdminActions.BackupRestore, Models.AdminTargets.Backup, id, id, token: token); return Accepted(); diff --git a/PrivaPub/Controllers/ClientToServer/DataController.cs b/PrivaPub/Controllers/ClientToServer/DataController.cs index 01c42f6..806ae06 100644 --- a/PrivaPub/Controllers/ClientToServer/DataController.cs +++ b/PrivaPub/Controllers/ClientToServer/DataController.cs @@ -40,7 +40,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(DataController)}.{nameof(Languages)}()"); - return BadRequest(result.Invalidate("Something went wrong.", exception: ex)); + return BadRequest(result.Invalidate(12001.ToCodedError("Something went wrong."), exception: ex)); } } } diff --git a/PrivaPub/Controllers/ClientToServer/DomainBlockController.cs b/PrivaPub/Controllers/ClientToServer/DomainBlockController.cs index 8ade9b3..11ab682 100644 --- a/PrivaPub/Controllers/ClientToServer/DomainBlockController.cs +++ b/PrivaPub/Controllers/ClientToServer/DomainBlockController.cs @@ -34,7 +34,7 @@ namespace PrivaPub.Controllers.ClientToServer { var domain = DomainBlocks.Normalise(form.Domain); if (!ModelState.IsValid || Uri.CheckHostName(domain) != UriHostNameType.Dns) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(13001.ToCodedError(localizer["Invalid model."]))); var block = await DB.Default.UpdateAndGet() .Match(b => b.Domain == domain) diff --git a/PrivaPub/Controllers/ClientToServer/EmojiAdminController.cs b/PrivaPub/Controllers/ClientToServer/EmojiAdminController.cs index 47ba6a2..188faa1 100644 --- a/PrivaPub/Controllers/ClientToServer/EmojiAdminController.cs +++ b/PrivaPub/Controllers/ClientToServer/EmojiAdminController.cs @@ -43,7 +43,7 @@ namespace PrivaPub.Controllers.ClientToServer return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default; } - IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status)); + IActionResult Refused(int status, string message, int errorCode) => StatusCode(status, new WebResult().Invalidate(errorCode.ToCodedError(localizer[message]), status)); [HttpGet, Route(ApiPaths.EmojiAdmin.GET_List)] public async Task List(CancellationToken token) @@ -64,10 +64,10 @@ namespace PrivaPub.Controllers.ClientToServer var key = form.Shortcode.ToLowerInvariant(); var existing = await DB.Default.Find().Match(e => e.Key == key).ExecuteFirstAsync(token); if (existing != default && (existing.DeletedAt == default || existing.Shortcode != form.Shortcode)) - return Refused(StatusCodes.Status409Conflict, "This shortcode is taken."); + return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.", 14004); var outcome = await media.EmojiImage(form.Shortcode, await Picture(token), token); if (!outcome.Ok) - return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); + return StatusCode(outcome.Status, new WebResult().Invalidate(14002.ToCodedError(outcome.Error), outcome.Status)); var now = DateTime.UtcNow; var emoji = existing ?? new LocalEmoji { Shortcode = form.Shortcode, Key = key, CreatedAt = now }; @@ -93,7 +93,7 @@ namespace PrivaPub.Controllers.ClientToServer if (!saved) { await media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token); - return Refused(StatusCodes.Status409Conflict, "This shortcode is taken."); + return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.", 14005); } await LocalEmojis.Reload(CancellationToken.None); var notes = new[] { existing != default ? "added again" : default, emoji.Disabled ? "disabled" : default, Animated(emoji) }.Where(n => n != default).ToList(); @@ -133,7 +133,7 @@ namespace PrivaPub.Controllers.ClientToServer { outcome = await media.EmojiImage(emoji.Shortcode, image, token); if (!outcome.Ok) - return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); + return StatusCode(outcome.Status, new WebResult().Invalidate(14003.ToCodedError(outcome.Error), outcome.Status)); Picture(emoji, outcome.Attachment, now); changed.Add("image"); } diff --git a/PrivaPub/Controllers/ClientToServer/GroupController.cs b/PrivaPub/Controllers/ClientToServer/GroupController.cs index 2d70bc7..c9e525d 100644 --- a/PrivaPub/Controllers/ClientToServer/GroupController.cs +++ b/PrivaPub/Controllers/ClientToServer/GroupController.cs @@ -63,18 +63,18 @@ namespace PrivaPub.Controllers.ClientToServer return Invalid(); var rootId = User.GetUserId(); if (!await users.PasswordMatches(rootId, form.Password, token)) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(15001.ToCodedError(localizer[RootUsersService.NoMatch]), StatusCodes.Status403Forbidden)); var owns = await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token); var group = owns ? await dbEntities.Groups.MatchID(form.GroupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token) : default; if (group == default) - return NotFound(new WebResult().Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound)); + return NotFound(new WebResult().Invalidate(15002.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound)); if (group.OwnerAvatarId != form.AvatarId) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer["Only the group's owner can delete it."], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(15003.ToCodedError(localizer["Only the group's owner can delete it."]), StatusCodes.Status403Forbidden)); await groups.Remove(group.ID, CancellationToken.None); return Ok(); } - IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + IActionResult Invalid() => BadRequest(new WebResult().Invalidate(15004.ToCodedError(localizer["Invalid model."]))); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } diff --git a/PrivaPub/Controllers/ClientToServer/InstanceAdminController.cs b/PrivaPub/Controllers/ClientToServer/InstanceAdminController.cs index 1361e74..88dcb3b 100644 --- a/PrivaPub/Controllers/ClientToServer/InstanceAdminController.cs +++ b/PrivaPub/Controllers/ClientToServer/InstanceAdminController.cs @@ -48,7 +48,7 @@ namespace PrivaPub.Controllers.ClientToServer return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default; } - IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status)); + IActionResult Refused(int status, string message, int errorCode) => StatusCode(status, new WebResult().Invalidate(errorCode.ToCodedError(localizer[message]), status)); #region settings @@ -68,10 +68,10 @@ namespace PrivaPub.Controllers.ClientToServer return Forbid(); var contact = Clean(form.ContactAccountId); if (contact != default && !await IsContactable(contact, token)) - return Refused(StatusCodes.Status422UnprocessableEntity, "The contact account must be a persona of this server."); + return Refused(StatusCodes.Status422UnprocessableEntity, "The contact account must be a persona of this server.", 16003); var rules = form.Rules ?? new(); if (rules.Count > ServerSettingsForm.MaxRules || rules.Any(r => string.IsNullOrWhiteSpace(r?.Text))) - return Refused(StatusCodes.Status422UnprocessableEntity, "Every rule needs its text, and there can be 50 at most."); + return Refused(StatusCodes.Status422UnprocessableEntity, "Every rule needs its text, and there can be 50 at most.", 16004); var changed = new List(); var ruleActs = new List<(string Action, ServerRule Rule)>(); @@ -182,7 +182,7 @@ namespace PrivaPub.Controllers.ClientToServer var file = Request.HasFormContentType ? (await Request.ReadFormAsync(token)).Files["file"] : default; var outcome = await media.ServerImage(Thumbnail, file, token); if (!outcome.Ok) - return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); + return StatusCode(outcome.Status, new WebResult().Invalidate(16002.ToCodedError(outcome.Error), outcome.Status)); var previous = default(string); var saved = await instanceSettings.Update(settings => { @@ -348,9 +348,9 @@ namespace PrivaPub.Controllers.ClientToServer IActionResult Invalid(AnnouncementForm form) => string.IsNullOrWhiteSpace(form.Text) - ? Refused(StatusCodes.Status422UnprocessableEntity, "An announcement needs its text.") + ? Refused(StatusCodes.Status422UnprocessableEntity, "An announcement needs its text.", 16005) : form.StartsAt != default && form.EndsAt != default && form.EndsAt < form.StartsAt - ? Refused(StatusCodes.Status422UnprocessableEntity, "An announcement can't end before it starts.") + ? Refused(StatusCodes.Status422UnprocessableEntity, "An announcement can't end before it starts.", 16006) : default; static AnnouncementDraft Draft(AnnouncementForm form) => new(form.Text, form.StartsAt, form.EndsAt, form.AllDay, form.IsPublished); @@ -400,11 +400,11 @@ namespace PrivaPub.Controllers.ClientToServer var id = form.AccountId?.Trim(); var picked = await Pickable(id, token); if (picked == default) - return Refused(StatusCodes.Status404NotFound, "No such account to suggest."); + return Refused(StatusCodes.Status404NotFound, "No such account to suggest.", 16007); if (instanceSettings.Current.StaffPicks.Contains(id)) - return Refused(StatusCodes.Status409Conflict, "This account is suggested already."); + return Refused(StatusCodes.Status409Conflict, "This account is suggested already.", 16008); if (instanceSettings.Current.StaffPicks.Count >= MaxStaffPicks) - return Refused(StatusCodes.Status422UnprocessableEntity, "40 accounts at most are suggested."); + return Refused(StatusCodes.Status422UnprocessableEntity, "40 accounts at most are suggested.", 16009); var saved = await instanceSettings.Update(settings => { if (!settings.StaffPicks.Contains(id)) @@ -495,13 +495,13 @@ namespace PrivaPub.Controllers.ClientToServer var address = form.Address?.Trim(); if (!Uri.TryCreate(address, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(uri.UserInfo) || !string.IsNullOrEmpty(uri.Fragment)) - return Refused(StatusCodes.Status422UnprocessableEntity, "A relay is named by the https address of its actor or its inbox."); + return Refused(StatusCodes.Status422UnprocessableEntity, "A relay is named by the https address of its actor or its inbox.", 16010); if (relays.Configured.Contains(address)) - return Refused(StatusCodes.Status409Conflict, "The configuration names this relay already."); + return Refused(StatusCodes.Status409Conflict, "The configuration names this relay already.", 16011); if (instanceSettings.Current.Relays.Contains(address)) return Ok(await RelayViews(instanceSettings.Current, token)); if (instanceSettings.Current.Relays.Count >= MaxSettingsRelays) - return Refused(StatusCodes.Status422UnprocessableEntity, "The settings name 20 relays at most."); + return Refused(StatusCodes.Status422UnprocessableEntity, "The settings name 20 relays at most.", 16012); var saved = await instanceSettings.Update(settings => { if (!settings.Relays.Contains(address)) @@ -521,7 +521,7 @@ namespace PrivaPub.Controllers.ClientToServer return Forbid(); address = address?.Trim(); if (relays.Configured.Contains(address)) - return Refused(StatusCodes.Status409Conflict, "This relay is named by the configuration (Federation:Relays): remove it there."); + return Refused(StatusCodes.Status409Conflict, "This relay is named by the configuration (Federation:Relays): remove it there.", 16013); if (string.IsNullOrEmpty(address) || !instanceSettings.Current.Relays.Contains(address)) return NotFound(); var saved = await instanceSettings.Update(settings => settings.Relays.Remove(address), admin.ID, token); diff --git a/PrivaPub/Controllers/ClientToServer/ModeratorController.cs b/PrivaPub/Controllers/ClientToServer/ModeratorController.cs index da18a1b..70e49fa 100644 --- a/PrivaPub/Controllers/ClientToServer/ModeratorController.cs +++ b/PrivaPub/Controllers/ClientToServer/ModeratorController.cs @@ -67,7 +67,7 @@ namespace PrivaPub.Controllers.ClientToServer form ??= new ResolveReportForm(); var action = string.IsNullOrWhiteSpace(form.Action) ? ModerationActions.None : form.Action.Trim().ToLowerInvariant(); if (!ModerationActions.IsResolution(action)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity)); + return UnprocessableEntity(new WebResult().Invalidate(17001.ToCodedError(localizer["Unknown moderation action."]), StatusCodes.Status422UnprocessableEntity)); var by = User.GetUserId(); var report = await DB.Default.Find().MatchID(id).ExecuteFirstAsync(token); if (report == default) @@ -81,7 +81,7 @@ namespace PrivaPub.Controllers.ClientToServer break; case ModerationActions.RemovePosts: if (report.PostIds.Count == 0) - return UnprocessableEntity(new WebResult().Invalidate(localizer["The report names no posts."], StatusCodes.Status422UnprocessableEntity)); + return UnprocessableEntity(new WebResult().Invalidate(17002.ToCodedError(localizer["The report names no posts."]), StatusCodes.Status422UnprocessableEntity)); foreach (var postId in report.PostIds) { var removed = await accountModeration.RemovePost(by, postId, form.Note, form.Warning, report.ID, token); @@ -172,7 +172,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task Moderate(ModerateAccountForm form, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(17003.ToCodedError(localizer["Invalid model."]))); var result = await accountModeration.Moderate(User.GetUserId(), form.AccountId, form.Action.Trim().ToLowerInvariant(), form.Note, form.Warning, default, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -182,7 +182,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task RemovePost(RemovePostForm form, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(17004.ToCodedError(localizer["Invalid model."]))); var result = await accountModeration.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token); return result.IsValid ? Ok() : StatusCode(result.StatusCode, result); } diff --git a/PrivaPub/Controllers/ClientToServer/PersonaArchiveController.cs b/PrivaPub/Controllers/ClientToServer/PersonaArchiveController.cs index 99f9b17..7452571 100644 --- a/PrivaPub/Controllers/ClientToServer/PersonaArchiveController.cs +++ b/PrivaPub/Controllers/ClientToServer/PersonaArchiveController.cs @@ -38,7 +38,7 @@ namespace PrivaPub.Controllers.ClientToServer return NotFound(); var state = await PersonaArchives.Of(avatarId, token); if (state.ExportState is "queued" or "running") - return Conflict(new WebResult().Invalidate("The archive is being made.")); + return Conflict(new WebResult().Invalidate(18001.ToCodedError("The archive is being made."))); state.ExportState = "queued"; state.ExportAskedAt = DateTime.UtcNow; state.ExportError = default; @@ -112,12 +112,12 @@ namespace PrivaPub.Controllers.ClientToServer return NotFound(); // a suspended persona may take its archive away, never bring one in (R6): an import follows, blocks and posts if (await DB.Default.Find().MatchID(avatarId).Match(a => a.SuspendedAt != null).ExecuteAnyAsync(token)) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate("This persona is suspended.", StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(18002.ToCodedError("This persona is suspended."), StatusCodes.Status403Forbidden)); var state = await PersonaArchives.Of(avatarId, token); if (state.ImportState is "queued" or "running") - return Conflict(new WebResult().Invalidate("An import is running.")); + return Conflict(new WebResult().Invalidate(18003.ToCodedError("An import is running."))); if (form.Parts.Count == 0 || form.Parts.Any(p => !PersonaArchives.Parts.Contains(p))) - return UnprocessableEntity(new WebResult().Invalidate("Choose what to import.")); + return UnprocessableEntity(new WebResult().Invalidate(18004.ToCodedError("Choose what to import."))); if (transfers.Owner(form.UploadId) != User.GetUserId()) return NotFound(); var path = transfers.Take(form.UploadId, PersonaArchives.Folder(backups.Root, avatarId), $"import-{form.UploadId}.zip"); @@ -128,7 +128,7 @@ namespace PrivaPub.Controllers.ClientToServer if (archive?.Has("actor.json") != true) { System.IO.File.Delete(path); - return UnprocessableEntity(new WebResult().Invalidate(refused ?? "the archive has no actor.json")); + return UnprocessableEntity(new WebResult().Invalidate(18005.ToCodedError(refused ?? "the archive has no actor.json"))); } state.ImportState = "queued"; state.ImportAskedAt = DateTime.UtcNow; diff --git a/PrivaPub/Controllers/ClientToServer/PostController.cs b/PrivaPub/Controllers/ClientToServer/PostController.cs index ab1c266..e90c540 100644 --- a/PrivaPub/Controllers/ClientToServer/PostController.cs +++ b/PrivaPub/Controllers/ClientToServer/PostController.cs @@ -45,7 +45,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task InsertDm(InsertDmForm form, CancellationToken token) => !ModelState.IsValid ? Invalid() : Answer(await postsService.InsertDm(User.GetUserId(), form, token)); - IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + IActionResult Invalid() => BadRequest(new WebResult().Invalidate(19001.ToCodedError(localizer["Invalid model."]))); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } diff --git a/PrivaPub/Controllers/ClientToServer/PrivateAvatarController.cs b/PrivaPub/Controllers/ClientToServer/PrivateAvatarController.cs index eed5534..6509612 100644 --- a/PrivaPub/Controllers/ClientToServer/PrivateAvatarController.cs +++ b/PrivaPub/Controllers/ClientToServer/PrivateAvatarController.cs @@ -30,7 +30,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(20001.ToCodedError(localizer["Invalid model."]))); try { model.RootId = User.GetUserId(); @@ -43,7 +43,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(20002.ToCodedError(localizer["Something went wrong."]))); } } @@ -54,13 +54,13 @@ namespace PrivaPub.Controllers.ClientToServer [FromServices] Services.IPersonaRemoval personas, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(20003.ToCodedError(localizer["Invalid model."]))); var rootId = User.GetUserId(); if (!await users.PasswordMatches(rootId, form.Password, token)) - return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(20004.ToCodedError(localizer[Services.RootUsersService.NoMatch]), StatusCodes.Status403Forbidden)); if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token) || !await personas.Remove(form.AvatarId, CancellationToken.None)) - return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound)); + return NotFound(new WebResult().Invalidate(20005.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound)); return Ok(); } @@ -70,7 +70,7 @@ namespace PrivaPub.Controllers.ClientToServer { var avatar = await OwnPersona(avatarId, dbEntities, token); return avatar == default - ? NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound)) + ? NotFound(new WebResult().Invalidate(20006.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound)) : Ok(PreferencesOf(avatar)); } @@ -78,12 +78,12 @@ namespace PrivaPub.Controllers.ClientToServer public async Task SavePreferences(PersonaPreferencesForm form, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(20007.ToCodedError(localizer["Invalid model."]))); if (!Models.User.ExpandMediaModes.IsKnown(form.ExpandMedia)) - return UnprocessableEntity(new WebResult().Invalidate(localizer["Media are shown as default, show_all or hide_all."], StatusCodes.Status422UnprocessableEntity)); + return UnprocessableEntity(new WebResult().Invalidate(20008.ToCodedError(localizer["Media are shown as default, show_all or hide_all."]), StatusCodes.Status422UnprocessableEntity)); var avatar = await OwnPersona(form.AvatarId, dbEntities, token); if (avatar == default) - return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound)); + return NotFound(new WebResult().Invalidate(20009.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound)); await MongoDB.Entities.DB.Default.Update().MatchID(avatar.ID) .Modify(a => a.Settings.ExpandMedia, form.ExpandMedia) .Modify(a => a.Settings.ExpandSpoilers, form.ExpandSpoilers) @@ -114,7 +114,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(20010.ToCodedError(localizer["Invalid model."]))); try { model.RootId = User.GetUserId(); @@ -127,7 +127,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(20011.ToCodedError(localizer["Something went wrong."]))); } } diff --git a/PrivaPub/Controllers/ClientToServer/RootUserController.cs b/PrivaPub/Controllers/ClientToServer/RootUserController.cs index 0559f42..3c3022d 100644 --- a/PrivaPub/Controllers/ClientToServer/RootUserController.cs +++ b/PrivaPub/Controllers/ClientToServer/RootUserController.cs @@ -47,9 +47,9 @@ namespace PrivaPub.Controllers.ClientToServer if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); var result = new WebResult(); if (!registrations.CurrentValue.IsOpen) - return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(localizer[RegistrationOptions.ClosedMessage], StatusCodes.Status403Forbidden)); + return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(21001.ToCodedError(localizer[RegistrationOptions.ClosedMessage]), StatusCodes.Status403Forbidden)); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21002.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.SignUpAsync(signUpForm, token); @@ -63,7 +63,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21003.ToCodedError(localizer["Something went wrong."]))); } } @@ -73,7 +73,7 @@ namespace PrivaPub.Controllers.ClientToServer if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21004.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.LoginAsync(loginForm, token); @@ -89,7 +89,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21005.ToCodedError(localizer["Something went wrong."]))); } } @@ -98,7 +98,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21006.ToCodedError(localizer["Invalid model."]))); try { var invitation = await groupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token); @@ -108,7 +108,7 @@ namespace PrivaPub.Controllers.ClientToServer var avatarUserName = signUpForm.AvatarUserName?.Trim().ToLowerInvariant(); var personaProblem = await PersonaProblem(avatarUserName, signUpForm.UserName, token); if (personaProblem != default) - return BadRequest(result.Invalidate(personaProblem)); + return BadRequest(result.Invalidate(21007.ToCodedError(personaProblem))); result = await usersService.SignUpAsync(signUpForm, token); if (!result.IsValid) @@ -133,7 +133,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21008.ToCodedError(localizer["Something went wrong."]))); } } @@ -142,7 +142,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21009.ToCodedError(localizer["Invalid model."]))); try { var invitation = await groupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token); @@ -163,7 +163,7 @@ namespace PrivaPub.Controllers.ClientToServer { var personaProblem = await PersonaProblem(avatarUserName, user.UserName, token); if (personaProblem != default) - return BadRequest(new WebResult().Invalidate(personaProblem)); + return BadRequest(new WebResult().Invalidate(21010.ToCodedError(personaProblem))); var inserted = await InsertPersona(user.ID, avatarUserName, loginForm.AvatarName, token); if (!inserted.IsValid) return StatusCode(inserted.StatusCode, inserted); @@ -184,7 +184,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21011.ToCodedError(localizer["Something went wrong."]))); } } @@ -201,7 +201,7 @@ namespace PrivaPub.Controllers.ClientToServer if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21012.ToCodedError(localizer["Invalid model."]))); var claimed = false; var adminId = default(string); try @@ -212,7 +212,7 @@ namespace PrivaPub.Controllers.ClientToServer var avatarUserName = setupForm.AvatarUserName?.Trim().ToLowerInvariant(); var personaProblem = await PersonaProblem(avatarUserName, setupForm.UserName, token); if (personaProblem != default) - return BadRequest(result.Invalidate(personaProblem)); + return BadRequest(result.Invalidate(21013.ToCodedError(personaProblem))); claimed = await ServerSetup.Claim(token); if (!claimed) @@ -242,13 +242,13 @@ namespace PrivaPub.Controllers.ClientToServer logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()"); if (claimed && adminId == default) await ServerSetup.Release(CancellationToken.None); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21014.ToCodedError(localizer["Something went wrong."]))); } } IActionResult SetUpAlready() => StatusCode(StatusCodes.Status403Forbidden, - new WebResult().Invalidate(localizer["This server is already set up: joining it takes a group invitation."], StatusCodes.Status403Forbidden)); + new WebResult().Invalidate(21015.ToCodedError(localizer["This server is already set up: joining it takes a group invitation."]), StatusCodes.Status403Forbidden)); Task InsertPersona(string rootId, string avatarUserName, string avatarName, CancellationToken token = default) => avatarUsersService.InsertAvatar(new InsertAvatarForm @@ -288,7 +288,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21016.ToCodedError(localizer["Something went wrong."]))); } } @@ -304,7 +304,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21017.ToCodedError(localizer["Something went wrong."]))); } } @@ -313,7 +313,7 @@ namespace PrivaPub.Controllers.ClientToServer [HttpPost, Route(ApiPaths.RootUser.POST_UpdateUser), Authorize(Policy = Policies.IsUser)] public IActionResult UpdateUser(UserForm userEmailForm) => StatusCode(StatusCodes.Status422UnprocessableEntity, - new WebResult().Invalidate(localizer["Changing the address takes your password and a code sent to it."], StatusCodes.Status422UnprocessableEntity)); + new WebResult().Invalidate(21018.ToCodedError(localizer["Changing the address takes your password and a code sent to it."]), StatusCodes.Status422UnprocessableEntity)); [HttpGet, Route(ApiPaths.RootUser.GET_Account), Authorize(Policy = Policies.IsUser)] public async Task Account(CancellationToken token = default) @@ -326,7 +326,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task RequestEmailChange(EmailChangeForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21019.ToCodedError(localizer["Invalid model."]))); var result = await usersService.RequestEmailChangeAsync(User.GetUserId(), form, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -335,7 +335,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task VerifyEmail(EmailCodeForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21020.ToCodedError(localizer["Invalid model."]))); var result = await usersService.VerifyEmailAsync(User.GetUserId(), form.Code, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -344,7 +344,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task TotpSetup(PasswordForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21021.ToCodedError(localizer["Invalid model."]))); var result = await usersService.TotpSetupAsync(User.GetUserId(), form.Password, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -354,7 +354,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task TotpEnable(TotpCodeForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21022.ToCodedError(localizer["Invalid model."]))); var result = await usersService.TotpEnableAsync(User.GetUserId(), form.Code, token); if (!result.IsValid) return StatusCode(result.StatusCode, result); @@ -366,7 +366,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task TotpDisable(TotpDisableForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21023.ToCodedError(localizer["Invalid model."]))); var result = await usersService.TotpDisableAsync(User.GetUserId(), form.Password, form.Code, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -375,7 +375,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task RemoveEmail(PasswordForm form, CancellationToken token = default) { if (!ModelState.IsValid) - return BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + return BadRequest(new WebResult().Invalidate(21024.ToCodedError(localizer["Invalid model."]))); var result = await usersService.RemoveEmailAsync(User.GetUserId(), form.Password, token); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } @@ -385,7 +385,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21025.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.UpdateUserSettingsAsync(userSettings, User.GetUserId(), token); @@ -397,7 +397,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21026.ToCodedError(localizer["Something went wrong."]))); } } @@ -406,7 +406,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21027.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId(), token); @@ -420,7 +420,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21028.ToCodedError(localizer["Something went wrong."]))); } } @@ -447,7 +447,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21029.ToCodedError(localizer["Something went wrong."]))); } } @@ -456,7 +456,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21030.ToCodedError(localizer["Invalid model."]))); try { var host = string.IsNullOrEmpty(appConfiguration.CurrentValue.FrontendBaseAddress) @@ -471,7 +471,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21031.ToCodedError(localizer["Something went wrong."]))); } } @@ -494,7 +494,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21032.ToCodedError(localizer["Something went wrong."]))); } } @@ -503,7 +503,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21033.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.ChangePassword(newPasswordForm, token); @@ -515,7 +515,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21034.ToCodedError(localizer["Something went wrong."]))); } } @@ -524,7 +524,7 @@ namespace PrivaPub.Controllers.ClientToServer { var result = new WebResult(); if (!ModelState.IsValid) - return BadRequest(result.Invalidate(localizer["Invalid model."])); + return BadRequest(result.Invalidate(21035.ToCodedError(localizer["Invalid model."]))); try { result = await usersService.RemoveSelfAsync(User.GetUserId(), form.Password, token); @@ -533,7 +533,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21036.ToCodedError(localizer["Something went wrong."]))); } } @@ -549,7 +549,7 @@ namespace PrivaPub.Controllers.ClientToServer { var user = await dbEntities.RootUsers.MatchID(User.GetUserId()).ExecuteFirstAsync(token); if (user is not { IsBanned: false, DeletedAt: null }) - return Unauthorized(result.Invalidate(localizer["Unauthorized."], StatusCodes.Status401Unauthorized)); + return Unauthorized(result.Invalidate(21037.ToCodedError(localizer["Unauthorized."]), StatusCodes.Status401Unauthorized)); result = await usersService.GetUserSettingsAsync(user.ID, token: token); if (!result.IsValid) return StatusCode(result.StatusCode, result); @@ -559,7 +559,7 @@ namespace PrivaPub.Controllers.ClientToServer catch (Exception ex) { logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()"); - return BadRequest(result.Invalidate(localizer["Something went wrong."])); + return BadRequest(result.Invalidate(21038.ToCodedError(localizer["Something went wrong."]))); } } diff --git a/PrivaPub/Controllers/ClientToServer/SocialController.cs b/PrivaPub/Controllers/ClientToServer/SocialController.cs index 363ae18..69c4882 100644 --- a/PrivaPub/Controllers/ClientToServer/SocialController.cs +++ b/PrivaPub/Controllers/ClientToServer/SocialController.cs @@ -29,7 +29,7 @@ namespace PrivaPub.Controllers.ClientToServer public async Task Following([FromQuery] string avatarId, CancellationToken token) => Answer(await follows.Followings(User.GetUserId(), avatarId, token)); - IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."])); + IActionResult Invalid() => BadRequest(new WebResult().Invalidate(22001.ToCodedError(localizer["Invalid model."]))); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); } diff --git a/PrivaPub/Domain/Moderation/AccountModeration.cs b/PrivaPub/Domain/Moderation/AccountModeration.cs index 93a043e..c74a525 100644 --- a/PrivaPub/Domain/Moderation/AccountModeration.cs +++ b/PrivaPub/Domain/Moderation/AccountModeration.cs @@ -69,7 +69,7 @@ namespace PrivaPub.Domain.Moderation { var result = new WebResult(); if (!ModerationActions.IsAccountAction(action)) - return result.Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity); + return result.Invalidate(23001.ToCodedError(localizer["Unknown moderation action."]), StatusCodes.Status422UnprocessableEntity); try { var avatar = string.IsNullOrEmpty(accountId) ? default : await dbEntities.Avatars.MatchID(accountId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token); @@ -80,14 +80,14 @@ namespace PrivaPub.Domain.Moderation } var account = string.IsNullOrEmpty(accountId) ? default : await dbEntities.ForeignAvatars.MatchID(accountId).ExecuteFirstAsync(token); if (account == default) - return result.Invalidate(localizer["Account not found."], StatusCodes.Status404NotFound); + return result.Invalidate(23002.ToCodedError(localizer["Account not found."]), StatusCodes.Status404NotFound); result.Data = await Remote(byRootId, account, action, note, reportId, token); return result; } catch (Exception ex) { logger.LogError(ex, "{Service}.{Method}({Action})", nameof(AccountModeration), nameof(Moderate), action); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(23003.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -213,18 +213,18 @@ namespace PrivaPub.Domain.Moderation { var post = string.IsNullOrEmpty(postId) ? default : await dbEntities.Posts.MatchID(postId).ExecuteFirstAsync(token); if (post == default || post.DeletedAt.HasValue || post.ModeratedAt.HasValue) - return result.Invalidate(localizer["Post not found."], StatusCodes.Status404NotFound); + return result.Invalidate(23004.ToCodedError(localizer["Post not found."]), StatusCodes.Status404NotFound); if (!post.IsFederatedCopy) { var author = await localActors.FindById(LocalActorKind.Person, post.GroupUserId, token); if (author == default) - return result.Invalidate(localizer["Post not found."], StatusCodes.Status404NotFound); + return result.Invalidate(23005.ToCodedError(localizer["Post not found."]), StatusCodes.Status404NotFound); // deleted as its author deletes it: emptied, out of every timeline, and a Delete to its audience (but from a // suspended persona, which delivers nothing) var outcome = await statuses.Remove(author, post.ID, CancellationToken.None); if (!outcome.Ok) - return result.Invalidate(localizer["Post not found."], outcome.Status); + return result.Invalidate(23006.ToCodedError(localizer["Post not found."]), outcome.Status); await Social.Notifications.Warn(author.Id, author.Uri, "delete_statuses", warning, new[] { post.ID }, token); await log.Write(byRootId, AdminActions.PostRemove, AdminTargets.Post, post.ID, $"@{author.Handle}: {post.ObjectURI}", reportId, note, CancellationToken.None); @@ -240,7 +240,7 @@ namespace PrivaPub.Domain.Moderation catch (Exception ex) { logger.LogError(ex, "{Service}.{Method}()", nameof(AccountModeration), nameof(RemovePost)); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(23007.ToCodedError(localizer["Something went wrong."]), exception: ex); } } diff --git a/PrivaPub/Domain/Social/FollowService.cs b/PrivaPub/Domain/Social/FollowService.cs index d6101b7..02b6146 100644 --- a/PrivaPub/Domain/Social/FollowService.cs +++ b/PrivaPub/Domain/Social/FollowService.cs @@ -53,17 +53,17 @@ namespace PrivaPub.Domain.Social { var follower = await OwnedAvatar(rootUserId, form.AvatarId, token); if (follower == default) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(24001.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var following = await FollowAs(follower, form.Target, true, token: token); if (following == default) - return result.Invalidate(localizer["Account not found."], StatusCodes.Status404NotFound); + return result.Invalidate(24002.ToCodedError(localizer["Account not found."]), StatusCodes.Status404NotFound); result.Data = ToView(following); return result; } catch (Exception ex) { logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(24003.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -74,14 +74,14 @@ namespace PrivaPub.Domain.Social { var follower = await OwnedAvatar(rootUserId, form.AvatarId, token); if (follower == default) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(24004.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); await UnfollowAs(follower, form.Target, token); return result; } catch (Exception ex) { logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(24005.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -251,7 +251,7 @@ namespace PrivaPub.Domain.Social var result = new WebResult(); var follower = await OwnedAvatar(rootUserId, avatarId, token); if (follower == default) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(24006.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); result.Data = (await dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token)) .Select(ToView).ToList(); return result; diff --git a/PrivaPub/Domain/Timelines/TimelineService.cs b/PrivaPub/Domain/Timelines/TimelineService.cs index d065f81..bbad985 100644 --- a/PrivaPub/Domain/Timelines/TimelineService.cs +++ b/PrivaPub/Domain/Timelines/TimelineService.cs @@ -31,7 +31,7 @@ namespace PrivaPub.Domain.Timelines { var result = new WebResult(); if (!await Owns(rootUserId, avatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(25001.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var query = dbEntities.TimelineEntries.Match(e => e.AvatarId == avatarId); if (!string.IsNullOrEmpty(maxId)) @@ -60,7 +60,7 @@ namespace PrivaPub.Domain.Timelines { var result = new WebResult(); if (!await Owns(rootUserId, avatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(25002.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var query = dbEntities.Notifications.Match(n => n.AvatarId == avatarId); if (!string.IsNullOrEmpty(maxId)) @@ -84,7 +84,7 @@ namespace PrivaPub.Domain.Timelines { var result = new WebResult(); if (!await Owns(rootUserId, avatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(25003.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); await DB.Default.Update().Match(n => n.AvatarId == avatarId && !n.IsRead).Modify(n => n.IsRead, true).ExecuteAsync(token); return result; } diff --git a/PrivaPub/ErrUtility.cs b/PrivaPub/ErrUtility.cs new file mode 100644 index 0000000..6457331 --- /dev/null +++ b/PrivaPub/ErrUtility.cs @@ -0,0 +1,6 @@ +namespace PrivaPub; + +public static class ErrUtility +{ + public static string ToCodedError(this int errorCode, string errorMessage) => $"[ERR{errorCode:D7}] {errorMessage}"; +} diff --git a/PrivaPub/PrivaPub.csproj b/PrivaPub/PrivaPub.csproj index 70eed7b..9bf9029 100644 --- a/PrivaPub/PrivaPub.csproj +++ b/PrivaPub/PrivaPub.csproj @@ -4,6 +4,7 @@ net10.0 disable enable + true diff --git a/PrivaPub/Services/ClientToServer/Private/IPrivateAvatarUsersService.cs b/PrivaPub/Services/ClientToServer/Private/IPrivateAvatarUsersService.cs index e105c4a..0087ea9 100644 --- a/PrivaPub/Services/ClientToServer/Private/IPrivateAvatarUsersService.cs +++ b/PrivaPub/Services/ClientToServer/Private/IPrivateAvatarUsersService.cs @@ -35,13 +35,13 @@ namespace PrivaPub.Services.ClientToServer.Private { 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(26001.ToCodedError(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]); + return result.Invalidate(26002.ToCodedError(localizer["The username '{0}' is already taken.", userName])); if (!await IsValidRootUser(form.RootId, token)) - return result.Invalidate(localizer["You can't do this action because of your account status."]); + return result.Invalidate(26003.ToCodedError(localizer["You can't do this action because of your account status."])); var (privateKey, publicKey) = Keys.NewKeyPair(); var newAvatar = new Avatar @@ -59,7 +59,7 @@ namespace PrivaPub.Services.ClientToServer.Private 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]); + return result.Invalidate(26004.ToCodedError(localizer["The username '{0}' is already taken.", userName])); if (form.Settings is { IsDefault: false }) Apply(newAvatar.Settings, form.Settings); @@ -77,7 +77,7 @@ namespace PrivaPub.Services.ClientToServer.Private catch (Exception ex) { logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(InsertAvatar)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(26005.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -87,20 +87,20 @@ namespace PrivaPub.Services.ClientToServer.Private try { if (!await IsValidRootUser(form.RootId, token)) - return result.Invalidate(localizer["You can't do this action because of your account status."]); + return result.Invalidate(26006.ToCodedError(localizer["You can't do this action because of your account status."])); var owns = await dbEntities.RootToAvatars .Match(ra => ra.RootId == form.RootId && ra.AvatarId == form.AvatarId) .ExecuteAnyAsync(token); if (!owns) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(26007.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); 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(26008.ToCodedError(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(26009.ToCodedError(localizer["This persona is suspended."]), StatusCodes.Status403Forbidden); avatar.Name = form.Name; avatar.Biography = form.Biography; @@ -119,7 +119,7 @@ namespace PrivaPub.Services.ClientToServer.Private catch (Exception ex) { logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(UpdateAvatar)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(26010.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -140,7 +140,7 @@ namespace PrivaPub.Services.ClientToServer.Private catch (Exception ex) { logger.LogError(ex, $"{nameof(PrivateAvatarUsersService)}.{nameof(GetRootAvatars)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(26011.ToCodedError(localizer["Something went wrong."]), exception: ex); } } diff --git a/PrivaPub/Services/GroupUsersService.cs b/PrivaPub/Services/GroupUsersService.cs index 771cd87..288eddc 100644 --- a/PrivaPub/Services/GroupUsersService.cs +++ b/PrivaPub/Services/GroupUsersService.cs @@ -45,7 +45,7 @@ namespace PrivaPub.Services try { if (!await OwnsAvatar(rootUserId, avatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(27001.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var groups = await dbEntities.Groups .Match(g => !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == avatarId)) @@ -56,7 +56,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetGroups)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27002.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -66,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(27003.ToCodedError(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]); + return result.Invalidate(27004.ToCodedError(localizer["The username '{0}' is already taken.", userName])); var (privateKey, publicKey) = Keys.NewKeyPair(); var group = new GroupEntity @@ -92,7 +92,7 @@ namespace PrivaPub.Services }; 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]); + return result.Invalidate(27005.ToCodedError(localizer["The username '{0}' is already taken.", userName])); var actor = localActors.FromGroup(group); group.Url = actor.Uri; group.InboxURL = actor.Inbox; @@ -105,7 +105,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(InsertGroup)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27006.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -116,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(27007.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound); if (form.Name != default) group.Name = form.Name; @@ -143,7 +143,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(UpdateGroup)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27008.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -153,13 +153,13 @@ namespace PrivaPub.Services try { if (!await OwnsAvatar(rootUserId, form.AvatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(27009.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); 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(27010.ToCodedError(localizer["Invalid invitation."]), StatusCodes.Status404NotFound); if (!string.IsNullOrEmpty(group.HashedInvitationPassword)) { @@ -167,7 +167,7 @@ namespace PrivaPub.Services ? (false, false) : passwordHasher.Check(group.HashedInvitationPassword, form.InvitationPassword); if (!verified) - return result.Invalidate(localizer["Invalid password."], StatusCodes.Status406NotAcceptable); + return result.Invalidate(27011.ToCodedError(localizer["Invalid password."]), StatusCodes.Status406NotAcceptable); } if (!group.Members.Any(m => !m.IsForeign && m.AvatarId == form.AvatarId)) @@ -184,7 +184,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(JoinGroup)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27012.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -221,13 +221,13 @@ namespace PrivaPub.Services try { if (!await OwnsAvatar(rootUserId, form.AvatarId, token)) - return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound); + return result.Invalidate(27013.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); 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(27014.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound); if (group.OwnerAvatarId == form.AvatarId) - return result.Invalidate(localizer["The owner cannot leave the group."]); + return result.Invalidate(27015.ToCodedError(localizer["The owner cannot leave the group."])); group.Members.RemoveAll(m => !m.IsForeign && m.AvatarId == form.AvatarId); group.UpdatedAt = DateTime.UtcNow; @@ -243,7 +243,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(LeaveGroup)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27016.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -254,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(27017.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound); 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(27018.ToCodedError(localizer["Request not found."]), StatusCodes.Status404NotFound); follower.IsAccepted = true; await DB.Default.SaveAsync(follower, token); @@ -285,7 +285,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(ApproveMember)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27019.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -296,10 +296,10 @@ namespace PrivaPub.Services ? default : 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(27020.ToCodedError(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); + return result.Invalidate(27021.ToCodedError(localizer["Invalid password."]), StatusCodes.Status406NotAcceptable); result.Data = group; return result; } @@ -313,7 +313,7 @@ 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(27022.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound); var members = new List(); foreach (var member in group.Members) @@ -346,7 +346,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(GetMembers)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27023.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -370,12 +370,12 @@ 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(27024.ToCodedError(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(27025.ToCodedError(localizer["Request not found."]), StatusCodes.Status404NotFound); await DB.Default.DeleteAsync(request.ID); await RejectFollow(group, request, token); return result; @@ -383,7 +383,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RejectMember)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27026.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -396,15 +396,15 @@ 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(27027.ToCodedError(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(27028.ToCodedError(localizer["Member not found."]), StatusCodes.Status404NotFound); if (member.Role == GroupRole.Owner) - return result.Invalidate(localizer["The owner cannot leave the group."]); + return result.Invalidate(27029.ToCodedError(localizer["The owner cannot leave the group."])); group.Members.Remove(member); group.UpdatedAt = DateTime.UtcNow; @@ -426,7 +426,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(GroupUsersService)}.{nameof(RemoveMember)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(27030.ToCodedError(localizer["Something went wrong."]), exception: ex); } } diff --git a/PrivaPub/Services/JwtEvents.cs b/PrivaPub/Services/JwtEvents.cs index c9c03f6..ee75463 100644 --- a/PrivaPub/Services/JwtEvents.cs +++ b/PrivaPub/Services/JwtEvents.cs @@ -53,7 +53,7 @@ namespace PrivaPub.Services try { var localizer = context.HttpContext.RequestServices.GetRequiredService>(); - var webResult = new WebResult().Invalidate(localizer["Unauthorized."], StatusCodes.Status401Unauthorized); + var webResult = new WebResult().Invalidate(28001.ToCodedError(localizer["Unauthorized."]), StatusCodes.Status401Unauthorized); context.Response.ContentType = contentType; await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult, Web))); } @@ -69,7 +69,7 @@ namespace PrivaPub.Services try { var localizer = context.HttpContext.RequestServices.GetRequiredService>(); - var webResult = new WebResult().Invalidate(localizer["Forbidden."], StatusCodes.Status403Forbidden); + var webResult = new WebResult().Invalidate(28002.ToCodedError(localizer["Forbidden."]), StatusCodes.Status403Forbidden); context.Response.ContentType = contentType; await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult, Web))); } diff --git a/PrivaPub/Services/PostsService.cs b/PrivaPub/Services/PostsService.cs index e7c11a9..3906eb4 100644 --- a/PrivaPub/Services/PostsService.cs +++ b/PrivaPub/Services/PostsService.cs @@ -49,7 +49,7 @@ 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(29001.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); return await Answer(() => statuses.Publish(author, new StatusDraft { Text = form.Text, @@ -69,7 +69,7 @@ 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(29002.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var result = await Answer(() => statuses.Remove(author, form.PostId, token), nameof(DeletePost), token); result.Data = default; return result; @@ -79,7 +79,7 @@ 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(29003.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); return await Answer(() => statuses.Edit(author, form.PostId, new StatusDraft { Text = form.Text, @@ -96,7 +96,7 @@ 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(29004.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); var query = dbEntities.Posts; if (string.IsNullOrEmpty(groupId)) @@ -107,7 +107,7 @@ namespace PrivaPub.Services .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(29005.ToCodedError(localizer["Group not found."]), StatusCodes.Status404NotFound); query.Match(p => p.GroupId == groupId); } @@ -118,7 +118,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetPosts)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(29006.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -126,9 +126,9 @@ 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(29007.ToCodedError(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 new WebResult().Invalidate(29008.ToCodedError(localizer["At least one recipient is required."])); return await Answer(() => statuses.Publish(author, new StatusDraft { Text = form.Text, @@ -146,7 +146,7 @@ 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(29009.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound); if (string.IsNullOrEmpty(dmGroupId)) { @@ -167,7 +167,7 @@ namespace PrivaPub.Services .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(29010.ToCodedError(localizer["Conversation not found."]), StatusCodes.Status404NotFound); var dms = await dbEntities.Posts .Match(p => p.ConversationId == dmGroupId && p.Visibility == PostVisibility.Direct) @@ -181,7 +181,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(PostsService)}.{nameof(GetDms)}"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(29011.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -192,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(29012.ToCodedError(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(29013.ToCodedError(localizer["Invalid model."])); var query = new MongoDB.Bson.BsonDocument { @@ -223,14 +223,14 @@ namespace PrivaPub.Services { var outcome = await action(); if (!outcome.Ok) - return result.Invalidate(localizer[outcome.Error], outcome.Status); + return result.Invalidate(29014.ToCodedError(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); + return result.Invalidate(29015.ToCodedError(localizer["Something went wrong."]), exception: ex); } } diff --git a/PrivaPub/Services/RootUsersService.cs b/PrivaPub/Services/RootUsersService.cs index 8a4a807..671a9f3 100644 --- a/PrivaPub/Services/RootUsersService.cs +++ b/PrivaPub/Services/RootUsersService.cs @@ -43,7 +43,7 @@ namespace PrivaPub.Services { signUpForm.UserName = signUpForm.UserName.ToLower(); if (await dbEntities.RootUsers.Match(u => u.UserName == signUpForm.UserName).ExecuteAnyAsync(token)) - return result.Invalidate(localizer["Username '{0}' already taken.", signUpForm.UserName]); + return result.Invalidate(30001.ToCodedError(localizer["Username '{0}' already taken.", signUpForm.UserName])); var signUpPasswordHashed = passwordHasher.Hash(signUpForm.Password); var newUser = new RootUser @@ -74,7 +74,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SignUpAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30002.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -89,16 +89,16 @@ namespace PrivaPub.Services 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(30003.ToCodedError(localizer[NoMatch])); if (user.IsBanned) - return result.Invalidate(localizer["User '{0}' banned.", user.UserName]); + return result.Invalidate(30004.ToCodedError(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(30005.ToCodedError(localizer[TwoFactor.CodeNeeded]), StatusCodes.Status428PreconditionRequired); if (!await TwoFactor.Consume(user, loginForm.OneTimeCode, CancellationToken.None)) - return result.Invalidate(localizer[TwoFactor.CodeInvalid]); + return result.Invalidate(30006.ToCodedError(localizer[TwoFactor.CodeInvalid])); } // hashed again at today's iterations; matched on the old hash, so two sign-ins at once never undo each other @@ -122,7 +122,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(LoginAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30007.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -133,12 +133,12 @@ namespace PrivaPub.Services { var isSupportedLanguage = appConfigurationService.AppConfiguration.SupportedLanguages.Contains(userSettings.LanguageCode); if (!isSupportedLanguage) - return result.Invalidate(localizer["Language code '{0}' unsupported.", userSettings.LanguageCode]); + return result.Invalidate(30008.ToCodedError(localizer["Language code '{0}' unsupported.", userSettings.LanguageCode])); 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(30009.ToCodedError(localizer["Language code '{0}' doesn't exist.", userSettings.LanguageCode])); var language = await dbEntities.Languages.Match(l => l.International2Code == userSettings.LanguageCode) .ExecuteFirstAsync(token); @@ -161,7 +161,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserSettingsAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30010.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -173,12 +173,12 @@ namespace PrivaPub.Services 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(30011.ToCodedError(localizer["Username '{0}' not found.", userId])); var (verified, needsUpgrade) = passwordHasher.Check(user.HashedPassword, userPasswordForm.OldPassword); if (!verified) - return result.Invalidate(localizer["Wrong password."]); + return result.Invalidate(30012.ToCodedError(localizer["Wrong password."])); await DB.Default.Update().MatchID(user.ID) .Modify(u => u.HashedPassword, passwordHasher.Hash(userPasswordForm.NewPassword)) @@ -193,7 +193,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserPasswordAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30013.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -207,13 +207,13 @@ namespace PrivaPub.Services if (await removal.Remove(id, CancellationToken.None)) removed++; if (removed == 0) - return result.Invalidate(localizer["User already deleted."]); + return result.Invalidate(30014.ToCodedError(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); + return result.Invalidate(30015.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -226,14 +226,14 @@ namespace PrivaPub.Services 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); + return result.Invalidate(30016.ToCodedError(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); + return result.Invalidate(30017.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -260,7 +260,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(BanUserAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30018.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -279,7 +279,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UnbanUserAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30019.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -290,7 +290,7 @@ namespace PrivaPub.Services { var user = await dbEntities.RootUsers.MatchID(userId).ExecuteFirstAsync(token); if (user == default) - return result.Invalidate(localizer["User not found."], StatusCodes.Status404NotFound); + return result.Invalidate(30020.ToCodedError(localizer["User not found."]), StatusCodes.Status404NotFound); if (loginForm != default && loginForm.ThemeIsDarkMode != user.Settings.ThemeIsDarkMode) { @@ -307,7 +307,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(GetUserSettingsAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30021.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -332,7 +332,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SetupAndSendRecoveryEmail)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30022.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -353,7 +353,7 @@ namespace PrivaPub.Services } catch (Exception ex) { - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30023.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -367,7 +367,7 @@ namespace PrivaPub.Services var user = recovery == default ? default : 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(30024.ToCodedError(localizer["Invalid recovery code."]), StatusCodes.Status404NotFound); await DB.Default.Update().MatchID(user.ID) .Modify(u => u.HashedPassword, passwordHasher.Hash(newPasswordForm.NewPassword)) @@ -380,7 +380,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(ChangePassword)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30025.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -407,7 +407,7 @@ namespace PrivaPub.Services { 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(30026.ToCodedError(localizer["User not found."]), StatusCodes.Status404NotFound); var now = DateTime.UtcNow; var pending = await DB.Default.Find().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync(token); result.Data = new ViewAccount @@ -425,7 +425,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(AccountAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30027.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -439,7 +439,7 @@ namespace PrivaPub.Services 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(30028.ToCodedError(localizer["Wrong password."]), StatusCodes.Status403Forbidden); await DB.Default.DeleteAsync(v => v.RootUserId == user.ID); var pending = new EmailVerification @@ -457,7 +457,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RequestEmailChangeAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30029.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -470,18 +470,18 @@ namespace PrivaPub.Services var now = DateTime.UtcNow; var pending = await DB.Default.Find().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(30030.ToCodedError(localizer[EmailCodeInvalid])); if (pending.CodeHash != RecoveryJob.Hash(code?.Trim())) { if (pending.Attempts + 1 >= EmailVerification.MaxAttempts) await DB.Default.DeleteAsync(pending.ID); else await DB.Default.Update().MatchID(pending.ID).Modify(b => b.Inc(v => v.Attempts, 1)).ExecuteAsync(token); - return result.Invalidate(localizer[EmailCodeInvalid]); + return result.Invalidate(30031.ToCodedError(localizer[EmailCodeInvalid])); } await DB.Default.DeleteAsync(pending.ID); 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]); + return result.Invalidate(30032.ToCodedError(localizer[EmailCodeInvalid])); await DB.Default.Update().MatchID(rootId) .Modify(u => u.Email, pending.Email) @@ -493,7 +493,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(VerifyEmailAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30033.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -507,9 +507,9 @@ namespace PrivaPub.Services 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(30034.ToCodedError(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(30035.ToCodedError(localizer["Two-factor sign-in is on already: turn it off first."]), StatusCodes.Status409Conflict); var secret = TwoFactor.NewSecret(); await DB.Default.Update().MatchID(rootId) @@ -522,7 +522,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpSetupAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30036.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -533,9 +533,9 @@ namespace PrivaPub.Services { 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(30037.ToCodedError(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(30038.ToCodedError(localizer[TwoFactor.CodeInvalid])); var codes = TwoFactor.NewRecoveryCodes(); await DB.Default.Update().MatchID(rootId) @@ -555,7 +555,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpEnableAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30039.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -567,11 +567,11 @@ namespace PrivaPub.Services 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(30040.ToCodedError(localizer["Wrong password."]), StatusCodes.Status403Forbidden); if (user.Totp?.EnabledAt == default) return await AccountAsync(rootId, token); if (!await TwoFactor.Consume(user, code, CancellationToken.None)) - return result.Invalidate(localizer[TwoFactor.CodeInvalid]); + return result.Invalidate(30041.ToCodedError(localizer[TwoFactor.CodeInvalid])); await DB.Default.Update().MatchID(rootId).Modify(u => u.Totp, null).ExecuteAsync(token); return await AccountAsync(rootId, token); @@ -579,7 +579,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpDisableAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30042.ToCodedError(localizer["Something went wrong."]), exception: ex); } } @@ -591,7 +591,7 @@ namespace PrivaPub.Services 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(30043.ToCodedError(localizer["Wrong password."]), StatusCodes.Status403Forbidden); await DB.Default.Update().MatchID(rootId) .Modify(u => u.Email, null) @@ -605,7 +605,7 @@ namespace PrivaPub.Services catch (Exception ex) { logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveEmailAsync)}()"); - return result.Invalidate(localizer["Something went wrong."], exception: ex); + return result.Invalidate(30044.ToCodedError(localizer["Something went wrong."]), exception: ex); } } }