Я пытаюсь ограничить пользователей в 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
Как ограничить пользователей определенной группой участников в Umbraco и предотвратить несанкционированное сохранение? ⇐ C#
Место общения программистов C#
1733706950
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"}
Подробнее здесь: [url]https://stackoverflow.com/questions/79263635/how-to-restrict-users-to-a-specific-member-group-in-umbraco-and-prevent-unauthor[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия