yavsc/src/cli/Commands/UserListCleanUp.cs

76 lines
2.9 KiB
C#
Raw Normal View History

2021-06-03 16:24:33 +01:00
using cli.Model;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Yavsc.Server.Settings;
using Yavsc.Models;
2023-03-19 17:57:55 +00:00
using Microsoft.AspNetCore.Identity;
2025-07-16 00:47:50 +01:00
using Yavsc.Services;
2021-06-03 16:24:33 +01:00
namespace cli.Commands
{
public class UserListCleanUp : ICommander
{
public CommandLineApplication Integrate(CommandLineApplication rootApp)
{
CommandOption sendHelpOption = null;
CommandLineApplication userCleanupCommandApp
= rootApp.Command("user-cleanup",
(target) =>
{
target.FullName = "Remove invalid users";
target.Description = "Remove who didn't confirmed their e-mail in 14 days";
sendHelpOption = target.HelpOption("-? | -h | --help");
}, false);
userCleanupCommandApp.OnExecute(async () =>
{
bool showhelp = sendHelpOption.HasValue();
if (!showhelp)
{
2026-08-22 03:34:48 +01:00
2021-06-03 16:24:33 +01:00
2025-07-16 00:47:50 +01:00
var mailer = Program.AppHost.Services.GetService<MailSender>();
var loggerFactory = Program.AppHost.Services.GetService<ILoggerFactory>();
2021-06-03 16:24:33 +01:00
var logger = loggerFactory.CreateLogger<Program>();
2025-07-16 00:47:50 +01:00
var userManager = Program.AppHost.Services.GetService<UserManager<ApplicationUser>>();
ApplicationDbContext dbContext = Program.AppHost.Services.GetService<ApplicationDbContext>();
2021-06-03 16:24:33 +01:00
Func<ApplicationUser, bool> criteria = UserPolicies.Criterias["user-to-remove"];
2021-06-03 18:21:31 +01:00
if (userManager==null)
{
logger.LogError("No user manager");
throw new Exception("No user manager");
}
2021-06-03 16:24:33 +01:00
logger.LogInformation("Starting emailling");
2025-07-16 00:47:50 +01:00
try
{
2021-06-03 18:21:31 +01:00
mailer.SendEmailFromCriteria("user-to-remove");
}
2025-07-16 00:47:50 +01:00
catch (Exception ex)
2021-06-03 18:21:31 +01:00
{
logger.LogWarning(ex.Message);
2025-07-16 00:47:50 +01:00
throw;
2021-06-03 18:21:31 +01:00
}
ApplicationUser [] users = dbContext.ApplicationUser.Where(
u => criteria(u)).ToArray();
foreach (ApplicationUser user in users)
2021-06-03 16:24:33 +01:00
{
dbContext.DeviceDeclaration.RemoveRange(dbContext.DeviceDeclaration.Where(g => g.DeviceOwnerId == user.Id));
await userManager.DeleteAsync(user);
}
logger.LogInformation("Finished user cleanup");
}
else
{
userCleanupCommandApp.ShowHelp();
return 1;
}
return 0;
});
return userCleanupCommandApp;
}
}
}