Как ограничить пользователей определенной группой участников в Umbraco и предотвратить несанкционированное сохранение?C#

Место общения программистов C#
Ответить
Anonymous
 Как ограничить пользователей определенной группой участников в Umbraco и предотвратить несанкционированное сохранение?

Сообщение Anonymous »

Я пытаюсь ограничить пользователей в Umbraco, чтобы пользователи с ролью «collarDatabase» могли добавлять участников только в группу участников «Collar_Database». Если пользователь попытается добавить участника в любую другую группу, операция завершится неудачно, и никакие изменения не будут сохранены. Я использую MemberSavingNotification, чтобы отменить сохранение, если обнаружены неавторизованные группы. Проблема в том, что обработчик срабатывает несколько раз для одного и того же запроса, а изменения членов по-прежнему сохраняются даже после вызова уведомления.CancelOperation(). Как я могу гарантировать, что обработчик запускается только один раз для каждого запроса и что сохранение полностью блокируется в случае обнаружения неавторизованных групп?
Вот мой handler.cs:
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Linq;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;

public class RestrictMemberGroupEditHandler : INotificationHandler
{
private readonly ILogger _logger;
private readonly IMemberService _memberService;
private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor;

private static readonly ConcurrentDictionary ProcessedRequestIds = new ConcurrentDictionary();

public RestrictMemberGroupEditHandler(
ILogger logger,
IMemberService memberService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor)
{
_logger = logger;
_memberService = memberService;
_backOfficeSecurityAccessor = backOfficeSecurityAccessor;
}

public void Handle(MemberSavingNotification notification)
{
// Get a unique identifier for the current request
string requestId = GetRequestId();

if (ProcessedRequestIds.ContainsKey(requestId))
{
_logger.LogInformation("Skipping execution for RequestId {RequestId} as it has already been processed.", requestId);
return;
}

ProcessedRequestIds.TryAdd(requestId, true);

var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;

if (currentUser == null)
{
_logger.LogWarning("No current backend user found.");
return;
}

_logger.LogInformation("RestrictMemberGroupEditHandler triggered for user: {UserName}", currentUser.Name);

if (!currentUser.Groups.Any(g => g.Alias == "collarDatabase"))
{
_logger.LogInformation("User {UserName} is not in the 'Collar_Database' role. No restriction applied.", currentUser.Name);
return;
}

foreach (var member in notification.SavedEntities)
{
var assignedGroups = _memberService.GetAllRoles(member.Username).ToList();

_logger.LogInformation("Groups being assigned to member {MemberName}: {Groups}",
member.Name,
string.Join(", ", assignedGroups));

// Check for unauthorized groups
var unauthorizedGroups = assignedGroups.Where(group => group != "Collar_Database").ToList();

if (unauthorizedGroups.Any())
{
_logger.LogWarning("User {UserName} attempted to add member {MemberName} to unauthorized groups: {Groups}",
currentUser.Name,
member.Name,
string.Join(", ", unauthorizedGroups));

notification.CancelOperation(new EventMessage(
"Access Denied",
$"You can only assign members to the 'Collar_Database' group. Unauthorized groups: {string.Join(", ", unauthorizedGroups)}",
EventMessageType.Error));

return;
}
}

ProcessedRequestIds.TryRemove(requestId, out _);
}

private string GetRequestId()
{
return System.Guid.NewGuid().ToString();
}
}

Вот мой композитор:
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Notifications;

public class RestrictMemberGroupEditComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.AddNotificationHandler();
}
}

Вот журнал того, как Джон Смит пытается добавить Джона Доу в неавторизованную группу. .
{"@t":"2024-12-09T01:04:51.369Z","@mt":"RestrictMemberGroupEditHandler triggered for user: {UserName}","UserName":"John Smith"}
{"@t":"2024-12-09T01:04:51.372Z","@mt":"Groups being assigned to member {MemberName}: {Groups}","MemberName":"John Doe","Groups":"example-group, Collar_Database"}
{"@t":"2024-12-09T01:04:51.372Z","@mt":"User {UserName} attempted to add member {MemberName} to unauthorized groups: {Groups}","UserName":"John Smith","MemberName":"John Doe","Groups":"example-group"}
{"@t":"2024-12-09T01:04:51.405Z","@mt":"RestrictMemberGroupEditHandler triggered for user: {UserName}","UserName":"John Smith"}
{"@t":"2024-12-09T01:04:51.406Z","@mt":"Groups being assigned to member {MemberName}: {Groups}","MemberName":"John Doe","Groups":"example-group, Collar_Database"}
{"@t":"2024-12-09T01:04:51.407Z","@mt":"User {UserName} attempted to add member {MemberName} to unauthorized groups: {Groups}","UserName":"John Smith","MemberName":"John Doe","Groups":"example-group"}


Подробнее здесь: https://stackoverflow.com/questions/792 ... t-unauthor
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»