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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
569 lines
24 KiB
C#
569 lines
24 KiB
C#
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
using Microsoft.Extensions.Localization;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
using MongoDB.Entities;
|
|
|
|
using PrivaPub.ClientModels;
|
|
using PrivaPub.ClientModels.Resources;
|
|
using PrivaPub.ClientModels.Group;
|
|
using PrivaPub.ClientModels.User;
|
|
using PrivaPub.ClientModels.User.Avatar;
|
|
using PrivaPub.Extensions;
|
|
using PrivaPub.Federation.Actors;
|
|
using PrivaPub.Infrastructure;
|
|
using PrivaPub.Models;
|
|
using PrivaPub.Models.User;
|
|
using PrivaPub.Resources;
|
|
using PrivaPub.Services;
|
|
using PrivaPub.Services.ClientToServer.Private;
|
|
using PrivaPub.StaticServices;
|
|
|
|
using System.ComponentModel.DataAnnotations;
|
|
|
|
namespace PrivaPub.Controllers.ClientToServer
|
|
{
|
|
[ApiController,
|
|
Route(ApiPaths.RootUser.Prefix)]
|
|
public class RootUserController(
|
|
IRootUsersService usersService,
|
|
IGroupUsersService groupUsersService,
|
|
IPrivateAvatarUsersService avatarUsersService,
|
|
ILocalActorService localActors,
|
|
AuthTokenManager authTokenManager,
|
|
IOptionsMonitor<AppConfiguration> appConfiguration,
|
|
IOptionsMonitor<RegistrationOptions> registrations,
|
|
IStringLocalizer<GenericRes> localizer,
|
|
ILogger<RootUserController> logger) : ControllerBase
|
|
{
|
|
#region User endpoints
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_SignUp), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
|
|
public async Task<IActionResult> SignUp(LoginForm signUpForm, CancellationToken token = default)
|
|
{
|
|
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
|
var result = new WebResult();
|
|
if (!registrations.CurrentValue.IsOpen)
|
|
return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(21001.ToCodedError(localizer[RegistrationOptions.ClosedMessage]), StatusCodes.Status403Forbidden));
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21002.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.SignUpAsync(signUpForm, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
(var user, var userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
|
var jwtUser = authTokenManager.GenerateToken(user, userSettings);
|
|
return Ok(jwtUser);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()");
|
|
return BadRequest(result.Invalidate(21003.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_Login), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
|
|
public async Task<IActionResult> Login(LoginForm loginForm, CancellationToken token = default)
|
|
{
|
|
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21004.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.LoginAsync(loginForm, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
var (user, userSettings) =
|
|
((RootUser, ViewUserSettings))result.Data;
|
|
var jwtUser = authTokenManager.GenerateToken(user, userSettings);
|
|
|
|
return Ok(jwtUser);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()");
|
|
return BadRequest(result.Invalidate(21005.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_InvitationSignUp), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> InvitationSignUp(InvitationLoginForm signUpForm, CancellationToken token)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21006.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
var invitation = await groupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token);
|
|
if (!invitation.IsValid)
|
|
return StatusCode(invitation.StatusCode, invitation);
|
|
|
|
var avatarUserName = signUpForm.AvatarUserName?.Trim().ToLowerInvariant();
|
|
var personaProblem = await PersonaProblem(avatarUserName, signUpForm.UserName, token);
|
|
if (personaProblem != default)
|
|
return BadRequest(result.Invalidate(21007.ToCodedError(personaProblem)));
|
|
|
|
result = await usersService.SignUpAsync(signUpForm, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
|
|
|
var avatar = await InsertPersona(user.ID, avatarUserName, signUpForm.AvatarName, token);
|
|
if (!avatar.IsValid)
|
|
return StatusCode(avatar.StatusCode, avatar);
|
|
|
|
var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
|
{
|
|
AvatarId = ((ViewAvatar)avatar.Data).Id,
|
|
InvitationCode = signUpForm.InvitationCode,
|
|
InvitationPassword = signUpForm.InvitationPassword
|
|
}, token);
|
|
if (!joined.IsValid)
|
|
return StatusCode(joined.StatusCode, joined);
|
|
|
|
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()");
|
|
return BadRequest(result.Invalidate(21008.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_InvitationLogin), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> InvitationLogin(InvitationLoginForm loginForm, CancellationToken token)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21009.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
var invitation = await groupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token);
|
|
if (!invitation.IsValid)
|
|
return StatusCode(invitation.StatusCode, invitation);
|
|
|
|
result = await usersService.LoginAsync(loginForm, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
|
|
|
var avatars = await avatarUsersService.GetRootAvatars(user.ID, token);
|
|
var avatarUserName = loginForm.AvatarUserName?.Trim().ToLowerInvariant();
|
|
var avatar = string.IsNullOrEmpty(avatarUserName)
|
|
? (avatars.Data as List<ViewAvatar>)?.FirstOrDefault()
|
|
: (avatars.Data as List<ViewAvatar>)?.FirstOrDefault(a => a.UserName == avatarUserName);
|
|
if (avatar == default)
|
|
{
|
|
var personaProblem = await PersonaProblem(avatarUserName, user.UserName, token);
|
|
if (personaProblem != default)
|
|
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);
|
|
avatar = (ViewAvatar)inserted.Data;
|
|
}
|
|
|
|
var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
|
{
|
|
AvatarId = avatar.Id,
|
|
InvitationCode = loginForm.InvitationCode,
|
|
InvitationPassword = loginForm.InvitationPassword
|
|
}, token);
|
|
if (!joined.IsValid)
|
|
return StatusCode(joined.StatusCode, joined);
|
|
|
|
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()");
|
|
return BadRequest(result.Invalidate(21011.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpGet, Route(ApiPaths.RootUser.GET_Setup), AllowAnonymous]
|
|
public async Task<IActionResult> Setup(CancellationToken token) =>
|
|
Ok(new ViewServerSetup { IsPending = await ServerSetup.IsPending(token) });
|
|
|
|
// The server's first login, made while it has no administrator (owner decision 2026-10-16: first come, first served):
|
|
// it is made the administrator, with its first persona, and setup closes for good. Sign-up stays closed to everyone
|
|
// else (registrations), so NodeInfo and the instance API don't change.
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_SetUp), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> SetUp(SetupForm setupForm, CancellationToken token)
|
|
{
|
|
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21012.ToCodedError(localizer["Invalid model."])));
|
|
var claimed = false;
|
|
var adminId = default(string);
|
|
try
|
|
{
|
|
if (!await ServerSetup.IsPending(token))
|
|
return SetUpAlready();
|
|
|
|
var avatarUserName = setupForm.AvatarUserName?.Trim().ToLowerInvariant();
|
|
var personaProblem = await PersonaProblem(avatarUserName, setupForm.UserName, token);
|
|
if (personaProblem != default)
|
|
return BadRequest(result.Invalidate(21013.ToCodedError(personaProblem)));
|
|
|
|
claimed = await ServerSetup.Claim(token);
|
|
if (!claimed)
|
|
return SetUpAlready();
|
|
|
|
result = await usersService.SignUpAsync(setupForm, token);
|
|
if (!result.IsValid)
|
|
{
|
|
await ServerSetup.Release(CancellationToken.None);
|
|
return StatusCode(result.StatusCode, result);
|
|
}
|
|
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
|
user.SetAdmin(true);
|
|
await DB.Default.SaveAsync(user, CancellationToken.None);
|
|
adminId = user.ID;
|
|
await ServerSetup.Claimed(adminId, CancellationToken.None);
|
|
|
|
// set up from here, whatever happens to the persona: it can be made in the client's settings
|
|
var avatar = await InsertPersona(user.ID, avatarUserName, setupForm.AvatarName, token);
|
|
if (!avatar.IsValid)
|
|
return StatusCode(avatar.StatusCode, avatar);
|
|
|
|
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()");
|
|
if (claimed && adminId == default)
|
|
await ServerSetup.Release(CancellationToken.None);
|
|
return BadRequest(result.Invalidate(21014.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
IActionResult SetUpAlready() =>
|
|
StatusCode(StatusCodes.Status403Forbidden,
|
|
new WebResult().Invalidate(21015.ToCodedError(localizer["This server is already set up: joining it takes a group invitation."]), StatusCodes.Status403Forbidden));
|
|
|
|
Task<WebResult> InsertPersona(string rootId, string avatarUserName, string avatarName, CancellationToken token = default) =>
|
|
avatarUsersService.InsertAvatar(new InsertAvatarForm
|
|
{
|
|
RootId = rootId,
|
|
Name = string.IsNullOrWhiteSpace(avatarName) ? avatarUserName : avatarName.Trim(),
|
|
UserName = avatarUserName,
|
|
Biography = string.Empty
|
|
}, token);
|
|
|
|
async Task<string> PersonaProblem(string avatarUserName, string rootUserName, CancellationToken token)
|
|
{
|
|
if (string.IsNullOrEmpty(avatarUserName))
|
|
return localizer["Choose a username for your persona."];
|
|
if (string.Equals(avatarUserName, rootUserName?.Trim(), StringComparison.OrdinalIgnoreCase))
|
|
return localizer["Your persona's username must differ from your login."];
|
|
if (await localActors.IsUserNameTaken(avatarUserName, token))
|
|
return localizer["The username '{0}' is already taken.", avatarUserName];
|
|
return default;
|
|
}
|
|
|
|
// This device signs out: its session (every token it renewed) is refused from now on. A token from before sessions had
|
|
// ids can't be told apart from the others, so it signs every device out.
|
|
[HttpGet, Route(ApiPaths.RootUser.GET_Logout), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> Logout([FromServices] IRootSessions sessions, CancellationToken token)
|
|
{
|
|
var result = new WebResult();
|
|
try
|
|
{
|
|
var sessionId = User.FindFirst(AuthTokenManager.SessionId)?.Value;
|
|
if (string.IsNullOrEmpty(sessionId))
|
|
await sessions.Revoke(User.GetUserId(), token);
|
|
else
|
|
await sessions.End(User.GetUserId(), sessionId, token);
|
|
return Ok();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()");
|
|
return BadRequest(result.Invalidate(21016.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_LogoutEverywhere), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> LogoutEverywhere([FromServices] IRootSessions sessions, CancellationToken token)
|
|
{
|
|
var result = new WebResult();
|
|
try
|
|
{
|
|
await sessions.Revoke(User.GetUserId(), token);
|
|
return Ok();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()");
|
|
return BadRequest(result.Invalidate(21017.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
// The address is changed only with the password and a code sent to it (/clientapi/user/email); this older route, which
|
|
// took neither and said whether an address was taken, no longer changes anything.
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_UpdateUser), Authorize(Policy = Policies.IsUser)]
|
|
public IActionResult UpdateUser(UserForm userEmailForm) =>
|
|
StatusCode(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<IActionResult> Account(CancellationToken token = default)
|
|
{
|
|
var result = await usersService.AccountAsync(User.GetUserId(), token);
|
|
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_RequestEmailChange), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> RequestEmailChange(EmailChangeForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_VerifyEmail), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> VerifyEmail(EmailCodeForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_TotpSetup), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> TotpSetup(PasswordForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
}
|
|
|
|
// on with the app's first code; every other session ends, and this device goes on with a new one
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_TotpEnable), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> TotpEnable(TotpCodeForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
var (user, userSettings, codes) = ((RootUser, ViewUserSettings, List<string>))result.Data;
|
|
return Ok(new ViewTotpEnabled { RecoveryCodes = codes, Session = authTokenManager.GenerateToken(user, userSettings) });
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_TotpDisable), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> TotpDisable(TotpDisableForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_RemoveEmail), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> RemoveEmail(PasswordForm form, CancellationToken token = default)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
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);
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_UpdateUserSettings), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> UpdateUserSettings(ViewUserSettings userSettings, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21025.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.UpdateUserSettingsAsync(userSettings, User.GetUserId(), token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
return Ok();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()");
|
|
return BadRequest(result.Invalidate(21026.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_UpdatePassword), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> UpdatePassword(UserPasswordForm userPasswordForm, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21027.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId(), token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
// every session ended with the change; this device goes on with a new one
|
|
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
|
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()");
|
|
return BadRequest(result.Invalidate(21028.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
// what the login's media take, every persona's, and its quota when the server sets one
|
|
[HttpGet, Route(ApiPaths.RootUser.GET_GetStorage), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> GetStorage([FromServices] Microsoft.Extensions.Options.IOptionsMonitor<Domain.Media.MediaOptions> media, CancellationToken token)
|
|
{
|
|
var (bytes, files) = await Domain.Privacy.Counted.MediaOfRoot(User.GetUserId(), token);
|
|
var quota = media.CurrentValue.QuotaBytesPerRoot;
|
|
return Ok(new PrivaPub.ClientModels.User.ViewStorage { MediaBytes = bytes, MediaFiles = files, QuotaBytes = quota > 0 ? quota : null });
|
|
}
|
|
|
|
[HttpGet, Route(ApiPaths.RootUser.GET_GetUserSettings), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> GetUserSettings(CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
try
|
|
{
|
|
result = await usersService.GetUserSettingsAsync(User.GetUserId(), token: token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
return Ok(result.Data);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()");
|
|
return BadRequest(result.Invalidate(21029.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_RecoverPassword), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> RecoverPassword(PasswordRecoveryForm passwordRecoveryForm, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21030.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
var host = string.IsNullOrEmpty(appConfiguration.CurrentValue.FrontendBaseAddress)
|
|
? $"{Request.Scheme}://{Request.Host.Host}"
|
|
: appConfiguration.CurrentValue.FrontendBaseAddress.TrimEnd('/');
|
|
result = await usersService.SetupAndSendRecoveryEmail(passwordRecoveryForm, host, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
return Ok(result.Data);//the same sentence for everyone
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()");
|
|
return BadRequest(result.Invalidate(21031.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_IsValidRecoveryCode), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> IsValidRecoveryCode(
|
|
[FromBody,
|
|
Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)),
|
|
Display(Name = "RecoveryCode", ResourceType = typeof(FieldsNameResource))]
|
|
string recoveryCode, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
try
|
|
{
|
|
result = await usersService.IsValidRecoveryCode(recoveryCode, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
return Ok(result.Data);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()");
|
|
return BadRequest(result.Invalidate(21032.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_ChangePassword), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
|
public async Task<IActionResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21033.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.ChangePassword(newPasswordForm, token);
|
|
if (!result.IsValid)
|
|
return StatusCode(result.StatusCode, result);
|
|
|
|
return Ok(result.Data);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()");
|
|
return BadRequest(result.Invalidate(21034.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
[HttpPost, Route(ApiPaths.RootUser.POST_RemoveSelf), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> RemoveSelf(RemoveSelfForm form, CancellationToken token = default)
|
|
{
|
|
var result = new WebResult();
|
|
if (!ModelState.IsValid)
|
|
return BadRequest(result.Invalidate(21035.ToCodedError(localizer["Invalid model."])));
|
|
try
|
|
{
|
|
result = await usersService.RemoveSelfAsync(User.GetUserId(), form.Password, token);
|
|
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()");
|
|
return BadRequest(result.Invalidate(21036.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
#endregion User endpoints
|
|
|
|
#region Auth refresh
|
|
|
|
[HttpGet, Route(ApiPaths.RootUser.GET_SniffAgain), Authorize(Policy = Policies.IsUser)]
|
|
public async Task<IActionResult> SniffAgain([FromServices] DbEntities dbEntities, CancellationToken token)
|
|
{
|
|
var result = new WebResult();
|
|
try
|
|
{
|
|
var user = await dbEntities.RootUsers.MatchID(User.GetUserId()).ExecuteFirstAsync(token);
|
|
if (user is not { IsBanned: false, DeletedAt: null })
|
|
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);
|
|
|
|
return Ok(authTokenManager.GenerateToken(user, (ViewUserSettings)result.Data, User.FindFirst(AuthTokenManager.SessionId)?.Value));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()");
|
|
return BadRequest(result.Invalidate(21038.ToCodedError(localizer["Something went wrong."])));
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|