Unban work

This commit is contained in:
defnotken
2025-09-04 10:54:52 -05:00
parent b782b0694f
commit 4feb64f015
12 changed files with 2400 additions and 3 deletions

View File

@@ -121,6 +121,7 @@ public abstract class AuthControllerBase : Controller
{
CharacterIdentification = charaIdent,
Reason = "Autobanned CharacterIdent (" + uid + ")",
BannedUid = uid,
});
}

View File

@@ -0,0 +1,79 @@
using LightlessSync.API.Routes;
using LightlessSyncShared.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace LightlessSyncAuthService.Controllers;
[Route(LightlessAuth.User)]
public class UserController : Controller
{
protected readonly ILogger Logger;
protected readonly IDbContextFactory<LightlessDbContext> LightlessDbContextFactory;
public UserController(ILogger<UserController> logger, IDbContextFactory<LightlessDbContext> lightlessDbContext)
{
Logger = logger;
LightlessDbContextFactory = lightlessDbContext;
}
[Authorize(Policy = "Internal")]
[HttpPost(LightlessAuth.User_Unban_Uid)]
public async Task UnBanUserByUid(string uid)
{
using var dbContext = await LightlessDbContextFactory.CreateDbContextAsync();
Logger.LogInformation("Unbanning user with UID {UID}", uid);
//Mark User as not banned, and not marked for ban (if marked)
var auth = await dbContext.Auth.FirstOrDefaultAsync(f => f.UserUID == uid);
if (auth != null)
{
auth.IsBanned = false;
auth.MarkForBan = false;
}
// Remove all bans associated with this user
var bannedFromLightlessIds = dbContext.BannedUsers.Where(b => b.BannedUid == uid);
dbContext.BannedUsers.RemoveRange(bannedFromLightlessIds);
// Remove all character/discord bans associated with this user
var lodestoneAuths = dbContext.LodeStoneAuth.Where(l => l.User != null && l.User.UID == uid).ToList();
foreach (var lodestoneAuth in lodestoneAuths)
{
var bannedRegs = dbContext.BannedRegistrations.Where(b => b.DiscordIdOrLodestoneAuth == lodestoneAuth.HashedLodestoneId || b.DiscordIdOrLodestoneAuth == lodestoneAuth.DiscordId.ToString());
dbContext.BannedRegistrations.RemoveRange(bannedRegs);
}
await dbContext.SaveChangesAsync();
}
[Authorize(Policy = "Internal")]
[HttpPost(LightlessAuth.User_Unban_Discord)]
public async Task UnBanUserByDiscordId(string discordId)
{
Logger.LogInformation("Unbanning user with discordId: {discordId}", discordId);
using var dbContext = await LightlessDbContextFactory.CreateDbContextAsync();
var userByDiscord = await dbContext.LodeStoneAuth.Include(l => l.User).FirstOrDefaultAsync(l => l.DiscordId.ToString() == discordId);
if (userByDiscord?.User == null)
{
Logger.LogInformation("Unbanning user with discordId: {discordId} but no user found", discordId);
return;
}
var bannedRegs = dbContext.BannedRegistrations.Where(b => b.DiscordIdOrLodestoneAuth == discordId || b.DiscordIdOrLodestoneAuth == userByDiscord.HashedLodestoneId);
//Mark User as not banned, and not marked for ban (if marked)
var auth = await dbContext.Auth.FirstOrDefaultAsync(f => f.UserUID == userByDiscord.User.UID);
if (auth != null)
{
auth.IsBanned = false;
auth.MarkForBan = false;
}
// Remove all bans associated with this user
var bannedFromLightlessIds = dbContext.BannedUsers.Where(b => b.BannedUid == auth.UserUID || b.BannedUid == auth.PrimaryUserUID);
dbContext.BannedUsers.RemoveRange(bannedFromLightlessIds);
await dbContext.SaveChangesAsync();
}
}

View File

@@ -88,7 +88,7 @@ public class Startup
services.AddControllers().ConfigureApplicationPartManager(a =>
{
a.FeatureProviders.Remove(a.FeatureProviders.OfType<ControllerFeatureProvider>().First());
a.FeatureProviders.Add(new AllowedControllersFeatureProvider(typeof(JwtController), typeof(OAuthController)));
a.FeatureProviders.Add(new AllowedControllersFeatureProvider(typeof(JwtController), typeof(OAuthController), typeof(UserController)));
});
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -7,7 +7,6 @@ using LightlessSyncShared.Models;
using LightlessSyncShared.Services;
using LightlessSyncShared.Utils.Configuration;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using StackExchange.Redis;
namespace LightlessSyncServices.Discord;

View File

@@ -103,6 +103,7 @@ public class LightlessModule : InteractionModuleBase
try
{
using HttpClient c = new HttpClient();
_logger.LogInformation("Sending message to main server with {}", scope);
await c.PostAsJsonAsync(new Uri(_lightlessServicesConfiguration.GetValue<Uri>
(nameof(ServicesConfiguration.MainServerAddress)), "/msgc/sendMessage"), new ClientMessage(messageType, message, uid ?? string.Empty))
.ConfigureAwait(false);
@@ -138,6 +139,85 @@ public class LightlessModule : InteractionModuleBase
}
}
[SlashCommand("unbanbydiscord", "ADMIN ONLY: Unban a user by their discord ID")]
public async Task UnbanByDiscord([Summary("discord_id", "Discord ID to unban")] ulong discordId)
{
_logger.LogInformation("SlashCommand:{userId}:{Method}:{params}",
Context.Interaction.User.Id, nameof(UnbanByDiscord),
string.Join(",", new[] { $"{nameof(discordId)}:{discordId}" }));
try
{
using HttpClient c = new HttpClient();
await c.PostAsJsonAsync(new Uri(_lightlessServicesConfiguration.GetValue<Uri>
(nameof(ServicesConfiguration.MainServerAddress)), "/user/unbanDiscord"), new { discordId })
.ConfigureAwait(false);
var discordChannelForMessages = _lightlessServicesConfiguration.GetValueOrDefault<ulong?>(nameof(ServicesConfiguration.DiscordChannelForMessages), null);
if (discordChannelForMessages != null)
{
var discordChannel = await Context.Guild.GetChannelAsync(discordChannelForMessages.Value).ConfigureAwait(false) as IMessageChannel;
if (discordChannel != null)
{
var embedColor = Color.Blue;
EmbedBuilder eb = new();
eb.WithTitle("Unban Alert!");
eb.WithColor(embedColor);
eb.WithDescription(discordId + " has been unbanned");
await discordChannel.SendMessageAsync(embed: eb.Build()).ConfigureAwait(false);
}
}
await RespondAsync("Message sent", ephemeral: true).ConfigureAwait(false);
}
catch (Exception ex)
{
EmbedBuilder eb = new();
eb.WithTitle("An error occured");
eb.WithDescription("Please report this: " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine);
await RespondAsync(embeds: new Embed[] { eb.Build() }, ephemeral: true).ConfigureAwait(false);
}
}
[SlashCommand("unbanbyuid", "ADMIN ONLY: Unban a user by their uid")]
public async Task UnbanByUID([Summary("uid", "uid to unban")] string uid)
{
_logger.LogInformation("SlashCommand:{userId}:{Method}:{params}",
Context.Interaction.User.Id, nameof(UnbanByUID),
string.Join(",", new[] { $"{nameof(uid)}:{uid}" }));
try
{
using HttpClient c = new HttpClient();
await c.PostAsJsonAsync(new Uri(_lightlessServicesConfiguration.GetValue<Uri>
(nameof(ServicesConfiguration.MainServerAddress)), "/user/unbanUID"), new { uid })
.ConfigureAwait(false);
var discordChannelForMessages = _lightlessServicesConfiguration.GetValueOrDefault<ulong?>(nameof(ServicesConfiguration.DiscordChannelForMessages), null);
if (discordChannelForMessages != null)
{
var discordChannel = await Context.Guild.GetChannelAsync(discordChannelForMessages.Value).ConfigureAwait(false) as IMessageChannel;
if (discordChannel != null)
{
var embedColor = Color.Blue;
EmbedBuilder eb = new();
eb.WithTitle("Unban Alert!");
eb.WithColor(embedColor);
eb.WithDescription(uid + " has been unbanned");
await discordChannel.SendMessageAsync(embed: eb.Build()).ConfigureAwait(false);
}
}
await RespondAsync("Message sent", ephemeral: true).ConfigureAwait(false);
}
catch (Exception ex)
{
EmbedBuilder eb = new();
eb.WithTitle("An error occured");
eb.WithDescription("Please report this: " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine);
await RespondAsync(embeds: new Embed[] { eb.Build() }, ephemeral: true).ConfigureAwait(false);
}
}
public async Task<Embed> HandleUserAdd(string desiredUid, ulong discordUserId)
{
var embed = new EmbedBuilder();

View File

@@ -54,4 +54,8 @@
<ProjectReference Include="..\..\LightlessAPI\LightlessSyncAPI\LightlessSync.API.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="LightlessSyncServer\Migrations\" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LightlessSyncServer.Migrations
{
/// <inheritdoc />
public partial class AddBannedUid : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "banned_uid",
table: "banned_users",
type: "text",
nullable: true,
oldClrType: typeof(string),
oldType: "character varying(10)",
oldNullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "banned_uid",
table: "banned_users",
type: "character varying(10)",
nullable: true,
oldClrType: typeof(string),
oldType: "text",
oldNullable: true);
}
}
}

View File

@@ -68,6 +68,10 @@ namespace LightlessSyncServer.Migrations
.HasColumnType("text")
.HasColumnName("reason");
b.Property<string>("BannedUid")
.HasColumnType("character varying(10)")
.HasColumnName("banned_uid");
b.Property<byte[]>("Timestamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()

View File

@@ -8,6 +8,7 @@ public class Banned
[MaxLength(100)]
public string CharacterIdentification { get; set; }
public string Reason { get; set; }
public string BannedUid { get; set; }
[Timestamp]
public byte[] Timestamp { get; set; }
}