public async Task <IActionResult> Index(int?id)
        {
            this.AddBreadCrumb(new BreadCrumb
            {
                Title = "مدیریت نقش‌ها",
                Url   = Url.Action("Index", "RolesManager"),
                Order = -1
            });

            if (!id.HasValue)
            {
                return(View("Error"));
            }

            var role = await _roleManager.FindRoleIncludeRoleClaimsAsync(id.Value).ConfigureAwait(false);

            if (role == null)
            {
                return(View("NotFound"));
            }

            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            return(View(model: new DynamicRoleClaimsManagerViewModel
            {
                SecuredControllerActions = securedControllerActions,
                RoleIncludeRoleClaims = role
            }));
        }
        public bool CanUserAccess(ClaimsPrincipal user, string area, string controller, string action)
        {
            var currentClaimValue        = $"{area}:{controller}:{action}";
            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            if (!securedControllerActions.SelectMany(x => x.MvcActions).Any(x => x.ActionId == currentClaimValue))
            {
                throw new KeyNotFoundException($@"The `secured` area={area}/controller={controller}/action={action} with `ConstantPolicies.DynamicPermission` policy not found. Please check you have entered the area/controller/action names correctly and also it's decorated with the correct security policy.");
            }

            if (!user.Identity.IsAuthenticated)
            {
                return(false);
            }

            if (user.IsInRole(ConstantRoles.Admin))
            {
                // Admin users have access to all of the pages.
                return(true);
            }

            // Check for dynamic permissions
            // A user gets its permissions claims from the `ApplicationClaimsPrincipalFactory` class automatically and it includes the role claims too.
            return(user.HasClaim(claim => claim.Type == ConstantPolicies.DynamicPermissionClaimType &&
                                 claim.Value == currentClaimValue));
        }
Example #3
0
        public IActionResult Index()
        {
            //_smsManagement.sendMessage("09302490811", "خوش آمدید.");
            var userId  = User.Identity.GetUserId();
            var IsAdmin = User.IsInRole(ConstantRoles.Admin);

            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission).Select(p => p.MvcActions);
            var list = new List <MvcActionViewModel>();

            foreach (var item in securedControllerActions)
            {
                list.AddRange(item);
            }

            var filteraction = new List <DashboardMenu>();

            foreach (var item in list)
            {
                foreach (var item2 in item.ActionAttributes)
                {
                    var attr = item2 as GroupingDashboard;

                    if (attr != null)
                    {
                        filteraction.Add(new DashboardMenu
                        {
                            Key     = attr._DisplayName,
                            Actions = item
                        });
                    }
                }
            }

            filteraction.Distinct();



            List <RoleClaim> userRoles = null;

            if (!IsAdmin)
            {
                userRoles = _roleManager.FindRoleClaimOfCurrentUser();
            }

            return(View(model: new UserModulesAccessViewModel
            {
                SecuredControllerActions = filteraction,
                RoleClaims = userRoles,
                IsAdmin = IsAdmin
            }));
        }
        public bool CanUserAccess(ClaimsPrincipal user, string area, string controller, string action)
        {
            var currentClaimValue        = $"{area}:{controller}:{action}";
            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            if (!securedControllerActions.SelectMany(x => x.MvcActions).Any(x => x.ActionId == currentClaimValue))
            {
                throw new KeyNotFoundException($@"The `secured` area={area}/controller={controller}/action={action} with `ConstantPolicies.DynamicPermission` policy not found. Please check you have entered the area/controller/action names correctly and also it's decorated with the correct security policy.");
            }

            if (!user.Identity.IsAuthenticated)
            {
                return(false);
            }

            return(user.HasClaim(claim => claim.Type == ConstantPolicies.DynamicPermissionClaimType &&
                                 claim.Value == currentClaimValue));
        }
        public async Task <IActionResult> Index(int?id)
        {
            if (id == null)
            {
                return(View("Error"));
            }

            var role = await _roleManager.FindRoleIncludeRoleClaimsAsync(id.Value);

            if (role == null)
            {
                return(View("NotFound"));
            }

            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            return(View(model: new DynamicRoleClaimsManagerViewModel
            {
                SecuredControllerActions = securedControllerActions,
                RoleIncludeRoleClaims = role
            }));
        }
        public async Task <IActionResult> Index(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var Role = await _roleManager.FindClaimsInRole(id);

            if (Role == null)
            {
                return(NotFound());
            }

            var SecuredControllerActions = _mvcActionsDiscovery.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            return(View(new DynamicAccessIndexViewModel
            {
                RoleIncludeRoleClaims = Role,
                SecuredControllerActions = SecuredControllerActions,
            }));
        }
        public async Task <IActionResult> Index(int userId)
        {
            if (userId == 0)
            {
                return(NotFound());
            }


            var user = await _userManager.FindClaimsInUser(userId);

            if (user == null)
            {
                return(NotFound());
            }

            var securedControllerActions = _mvcActionsDiscovery.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);

            return(View(new DynamicAccessIndexViewModel
            {
                UserIncludeUserClaims = user,
                SecuredControllerActions = securedControllerActions,
            }));
        }
Example #8
0
        public async Task <ActionResult <DynamicRoleClaimsManagerViewModel> > Get(int?id)
        {
            if (!id.HasValue)
            {
                return(BadRequest());
            }

            var role = await _roleManager.FindRoleIncludeRoleClaimsAsync(id.Value);

            if (role == null)
            {
                return(NotFound());
            }

            var securedControllerActions =
                _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies
                                                                                     .DynamicPermission);

            return(new DynamicRoleClaimsManagerViewModel
            {
                SecuredControllerActions = securedControllerActions,
                RoleIncludeRoleClaims = role
            });
        }
        public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync()
        {
            var adminUserSeed = _adminUserSeedOptions.Value.AdminUserSeed;

            var name      = adminUserSeed.Username;
            var password  = adminUserSeed.Password;
            var email     = adminUserSeed.Email;
            var roleName  = adminUserSeed.RoleName;
            var firstName = adminUserSeed.FirstName;
            var lastName  = adminUserSeed.LastName;

            var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync);

            var adminUser = await _applicationUserManager.FindByNameAsync(name);

            if (adminUser != null)
            {
                _logger.LogInformation($"{thisMethodName}: adminUser already exists.");
                return(IdentityResult.Success);
            }

            //Create the `Admin` Role if it does not exist
            var adminRole = await _roleManager.FindByNameAsync(roleName);

            if (adminRole == null)
            {
                adminRole = new AppRole(roleName);
                var adminRoleResult = await _roleManager.CreateAsync(adminRole);

                if (adminRoleResult == IdentityResult.Failed())
                {
                    _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}");
                    return(IdentityResult.Failed());
                }
            }
            else
            {
                _logger.LogInformation($"{thisMethodName}: adminRole already exists.");
            }



            adminUser = new AppUser
            {
                UserName         = name,
                Email            = email,
                EmailConfirmed   = true,
                LockoutEnabled   = true,
                RegisterDateTime = DateTime.Now,
                FirstName        = firstName,
                LastName         = lastName,
                //Gender=null,
                IsActive = true
            };
            var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password);

            if (adminUserResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false);

            if (setLockoutResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed.");
                return(IdentityResult.Failed());
            }

            var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name);

            if (addToRoleResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            ICollection <ControllerViewModel> securedControllerActions = _mvcActionsDiscovery.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);
            IList <string> allSecuredActions = securedControllerActions.SelectMany(s => s.MvcActions).ToList().Select(a => a.ActionId).ToList();

            await _roleManager.AddOrUpdateClaimsAsync(adminRole.Id, ConstantPolicies.DynamicPermissionClaimType, allSecuredActions);

            return(IdentityResult.Success);
        }