2023-02-18 08:52:17 +01:00
using Microsoft.AspNetCore.Authorization ;
using Microsoft.AspNetCore.Mvc ;
using Microsoft.Extensions.Localization ;
2026-10-17 05:23:45 +02:00
using MongoDB.Entities ;
2023-02-19 00:43:43 +01:00
using PrivaPub.ClientModels ;
2026-10-17 05:23:45 +02:00
using PrivaPub.ClientModels.Admin ;
2023-02-19 00:43:43 +01:00
using PrivaPub.ClientModels.User ;
2026-10-17 05:23:45 +02:00
using PrivaPub.Domain.Moderation ;
using PrivaPub.Domain.Timelines ;
2023-02-19 00:43:43 +01:00
using PrivaPub.Extensions ;
2026-10-17 05:23:45 +02:00
using PrivaPub.Federation.Actors ;
using PrivaPub.Models ;
using PrivaPub.Models.Group ;
using PrivaPub.Models.User ;
2023-02-19 00:43:43 +01:00
using PrivaPub.Resources ;
using PrivaPub.Services ;
2026-10-17 05:23:45 +02:00
using PrivaPub.StaticServices ;
2023-02-18 08:52:17 +01:00
using System.ComponentModel.DataAnnotations ;
2026-10-17 05:23:45 +02:00
using GroupEntity = PrivaPub . Models . Group . Group ;
2023-02-19 00:43:43 +01:00
namespace PrivaPub.Controllers.ClientToServer
2023-02-18 08:52:17 +01:00
{
2026-10-17 05:23:45 +02:00
// What only administrators do to logins (completion program R6): read them with their personas (the one place a login
// is shown next to its personas), change their role, ban and unban them, delete them, a persona or a group, and turn a
// login's two-factor sign-in off. Every act is kept in the staff's log; an entry about a login names none of its
// personas.
2023-02-18 08:52:17 +01:00
[ApiController,
2026-11-10 01:59:20 +01:00
Route(ApiPaths.Admin.Prefix),
2026-10-17 05:23:45 +02:00
Authorize(Policy = Policies.IsAdmin)]
2026-11-10 01:24:43 +01:00
public class AdminController (
ILogger < RootUserController > logger ,
IStringLocalizer < GenericRes > localizer ,
IRootUsersService rootUsersService ,
IModerationLog moderationLog ,
DbEntities dbEntities ,
ILocalActorService localActors ) : ControllerBase
2023-02-18 08:52:17 +01:00
{
2026-10-17 05:23:45 +02:00
const int MaxRootsPage = 100 ;
2023-02-18 08:52:17 +01:00
2026-10-17 02:56:57 +02:00
// an administrator never removes, bans or unbans itself; the request's own list is left as it came
UsersIds Others ( UsersIds usersIds )
{
var selfId = User . GetUserId ();
2026-10-17 05:23:45 +02:00
return new UsersIds { UserIdList = usersIds . UserIdList . Where ( id => id != selfId ). Distinct (). ToList () };
}
// the logins a request names that exist and are not deleted, by id: what the log names them
static async Task < Dictionary < string , string >> Named ( UsersIds usersIds , CancellationToken token )
{
var ids = usersIds . UserIdList ;
return ids . Count == 0
? new Dictionary < string , string >()
: ( await DB . Default . Find < RootUser >(). Match ( u => ids . Contains ( u . ID ) && u . DeletedAt == null ). ExecuteAsync ( token )). ToDictionary ( u => u . ID , u => u . UserName );
2026-10-17 02:56:57 +02:00
}
2026-11-10 01:59:20 +01:00
[HttpDelete, Route(ApiPaths.Admin.DELETE_RemoveUsers)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > RemoveUsers ([ Required ] UsersIds usersIds , CancellationToken token )
2023-02-18 08:52:17 +01:00
{
var result = new WebResult ();
try
{
2026-10-17 05:23:45 +02:00
var others = Others ( usersIds );
var named = await Named ( others , token );
2026-11-10 01:24:43 +01:00
result = await rootUsersService . RemoveUserAsync ( others , token );
2023-02-18 08:52:17 +01:00
if (! result . IsValid )
return StatusCode ( result . StatusCode , result );
2026-10-17 05:23:45 +02:00
foreach ( var ( id , name ) in named )
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . RootDelete , AdminTargets . Root , id , name , token : CancellationToken . None );
2023-02-18 08:52:17 +01:00
return Ok ();
}
catch ( Exception ex )
{
2026-11-10 01:24:43 +01:00
logger . LogError ( ex , $"{nameof(User)}.{nameof(RemoveUsers)}()" );
2026-11-10 08:11:11 +01:00
return BadRequest ( result . Invalidate ( 10001. ToCodedError ( localizer [ "Something went wrong." ])));
2023-02-18 08:52:17 +01:00
}
}
2026-10-17 05:23:45 +02:00
// A ban ends the login's sessions and holds its personas back as suspended ones (Restrictions), without writing a word
// on any of them; unbanning gives them back as they were.
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_BanUsers)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > BanUsers ([ Required ] UsersIds usersIds , [ FromServices ] IRootSessions sessions , CancellationToken token )
2023-02-18 08:52:17 +01:00
{
if (! ModelState . IsValid )
return BadRequest ( usersIds );
var result = new WebResult ();
try
{
2026-10-17 05:23:45 +02:00
var others = Others ( usersIds );
var named = await Named ( others , token );
var banned = ( await DB . Default . Find < RootUser >(). Match ( u => others . UserIdList . Contains ( u . ID ) && u . IsBanned ). ExecuteAsync ( token )). Select ( u => u . ID ). ToHashSet ();
2026-11-10 01:24:43 +01:00
result = await rootUsersService . BanUserAsync ( others , token );
2023-02-18 08:52:17 +01:00
if (! result . IsValid )
return StatusCode ( result . StatusCode , result );
2026-10-17 05:23:45 +02:00
await Restrictions . Reload ( CancellationToken . None );
foreach ( var ( id , name ) in named . Where ( n => ! banned . Contains ( n . Key )))
{
await sessions . Revoke ( id , CancellationToken . None );
2026-11-10 01:24:43 +01:00
foreach ( var link in await dbEntities . RootToAvatars . Match ( ra => ra . RootId == id ). ExecuteAsync ( token ))
2026-10-17 05:23:45 +02:00
Streams . CloseFor ( link . AvatarId );
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . RootBan , AdminTargets . Root , id , name , token : CancellationToken . None );
2026-10-17 05:23:45 +02:00
}
2023-02-18 08:52:17 +01:00
return Ok ();
}
catch ( Exception ex )
{
2026-11-10 01:24:43 +01:00
logger . LogError ( ex , $"{nameof(User)}.{nameof(BanUsers)}()" );
2026-11-10 08:11:11 +01:00
return BadRequest ( result . Invalidate ( 10002. ToCodedError ( localizer [ "Something went wrong." ])));
2023-02-18 08:52:17 +01:00
}
}
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_UnbanUsers)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > UnbanUsers ([ Required ] UsersIds usersIds , CancellationToken token )
2023-02-18 08:52:17 +01:00
{
if (! ModelState . IsValid )
return BadRequest ( usersIds );
var result = new WebResult ();
try
{
2026-10-17 05:23:45 +02:00
var others = Others ( usersIds );
var named = await Named ( others , token );
var banned = ( await DB . Default . Find < RootUser >(). Match ( u => others . UserIdList . Contains ( u . ID ) && u . IsBanned ). ExecuteAsync ( token )). Select ( u => u . ID ). ToHashSet ();
2026-11-10 01:24:43 +01:00
result = await rootUsersService . UnbanUserAsync ( others , token );
2023-02-18 08:52:17 +01:00
if (! result . IsValid )
return StatusCode ( result . StatusCode , result );
2026-10-17 05:23:45 +02:00
await Restrictions . Reload ( CancellationToken . None );
foreach ( var ( id , name ) in named . Where ( n => banned . Contains ( n . Key )))
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . RootUnban , AdminTargets . Root , id , name , token : CancellationToken . None );
2023-02-18 08:52:17 +01:00
return Ok ();
}
catch ( Exception ex )
{
2026-11-10 01:24:43 +01:00
logger . LogError ( ex , $"{nameof(User)}.{nameof(UnbanUsers)}()" );
2026-11-10 08:11:11 +01:00
return BadRequest ( result . Invalidate ( 10003. ToCodedError ( localizer [ "Something went wrong." ])));
2023-02-18 08:52:17 +01:00
}
}
2026-10-17 05:23:45 +02:00
// The logins, newest first, each with its personas and the groups they own; q finds a login by its name, or by the
// name of one of its personas.
2026-11-10 01:59:20 +01:00
[HttpGet, Route(ApiPaths.Admin.GET_Roots)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > Roots ([ FromQuery ] string q , [ FromQuery ] string before , [ FromQuery ] int limit = 50 , CancellationToken token = default )
{
limit = Math . Clamp ( limit , 1 , MaxRootsPage );
var query = DB . Default . Find < RootUser >(). Match ( u => u . DeletedAt == null );
var name = q ?. Trim (). TrimStart ( '@' ). Split ( '@' )[ 0 ]. ToLowerInvariant ();
if (! string . IsNullOrEmpty ( name ))
{
var personaIds = ( await DB . Default . Find < Avatar >(). Match ( a => a . UserName . StartsWith ( name ) && ! a . DeletionAt . HasValue )
. Project ( a => a . Include ( x => x . ID )). Limit ( 500 ). ExecuteAsync ( token )). Select ( a => a . ID ). ToList ();
var owners = personaIds . Count == 0
? new List < string >()
: ( await DB . Default . Find < RootToAvatar >(). Match ( ra => personaIds . Contains ( ra . AvatarId )). ExecuteAsync ( token )). Select ( ra => ra . RootId ). Distinct (). ToList ();
query . Match ( u => u . UserName . StartsWith ( name ) || owners . Contains ( u . ID ));
}
if (! string . IsNullOrEmpty ( before ))
{
if (! MongoDB . Bson . ObjectId . TryParse ( before , out _ ))
return BadRequest ();
query . Match ( f => f . Lt ( u => u . ID , before ));
}
var roots = await query . Sort ( u => u . ID , Order . Descending ). Limit ( limit ). ExecuteAsync ( token );
return Ok ( new ViewAdminRootsPage
{
Items = await Views ( roots , token ),
Next = roots . Count == limit ? roots [^ 1 ]. ID : default
});
}
2026-11-10 01:59:20 +01:00
[HttpGet, Route(ApiPaths.Admin.GET_M_Root)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > Root ( string id , CancellationToken token )
{
var root = await DB . Default . Find < RootUser >(). MatchID ( id ). Match ( u => u . DeletedAt == null ). ExecuteFirstAsync ( token );
return root == default ? NotFound () : Ok (( await Views ( new List < RootUser > { root }, token ))[ 0 ]);
}
// A login's role: user, moderator or administrator. Never one's own, and never the last administrator's.
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_M_Role)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > Role ( string id , RootRoleForm form , CancellationToken token )
{
if (! ModelState . IsValid || ! RootUser . TryParseRole ( form . Role , out var role ))
2026-11-10 08:11:11 +01:00
return UnprocessableEntity ( new WebResult (). Invalidate ( 10004. ToCodedError ( localizer [ "Unknown role." ]), StatusCodes . Status422UnprocessableEntity ));
2026-10-17 05:23:45 +02:00
if ( id == User . GetUserId ())
2026-11-10 08:11:11 +01:00
return Conflict ( new WebResult (). Invalidate ( 10005. ToCodedError ( localizer [ "You can't change your own role." ]), StatusCodes . Status409Conflict ));
2026-10-17 05:23:45 +02:00
var root = await DB . Default . Find < RootUser >(). MatchID ( id ). Match ( u => u . DeletedAt == null ). ExecuteFirstAsync ( token );
if ( root == default )
return NotFound ();
var was = root . Role ;
if ( was == role )
return Ok (( await Views ( new List < RootUser > { root }, token ))[ 0 ]);
if ( was == RootRole . Admin && ! await OtherAdministrators ( root . ID , token ))
2026-11-10 08:11:11 +01:00
return Conflict ( new WebResult (). Invalidate ( 10006. ToCodedError ( localizer [ "The last administrator can't be demoted." ]), StatusCodes . Status409Conflict ));
2026-10-17 05:23:45 +02:00
root . SetRole ( role );
await DB . Default . Update < RootUser >(). MatchID ( root . ID ). Modify ( u => u . Policies , root . Policies ). Modify ( u => u . UpdatedAt , root . UpdatedAt )
. ExecuteAsync ( CancellationToken . None );
// two administrators demoting each other at once: this one's act is undone, so one always remains
if ( was == RootRole . Admin && ! await OtherAdministrators ( root . ID , CancellationToken . None ))
{
root . SetRole ( was );
await DB . Default . Update < RootUser >(). MatchID ( root . ID ). Modify ( u => u . Policies , root . Policies ). ExecuteAsync ( CancellationToken . None );
2026-11-10 08:11:11 +01:00
return Conflict ( new WebResult (). Invalidate ( 10007. ToCodedError ( localizer [ "The last administrator can't be demoted." ]), StatusCodes . Status409Conflict ));
2026-10-17 05:23:45 +02:00
}
if ( role == RootRole . Admin )
await ServerSetup . Seal ( root . ID , default ); //an administrator exists: the client's setup is closed
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . RootRole , AdminTargets . Root , root . ID , root . UserName ,
2026-10-17 05:23:45 +02:00
note : $"{RoleName(was)} → {RoleName(role)}" , token : CancellationToken . None );
return Ok (( await Views ( new List < RootUser > { root }, token ))[ 0 ]);
}
// an administrator other than this login that can still act
static Task < bool > OtherAdministrators ( string rootId , CancellationToken token ) =>
DB . Default . Find < RootUser >(). Match ( u => u . ID != rootId && u . DeletedAt == null && ! u . IsBanned && u . Policies . Contains ( Policies . IsAdmin )). ExecuteAnyAsync ( token );
// A login that lost its authenticator and its recovery codes, as `PrivaPub admin reset-totp` does it: its two-factor
// sign-in goes, its password and sessions stay. Never one's own (that is /clientapi/user/totp/disable, with a code).
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_M_ResetTotp)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > ResetTotp ( string id , CancellationToken token )
{
if ( id == User . GetUserId ())
2026-11-10 08:11:11 +01:00
return Conflict ( new WebResult (). Invalidate ( 10008. ToCodedError ( localizer [ "Turn your own two-factor sign-in off from your account." ]), StatusCodes . Status409Conflict ));
2026-10-17 05:23:45 +02:00
var root = await DB . Default . Find < RootUser >(). MatchID ( id ). Match ( u => u . DeletedAt == null ). ExecuteFirstAsync ( token );
if ( root == default )
return NotFound ();
await DB . Default . Update < RootUser >(). MatchID ( root . ID ). Modify ( u => u . Totp , null ). ExecuteAsync ( CancellationToken . None );
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . RootResetTotp , AdminTargets . Root , root . ID , root . UserName , token : CancellationToken . None );
2026-10-17 05:23:45 +02:00
return Ok ();
}
// A persona deleted by an administrator, who types their own password again: as its login would delete it
// (PersonaRemoval), the groups it owns with it. The log keeps it without who acted when it is the administrator's own.
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_M_DeletePersona)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > DeletePersona ( string id , AdminPasswordForm form , [ FromServices ] IPersonaRemoval personas , CancellationToken token )
{
if (! ModelState . IsValid )
2026-11-10 08:11:11 +01:00
return BadRequest ( new WebResult (). Invalidate ( 10009. ToCodedError ( localizer [ "Invalid model." ])));
2026-11-10 01:24:43 +01:00
if (! await rootUsersService . PasswordMatches ( User . GetUserId (), form . Password , token ))
2026-11-10 08:11:11 +01:00
return StatusCode ( StatusCodes . Status403Forbidden , new WebResult (). Invalidate ( 10010. ToCodedError ( localizer [ Services . RootUsersService . NoMatch ]), StatusCodes . Status403Forbidden ));
2026-11-10 01:24:43 +01:00
var avatar = await dbEntities . Avatars . MatchID ( id ). Match ( a => ! a . DeletionAt . HasValue ). ExecuteFirstAsync ( token );
2026-10-17 05:23:45 +02:00
if ( avatar == default )
return NotFound ();
2026-11-10 01:24:43 +01:00
var label = "@" + localActors . FromAvatar ( avatar ). Handle ;
2026-10-17 05:23:45 +02:00
if (! await personas . Remove ( avatar . ID , CancellationToken . None ))
return NotFound ();
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . PersonaDelete , AdminTargets . Persona , avatar . ID , label , note : form . Note , token : CancellationToken . None );
2026-10-17 05:23:45 +02:00
return Ok ();
}
2026-11-10 01:59:20 +01:00
[HttpPost, Route(ApiPaths.Admin.POST_M_DeleteGroup)]
2026-10-17 05:23:45 +02:00
public async Task < IActionResult > DeleteGroup ( string id , AdminPasswordForm form , [ FromServices ] IGroupRemoval groups , CancellationToken token )
{
if (! ModelState . IsValid )
2026-11-10 08:11:11 +01:00
return BadRequest ( new WebResult (). Invalidate ( 10011. ToCodedError ( localizer [ "Invalid model." ])));
2026-11-10 01:24:43 +01:00
if (! await rootUsersService . PasswordMatches ( User . GetUserId (), form . Password , token ))
2026-11-10 08:11:11 +01:00
return StatusCode ( StatusCodes . Status403Forbidden , new WebResult (). Invalidate ( 10012. ToCodedError ( localizer [ Services . RootUsersService . NoMatch ]), StatusCodes . Status403Forbidden ));
2026-11-10 01:24:43 +01:00
var group = await dbEntities . Groups . MatchID ( id ). Match ( g => ! g . DeletionAt . HasValue ). ExecuteFirstAsync ( token );
2026-10-17 05:23:45 +02:00
if ( group == default )
return NotFound ();
2026-11-10 01:24:43 +01:00
var label = "@" + localActors . FromGroup ( group ). Handle ;
2026-10-17 05:23:45 +02:00
if (! await groups . Remove ( group . ID , CancellationToken . None ))
return NotFound ();
2026-11-10 01:24:43 +01:00
await moderationLog . Write ( User . GetUserId (), AdminActions . GroupDelete , AdminTargets . Group , group . ID , label , note : form . Note , token : CancellationToken . None );
2026-10-17 05:23:45 +02:00
return Ok ();
}
async Task < List < ViewAdminRoot >> Views ( List < RootUser > roots , CancellationToken token )
{
var ids = roots . Select ( r => r . ID ). ToList ();
2026-11-10 01:24:43 +01:00
var links = ids . Count == 0 ? new List < RootToAvatar >() : await dbEntities . RootToAvatars . Match ( ra => ids . Contains ( ra . RootId )). ExecuteAsync ( token );
2026-10-17 05:23:45 +02:00
var avatarIds = links . Select ( l => l . AvatarId ). Distinct (). ToList ();
var avatars = avatarIds . Count == 0
? new Dictionary < string , Avatar >()
2026-11-10 01:24:43 +01:00
: ( await dbEntities . Avatars . Match ( a => avatarIds . Contains ( a . ID ) && ! a . DeletionAt . HasValue ). ExecuteAsync ( token )). ToDictionary ( a => a . ID );
2026-10-17 05:23:45 +02:00
var owned = avatarIds . Count == 0
? new List < GroupEntity >()
2026-11-10 01:24:43 +01:00
: await dbEntities . Groups . Match ( g => avatarIds . Contains ( g . OwnerAvatarId ) && ! g . DeletionAt . HasValue ). ExecuteAsync ( token );
2026-10-17 05:23:45 +02:00
var me = User . GetUserId ();
return roots . Select ( root => new ViewAdminRoot
{
Id = root . ID ,
UserName = root . UserName ,
Role = RoleName ( root . Role ),
IsBanned = root . IsBanned ,
HasEmail = ! string . IsNullOrEmpty ( root . Email ),
IsEmailValidated = root . IsEmailValidated ,
HasTotp = root . Totp ?. EnabledAt != default ,
IsYou = root . ID == me ,
CreatedAt = root . CreatedAt ,
Personas = links . Where ( l => l . RootId == root . ID && avatars . ContainsKey ( l . AvatarId )). Select ( l => avatars [ l . AvatarId ])
. OrderBy ( a => a . UserName , StringComparer . Ordinal )
. Select ( a =>
{
2026-11-10 01:24:43 +01:00
var persona = localActors . FromAvatar ( a );
2026-10-17 05:23:45 +02:00
return new ViewAdminPersona
{
Id = a . ID ,
UserName = a . UserName ,
DisplayName = persona . Name ,
Handle = persona . Handle ,
SilencedAt = a . SilencedAt ,
SuspendedAt = a . SuspendedAt ,
Groups = owned . Where ( g => g . OwnerAvatarId == a . ID ). Select ( g => new ViewAdminGroup
{
Id = g . ID ,
UserName = g . UserName ,
Name = g . Name ,
IsCommunity = g . Kind == GroupKind . Community ,
MembersCount = g . Members . Count
}). ToList ()
};
}). ToList ()
}). ToList ();
}
static string RoleName ( RootRole role ) => role switch
{
RootRole . Admin => "admin" ,
RootRole . Moderator => "moderator" ,
_ => "user"
};
2023-02-18 08:52:17 +01:00
}
}