Activities of "jordanchen98"

Hi,

I tested this on my own project and its working as expected!

Thank you so much.

I've invited you to my repository.

I've added the dynamic permission but when I restarted the API, its not showing up.

Here is my implementation

DynamicPermissionDefinitionStoreInMemoryCache.LastCheckTime = null; DynamicPermissionDefinitionStoreInMemoryCache.CacheStamp = Guid.NewGuid().ToString();

Does this mean I can skip the static portion? and just use Dynamic Permission?

Hi,

I tried your method in my project and when I tried to run HttpApi.Host it said something about having an issue with the ISingletonDependancy.

using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SSDM.KMSv4.FilterFields;
using SSDM.KMSv4.FilterFieldShared;
using SSDM.KMSv4.ItemFilters;
using SSDM.KMSv4.Kiosks;
using SSDM.KMSv4.Localization;
using SSDM.KMSv4.Permissions;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Localization;

namespace SSDM.KMSv4.FilterValues;

[RemoteService(IsEnabled = false)]
[Authorize(KMSv4Permissions.FilterValues.Default)]
public class FilterValueAppService : ApplicationService, IFilterValueAppService
{
    private readonly FilterValueChildSharedService _fv;

    private readonly IKioskRepository _kioskRepository;
    private readonly IItemFilterRepository _itemFilterRepository;
    private readonly IFilterFieldRepository _filterFieldRepository;
    private readonly IFilterValueRepository _filterValueRepository;
    
    private readonly IExtendedStaticPermissionDefinitionStore _staticPermissionDefinitionStore;
    private readonly IPermissionDefinitionManager _permissionDefinitionManager;

    public FilterValueAppService(
        IItemFilterRepository itemFilterRepository, IFilterFieldRepository filterFieldRepository,
        IFilterValueRepository filterValueRepository, IKioskRepository kioskRepository,
        IExtendedStaticPermissionDefinitionStore staticPermissionDefinitionStore,
        IPermissionDefinitionManager permissionDefinitionManager
    )
    {
        _kioskRepository = kioskRepository;
        _itemFilterRepository = itemFilterRepository;
        _filterFieldRepository = filterFieldRepository;
        _filterValueRepository = filterValueRepository;
        _staticPermissionDefinitionStore = staticPermissionDefinitionStore;
        _permissionDefinitionManager = permissionDefinitionManager;

        _fv = new FilterValueChildSharedService(itemFilterRepository);
    }

    //---- Other functions ----//

    [Authorize(KMSv4Permissions.FilterValues.Create)]
    public virtual async Task<FilterValueDto> CreateAsync(FilterValueCreateDto input)
    {
        // Fetch records by FilterFieldId
        var recordsByFilterFieldId = await _filterValueRepository.GetListAsync(x => x.FilterFieldId.Equals(input.FilterFieldID));
        var ids = recordsByFilterFieldId.Select(x => x.Id).ToList();

        // Define the range
        int min = 1;
        int max = 2000000;

        // Get a random number not in the excluded list
        var generatedId = await GetRandomNumberNotInList(min, max, ids);

        FilterValue f = await _filterValueRepository.FirstOrDefaultAsync(x => x.Code == input.Code || x.Value == input.Value);
        if (f == null)
        {
            f = new FilterValue
            {
                Id = generatedId,
                Code = input.Code ?? "",
                Value = input.Value ?? "",
                FilterFieldId = input.FilterFieldID
            };
        }
        try
        {
            await _filterValueRepository.InsertAsync(f, true);
        }
        catch (Exception ex)
        {
            throw new UserFriendlyException(ex.Message);
        }
        await _fv.UpdateCreateItemFilter(f.Id, input.FilterValueParts);

        var branch = await _filterFieldRepository.FirstOrDefaultAsync(x => x.Desc.ToLower().Equals("branch"));
        var state = await _filterFieldRepository.FirstOrDefaultAsync(x => x.Desc.ToLower().Equals("state"));

        // Add Branch
        if (branch is not null && state is not null && input.FilterFieldID.Equals(branch.Id))
        {
            var branch_state = input.FilterValueParts.FirstOrDefault(x => x.ID.Equals(state.Id))?.Value.Replace(" ", "");
            var statePermission = await _permissionDefinitionManager.GetAsync(KMSv4Permissions.States.Default + "." + branch_state);

            if(statePermission is not null)
            {
                var permission = statePermission.AddChild("KMSv4.Branches." + f.Value.Replace(" ", ""), L(f.Value));
                await _staticPermissionDefinitionStore.AddPermissionDefinitionAsync(permission);
            }
        }

        // Add State
        if (state is not null && input.FilterFieldID.Equals(state.Id))
        {
            var statePermission = await _permissionDefinitionManager.GetAsync(KMSv4Permissions.States.Default);
            string state_permission_name = KMSv4Permissions.States.Default + "." + f.Value.Replace(" ", "");

            if (statePermission is not null)
            {
                var permission = statePermission.AddChild(state_permission_name, L(f.Value));
                await _staticPermissionDefinitionStore.AddPermissionDefinitionAsync(permission);
            }
        }

        return null;
    }

}

[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(IStaticPermissionDefinitionStore), typeof(IExtendedStaticPermissionDefinitionStore))]
public class MyStaticPermissionDefinitionStore : IExtendedStaticPermissionDefinitionStore, ISingletonDependency
{
    protected readonly IDictionary<string, PermissionGroupDefinition> PermissionGroupDefinitions;

    protected readonly IDictionary<string, PermissionDefinition> PermissionDefinitions;

    protected AbpPermissionOptions Options { get; }

    private readonly IServiceProvider _serviceProvider;

    public MyStaticPermissionDefinitionStore(
        IServiceProvider serviceProvider,
        IOptions<AbpPermissionOptions> options)
    {
        _serviceProvider = serviceProvider;
        Options = options.Value;

        PermissionGroupDefinitions = CreatePermissionGroupDefinitions();
        PermissionDefinitions = CreatePermissionDefinitions();
    }

    public Task AddPermissionDefinitionAsync(PermissionDefinition permissionDefinition)
    {
        if (!PermissionDefinitions.ContainsKey(permissionDefinition.Name))
        {
            PermissionDefinitions.Add(permissionDefinition.Name, permissionDefinition);
        }

        return Task.CompletedTask;
    }

    protected virtual Dictionary<string, PermissionDefinition> CreatePermissionDefinitions()
    {
        var permissions = new Dictionary<string, PermissionDefinition>();

        foreach (var groupDefinition in PermissionGroupDefinitions.Values)
        {
            foreach (var permission in groupDefinition.Permissions)
            {
                AddPermissionToDictionaryRecursively(permissions, permission);
            }
        }

        return permissions;
    }

    protected virtual void AddPermissionToDictionaryRecursively(
        Dictionary<string, PermissionDefinition> permissions,
        PermissionDefinition permission)
    {
        if (permissions.ContainsKey(permission.Name))
        {
            throw new AbpException("Duplicate permission name: " + permission.Name);
        }

        permissions[permission.Name] = permission;

        foreach (var child in permission.Children)
        {
            AddPermissionToDictionaryRecursively(permissions, child);
        }
    }

    protected virtual Dictionary<string, PermissionGroupDefinition> CreatePermissionGroupDefinitions()
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var context = new PermissionDefinitionContext(scope.ServiceProvider);

            var providers = Options
                .DefinitionProviders
                .Select(p => (scope.ServiceProvider.GetRequiredService(p) as IPermissionDefinitionProvider)!)
                .ToList();

            foreach (var provider in providers)
            {
                provider.PreDefine(context);
            }

            foreach (var provider in providers)
            {
                provider.Define(context);
            }

            foreach (var provider in providers)
            {
                provider.PostDefine(context);
            }

            return context.Groups;
        }
    }

    public Task<PermissionDefinition?> GetOrNullAsync(string name)
    {
        return Task.FromResult(PermissionDefinitions.GetOrDefault(name));
    }

    public virtual Task<IReadOnlyList<PermissionDefinition>> GetPermissionsAsync()
    {
        return Task.FromResult<IReadOnlyList<PermissionDefinition>>(
            PermissionDefinitions.Values.ToImmutableList()
        );
    }

    public Task<IReadOnlyList<PermissionGroupDefinition>> GetGroupsAsync()
    {
        return Task.FromResult<IReadOnlyList<PermissionGroupDefinition>>(
            PermissionGroupDefinitions.Values.ToImmutableList()
        );
    }
}


public interface IExtendedStaticPermissionDefinitionStore : IStaticPermissionDefinitionStore
{
    Task AddPermissionDefinitionAsync(PermissionDefinition permissionDefinition);
}

And I got this error:

 at Autofac.Core.Pipeline.ResolvePipeline.Invoke(Autofac.Core.Resolving.Pipeline.ResolveRequestContext)
   at Autofac.Core.Resolving.ResolveOperation.InvokePipeline(Autofac.ResolveRequest ByRef, Autofac.Core.Resolving.Pipeline.DefaultResolveRequestContext)
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(Autofac.Core.ISharingLifetimeScope, Autofac.ResolveRequest ByRef)
   at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(Autofac.ResolveRequest ByRef)
   at Autofac.Core.Resolving.ResolveOperation.Execute(Autofac.ResolveRequest ByRef)
   at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(Autofac.ResolveRequest ByRef)
   at Autofac.Core.Lifetime.LifetimeScope.Autofac.IComponentContext.ResolveComponent(Autofac.ResolveRequest ByRef)
   at Autofac.ResolutionExtensions.TryResolveService(Autofac.IComponentContext, Autofac.Core.Service, System.Collections.Generic.IEnumerable`1&lt;Autofac.Core.Parameter&gt;, System.Object ByRef)
   at Autofac.ResolutionExtensions.ResolveService(Autofac.IComponentContext, Autofac.Core.Service, System.Collections.Generic.IEnumerable`1<Autofac.Core.Parameter>)
   at Autofac.ResolutionExtensions.Resolve(Autofac.IComponentContext, System.Type, System.Collections.Generic.IEnumerable`1&lt;Autofac.Core.Parameter&gt;)
   at Autofac.ResolutionExtensions.Resolve(Autofac.IComponentContext, System.Type)
   at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetRequiredService(System.Type)
   at SSDM.KMSv4.FilterValues.MyStaticPermissionDefinitionStore+&lt;&gt;c__DisplayClass10_0.&lt;CreatePermissionGroupDefinitions&gt;b__0(System.Type)
   at System.Linq.Enumerable+IListSelectIterator`2[[System.__Canon, System.Private.CoreLib, Version=9.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=9.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Fill(System.Collections.Generic.IList`1&lt;System.__Canon&gt;, System.Span`1<System.__Canon>, System.Func`2&lt;System.__Canon,System.__Canon&gt;)
   at System.Linq.Enumerable+IListSelectIterator`2[[System.__Canon, System.Private.CoreLib, Version=9.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=9.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToList()
   at SSDM.KMSv4.FilterValues.MyStaticPermissionDefinitionStore.CreatePermissionGroupDefinitions()
   at DynamicClass.lambda_method1092(System.Runtime.CompilerServices.Closure, System.Object[])
   at Autofac.Core.Activators.Reflection.BoundConstructor.Instantiate()
   at Autofac.Core.Activators.Reflection.ReflectionActivator+<>c__DisplayClass14_0.<UseSingleConstructorActivation>b__0(Autofac.Core.Resolving.Pipeline.ResolveRequestContext, System.Action`1&lt;Autofac.Core.Resolving.Pipeline.ResolveRequestContext&gt;)

Not sure what this means.

Hi,

I tried it, it works well! When but when I restart the API the permission goes away so I guess I HAVE to save it into the database.

Do I store it into AbpPermissions after I added it into the static permission? Note: I saw that the new permission is added to AbpPermissionGrants

Thanks!

Thanks!

Hi,

I have emailed you the template project with the test code.

I think I've missed the .sql to restore so here it is: https://drive.google.com/file/d/1dIy4aG86qzAZ9TII0YJGDn_ftVZjkxvV/view?usp=drive_link

Thanks!

Hi,

I've emailed you a new project.

Thanks!

Showing 1 to 10 of 43 entries
Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09