Open Closed

Need data seeder to add roles and pre-defined permissions #8558


User avatar
0
nabass created

hi i have multi modules project each module has his own permissions and seeder so i want when creating new tenant create two roles by default with specific permissions

i achieved creating roles but permissions no i get the code which give them all permissions

 var multiTenancySide = CurrentTenant.GetMultiTenancySide();
 var allPermissionNames = (await PermissionDefinitionManager.GetPermissionsAsync())
     .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
     .Select(p => p.Name)
     .ToArray(); 

i created new array and put my permissions within it ===> not work i get all permission then filter them ===> not work here is my code


using Horizon.CoreSetting;
using Horizon.EInvoice;
using Horizon.HRMS1;
using Horizon.Inventory;
using Horizon.MainAccounting;
using Horizon.POS;
 
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;

using System;
using System.Linq;
 
using Volo.Abp.Authorization.Permissions;
 
using Volo.Abp.Guids;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Uow;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;



namespace Horizon.HorizonERP.ERP
{
    public class ERPDataSeedContributor : IDataSeedContributor, ITransientDependency
    {
        protected IGuidGenerator GuidGenerator { get; }
        protected IIdentityRoleRepository RoleRepository { get; }
        protected IIdentityUserRepository UserRepository { get; }
        protected ILookupNormalizer LookupNormalizer { get; }
        protected IdentityUserManager UserManager { get; }
        protected IdentityRoleManager RoleManager { get; }
        protected ICurrentTenant CurrentTenant { get; }
        protected IOptions<IdentityOptions> IdentityOptions { get; }
        protected IPermissionDefinitionManager PermissionDefinitionManager { get; }
        protected IPermissionDataSeeder PermissionDataSeeder { get; }


 
        private readonly InventoryDataSeederContributor _inventoryDataSeederContributor;
 private readonly POSDataSeederContributor _POsDataSeederContributor;
 
        public ERPDataSeedContributor(  
            InventoryDataSeederContributor inventoryDataSeederContributor 
 
            IGuidGenerator guidGenerator,
            IIdentityRoleRepository roleRepository,
            IIdentityUserRepository userRepository,
            ILookupNormalizer lookupNormalizer,
            IdentityUserManager userManager,
            IdentityRoleManager roleManager,
            ICurrentTenant currentTenant,
            IOptions<IdentityOptions> identityOptions,
            IPermissionDefinitionManager permissionDefinitionManager,
            IPermissionDataSeeder permissionDataSeeder)
        {
            GuidGenerator = guidGenerator;
            RoleRepository = roleRepository;
            UserRepository = userRepository;
            LookupNormalizer = lookupNormalizer;
            UserManager = userManager;
            RoleManager = roleManager;
            CurrentTenant = currentTenant;
            IdentityOptions = identityOptions;
            PermissionDefinitionManager = permissionDefinitionManager;
            PermissionDataSeeder = permissionDataSeeder;


  
            _inventoryDataSeederContributor = inventoryDataSeederContributor;
 
  		_POsDataSeederContributor = pOsDataSeederContributor;
        }
        [UnitOfWork]
        public async Task SeedAsync(DataSeedContext context)
        {
 
            await _inventoryDataSeederContributor.SeedAsync(context);
 
            await _POsDataSeederContributor.SeedAsync(context);

            var tenantId = context.TenantId;
            using (CurrentTenant.Change(tenantId))
            {
                await IdentityOptions.SetAsync();

                // "Accounting" and "Cashier" roles
                const string accRoleName = "Accounting";
                const string cashRoleName = "Cashier";

                var accRoleNameRole = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(accRoleName));
                if (accRoleNameRole == null)
                {
                    accRoleNameRole = new Volo.Abp.Identity.IdentityRole(GuidGenerator.Create(), accRoleName, tenantId)
                    {
                        IsPublic = true
                    };

                    (await RoleManager.CreateAsync(accRoleNameRole)).CheckErrors();
                }

                var cashRoleNameRole = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(cashRoleName));
                if (cashRoleNameRole == null)
                {
                    cashRoleNameRole = new Volo.Abp.Identity.IdentityRole(GuidGenerator.Create(), cashRoleName, tenantId)
                    {
                        IsPublic = true
                    };

                    (await RoleManager.CreateAsync(cashRoleNameRole)).CheckErrors();
                }
                //var user = await UserRepository.FindAsync(tenantId.Value);//your user id

                //(await UserManager.AddToRoleAsync(user, accRoleName)).CheckErrors();
                //(await UserManager.AddToRoleAsync(user, cashRoleName)).CheckErrors();

                var multiTenancySide = CurrentTenant.GetMultiTenancySide();
                var allPermissionNames = (await PermissionDefinitionManager.GetPermissionsAsync())
                    .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
                    .Select(p => p.Name)
                    .ToArray();

                var accPermissions = new[]
                {
                    "AccountIntegrations.Create",
                    "AccountIntegrations.Edit",
                    "AccountIntegrations.Delete",
                };
                await PermissionDataSeeder.SeedAsync(
                    RolePermissionValueProvider.ProviderName,
                    accRoleName,
                    accPermissions,
                    context?.TenantId
                     //allPermissionNames,
                );

                var cashPermissions = new[]
                {
                    "BasketReturn.Create"
                };

                await PermissionDataSeeder.SeedAsync(
                    RolePermissionValueProvider.ProviderName,
                    cashRoleName,
                    cashPermissions,
                    context?.TenantId
                    //allPermissionNames,
                );

            }
        }
    }
}

  • ABP Framework version: v8.0.2
  • UI Type:MVC
  • Database System: EF Core (SQL Server)

9 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    1. Does context.TenantId have a value?

    2. The PermissionDataSeeder will insert the records into the AbpPermissionGrant table. Can you check if the insert succeeds?

    3. Is this UI page from a tenant admin user?

    Thanks.

  • User Avatar
    0
    nabass created

    hi can you check this video https://streamable.com/6jc5vx

    thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I have checked the video. Code seems to be no problem.

    The PermissionDataSeeder will insert the records into the AbpPermissionGrant table. Can you check if the insert succeeds?

  • User Avatar
    0
    nabass created

    hi all permissions is for admin correct i want the permission i selected in my code for Accounting and Cashier role if i only used //================================================== var multiTenancySide = CurrentTenant.GetMultiTenancySide(); var allPermissionNames = (await PermissionDefinitionManager.GetPermissionsAsync()) .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide)) .Select(p => p.Name) .ToArray(); //================================================== so Accounting role and Cashier role will get all permissions as admin i do not want this i want specific permissions for each of them

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you share a simple project to reproduce the problem?

    I will download the code and debug it locally.

    liming.ma@volosoft.com

    Thanks.

  • User Avatar
    0
    nabass created

    hi sorry i can not share the code it's a company project i didn't do any thing except this class i shared with you and video you see no code for this case into any place just it... so you can take my code i shared and try it as i mentioned before if i use only //================================================== var multiTenancySide = CurrentTenant.GetMultiTenancySide(); var allPermissionNames = (await PermissionDefinitionManager.GetPermissionsAsync()) .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide)) .Select(p => p.Name) .ToArray(); //================================================== so Accounting role and Cashier role will get all permissions as admin i do not want this i want specific permissions for each of them

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    ok.

    1. Can you confirm the permission names are correct? Check your permissions definition class.
    2. Have the permissions for these names been inserted into the database?

    Because the PermissionDataSeeder just inserts the data.

    "AccountIntegrations.Create",
    "AccountIntegrations.Edit",
    "AccountIntegrations.Delete",
    "BasketReturn.Create"
    

    You can debug this code to see await PermissionGrantRepository.InsertManyAsync(permissions);

    var accPermissions = new[]
    {
        "AccountIntegrations.Create",
        "AccountIntegrations.Edit",
        "AccountIntegrations.Delete",
    };
    
    var names = accPermissions.ToArray();
    var existsPermissionGrants = (await PermissionGrantRepository.GetListAsync(names, RolePermissionValueProvider.ProviderName, cashRoleName)).Select(x => x.Name).ToList();
    var permissions = names.Except(existsPermissionGrants).Select(permissionName => new PermissionGrant(GuidGenerator.Create(), permissionName, RolePermissionValueProvider.ProviderName, cashRoleName, tenantId)).ToList();
    if (!permissions.Any())
    {
        return;
    }
    await PermissionGrantRepository.InsertManyAsync(permissions);
    
  • User Avatar
    0
    nabass created

    hi sir i got the problem my code is working but i must add module name before permission name like img below thanks for your hard efforts

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Great. : )

Made with ❤️ on ABP v9.1.0-preview. Updated on January 02, 2025, 07:06