Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

SecurityModelFactory.cs

using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Security;
using Nop.Web.Areas.Admin.Infrastructure.Mapper.Extensions;
using Nop.Web.Areas.Admin.Models.Customers;
using Nop.Web.Areas.Admin.Models.Security;

namespace Nop.Web.Areas.Admin.Factories;

/// 
/// Represents the security model factory implementation
/// 
public partial class SecurityModelFactory : ISecurityModelFactory
{
    #region Fields

    protected readonly ICustomerService _customerService;
    protected readonly ILocalizationService _localizationService;
    protected readonly IPermissionService _permissionService;

    #endregion

    #region Ctor

    public SecurityModelFactory(ICustomerService customerService,
        ILocalizationService localizationService,
        IPermissionService permissionService)
    {
        _customerService = customerService;
        _localizationService = localizationService;
        _permissionService = permissionService;
    }

    #endregion

    #region Methods

    /// 
    /// Prepare permission mapping model
    /// 
    /// Permission mapping model
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the permission mapping model
    /// 
    public virtual async Task PreparePermissionMappingModelAsync(PermissionMappingModel model)
    {
        ArgumentNullException.ThrowIfNull(model);

        var customerRoles = await _customerService.GetAllCustomerRolesAsync(true);
        model.AvailableCustomerRoles = customerRoles.Select(role => role.ToModel()).ToList();

        foreach (var permissionRecord in await _permissionService.GetAllPermissionRecordsAsync())
        {
            model.AvailablePermissions.Add(new PermissionRecordModel
            {
                Name = await _localizationService.GetLocalizedPermissionNameAsync(permissionRecord),
                SystemName = permissionRecord.SystemName
            });

            foreach (var role in customerRoles)
            {
                if (!model.Allowed.ContainsKey(permissionRecord.SystemName))
                    model.Allowed[permissionRecord.SystemName] = new Dictionary();
                model.Allowed[permissionRecord.SystemName][role.Id] =
                    (await _permissionService.GetMappingByPermissionRecordIdAsync(permissionRecord.Id)).Any(mapping => mapping.CustomerRoleId == role.Id);
            }
        }

        return model;
    }

    #endregion
}