87 lines
2.9 KiB
C#
87 lines
2.9 KiB
C#
using Managing.Application.Abstractions.Repositories;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Managing.Application.Shared;
|
|
|
|
public interface IAdminConfigurationService
|
|
{
|
|
Task<bool> IsUserAdminAsync(string userName);
|
|
List<string> GetAdminUserNames();
|
|
}
|
|
|
|
public class AdminConfigurationService : IAdminConfigurationService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly ILogger<AdminConfigurationService> _logger;
|
|
private readonly IServiceScopeFactory _serviceScopeFactory;
|
|
|
|
public AdminConfigurationService(
|
|
IConfiguration configuration,
|
|
ILogger<AdminConfigurationService> logger,
|
|
IServiceScopeFactory serviceScopeFactory)
|
|
{
|
|
_configuration = configuration;
|
|
_logger = logger;
|
|
_serviceScopeFactory = serviceScopeFactory;
|
|
}
|
|
|
|
public async Task<bool> IsUserAdminAsync(string userName)
|
|
{
|
|
if (string.IsNullOrEmpty(userName))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// First check configuration (for backward compatibility)
|
|
var adminUserNames = GetAdminUserNames();
|
|
var isAdminFromConfig = adminUserNames.Contains(userName, StringComparer.OrdinalIgnoreCase);
|
|
|
|
if (isAdminFromConfig)
|
|
{
|
|
_logger.LogInformation("User {UserName} has admin privileges from configuration", userName);
|
|
return true;
|
|
}
|
|
|
|
// If not in config, check database User.IsAdmin flag
|
|
try
|
|
{
|
|
using var scope = _serviceScopeFactory.CreateScope();
|
|
var userRepository = scope.ServiceProvider.GetRequiredService<IUserRepository>();
|
|
|
|
var user = await userRepository.GetUserByNameAsync(userName);
|
|
|
|
_logger.LogInformation("User {UserName} has admin privileges from database isAdmin {isAdmin}", userName,
|
|
user.IsAdmin);
|
|
|
|
if (user != null && user.IsAdmin)
|
|
{
|
|
_logger.LogInformation("User {UserName} has admin privileges from database", userName);
|
|
return true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Error checking admin status for user {UserName} from database", userName);
|
|
// If database check fails, fall back to config-only result
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public List<string> GetAdminUserNames()
|
|
{
|
|
var adminUsers = _configuration["AdminUsers"];
|
|
if (string.IsNullOrEmpty(adminUsers))
|
|
{
|
|
_logger.LogDebug("No admin users configured. Set AdminUsers environment variable.");
|
|
return new List<string>();
|
|
}
|
|
|
|
return adminUsers.Split(';', StringSplitOptions.RemoveEmptyEntries)
|
|
.Select(u => u.Trim())
|
|
.Where(u => !string.IsNullOrEmpty(u))
|
|
.ToList();
|
|
}
|
|
} |