|
| 1 | +// Copyright (c) CodeBlock.Dev. All rights reserved. |
| 2 | +// For more information visit https://codeblock.dev |
| 3 | + |
| 4 | +using System.Reflection; |
| 5 | +using CodeBlock.DevKit.Contracts.Models; |
| 6 | + |
| 7 | +namespace CanBeYours.Application.Helpers; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// This class contains all permissions used in the application. |
| 11 | +/// They will be automatically registered in the database. |
| 12 | +/// </summary> |
| 13 | +public static class Permissions |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// This class name is used as a group name for permissions related to demo things. |
| 17 | + /// </summary> |
| 18 | + public static class Demo |
| 19 | + { |
| 20 | + /// <summary> |
| 21 | + /// This property represents the permission to manage demo things. |
| 22 | + /// </summary> |
| 23 | + public const string DEMO_THINGS = "DemoThings"; |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Retrieves all permissions dynamically using reflection. |
| 28 | + /// </summary> |
| 29 | + public static IEnumerable<PermissionsSettings> GetPermissions() |
| 30 | + { |
| 31 | + var permissionsList = new List<PermissionsSettings>(); |
| 32 | + |
| 33 | + // Get all nested classes (categories) |
| 34 | + var categories = typeof(Permissions).GetNestedTypes(BindingFlags.Public | BindingFlags.Static); |
| 35 | + |
| 36 | + foreach (var category in categories) |
| 37 | + { |
| 38 | + // Get all public constants (permissions) inside the category |
| 39 | + var permissions = category |
| 40 | + .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) |
| 41 | + .Where(f => f.IsLiteral && !f.IsInitOnly) // Ensure they are constants |
| 42 | + .Select(f => new |
| 43 | + { |
| 44 | + SystemName = f.GetRawConstantValue()?.ToString(), // Property value |
| 45 | + DisplayName = f.GetRawConstantValue()?.ToString(), |
| 46 | + }) |
| 47 | + .Where(p => p.DisplayName != null) |
| 48 | + .ToList(); |
| 49 | + |
| 50 | + // Add extracted permissions to the list |
| 51 | + permissionsList.AddRange( |
| 52 | + permissions.Select(permission => new PermissionsSettings |
| 53 | + { |
| 54 | + SystemName = permission.SystemName, |
| 55 | + DisplayName = permission.DisplayName, |
| 56 | + GroupName = category.Name, |
| 57 | + }) |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + return permissionsList; |
| 62 | + } |
| 63 | +} |
0 commit comments