Ejemplo n.º 1
0
        private async void setupClaimsForRole(RoleManager <IdentityRole> roleManager, RoleClaim roleClaims)
        {
            await roleManager.CreateAsync(roleClaims.Role);

            foreach (var claim in roleClaims.Claims)
            {
                await roleManager.AddClaimAsync(roleClaims.Role, claim);
            }
        }
Ejemplo n.º 2
0
        async Task CreateUserAndRoles()
        {
            if (await _userManager.Users.CountAsync() > 0)
            {
                return;
            }

            using (var scope = await _context.Database.BeginTransactionAsync())
            {
                var role = new Role {
                    Name = "Administrator", Active = true
                };
                IdentityResult result = await _roleManager.CreateAsync(role);

                if (!result.Succeeded)
                {
                    scope.Rollback();
                    return;
                }

                IEnumerable <Claim> accessList = Enum.GetValues(typeof(AccessList)).Cast <AccessList>()
                                                 .Select(a => new Claim(a.ToString(), a.ToString()));

                foreach (var access in accessList)
                {
                    var claimResult = await _roleManager.AddClaimAsync(role, access);

                    if (!claimResult.Succeeded)
                    {
                        scope.Rollback();
                        return;
                    }
                }

                ISet <User> currentUser = _context.Users.ToHashSet();

                var user = new HashSet <User>
                {
                    new User {
                        UserName = "******", FirstName = "manager", LastName = "manager", Email = "*****@*****.**", UserType = UserType.Administrator, Active = true, Role = role, PasswordHash = "AAbb11"
                    },
                    new User {
                        UserName = "******", FirstName = "Ruben", LastName = "Aguirre", Email = "*****@*****.**", UserType = UserType.Operator, Active = true, Role = role, PasswordHash = "AAbb11"
                    }
                };

                user = user.Where(c => !currentUser.Any(v => v.Id == c.Id)).ToHashSet();
                foreach (var users in user)
                {
                    await _userManager.CreateAsync(users, "AAbb11");

                    await _userManager.AddToRoleAsync(users, role.Name);
                }

                scope.Commit();
            }
        }
        public static async Task AddPermissionClaim(this RoleManager <IdentityRole> roleManager, IdentityRole role, string permission)
        {
            var allClaims = await roleManager.GetClaimsAsync(role);

            if (!allClaims.Any(a => a.Type == "Permission" && a.Value == permission))
            {
                await roleManager.AddClaimAsync(role, new Claim("Permission", permission));
            }
        }
Ejemplo n.º 4
0
        public async Task <Tuple <bool, string[]> > UpdateRoleAsync(ApplicationRole role, IEnumerable <string> claims)
        {
            if (claims != null)
            {
                string[] invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
                if (invalidClaims.Any())
                {
                    return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) }));
                }
            }


            var result = await _roleManager.UpdateAsync(role);

            if (!result.Succeeded)
            {
                return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray()));
            }


            if (claims != null)
            {
                var roleClaims      = (await _roleManager.GetClaimsAsync(role)).Where(c => c.Type == ClaimConstants.Permission);
                var roleClaimValues = roleClaims.Select(c => c.Value).ToArray();

                var claimsToRemove = roleClaimValues.Except(claims).ToArray();
                var claimsToAdd    = claims.Except(roleClaimValues).Distinct().ToArray();

                if (claimsToRemove.Any())
                {
                    foreach (string claim in claimsToRemove)
                    {
                        result = await _roleManager.RemoveClaimAsync(role, roleClaims.Where(c => c.Value == claim).FirstOrDefault());

                        if (!result.Succeeded)
                        {
                            return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray()));
                        }
                    }
                }

                if (claimsToAdd.Any())
                {
                    foreach (string claim in claimsToAdd)
                    {
                        result = await _roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim)));

                        if (!result.Succeeded)
                        {
                            return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray()));
                        }
                    }
                }
            }

            return(Tuple.Create(true, new string[] { }));
        }
Ejemplo n.º 5
0
        internal static async Task AddCustomPermissionClaim(this RoleManager <IdentityRole> roleManager, IdentityRole role, string permission)
        {
            var allClaims = await roleManager.GetClaimsAsync(role);

            if (!allClaims.Any(a => a.Type == ApplicationClaimTypes.Permission && a.Value == permission))
            {
                await roleManager.AddClaimAsync(role, new Claim(ApplicationClaimTypes.Permission, permission));
            }
        }
Ejemplo n.º 6
0
        public async Task <bool> adicionarRequisicaoAfuncao([FromBody] ClaimViewModel _funcaoRequisicao)
        {
            Task <IdentityRole> funcao  = _roleManager.FindByIdAsync(_funcaoRequisicao.EmpresaUsuario.FuncaoId);
            IdentityRole        _funcao = await funcao;

            var resultado = await _roleManager.AddClaimAsync(_funcao, _funcaoRequisicao.toClaim());

            return(resultado.Succeeded);
        }
Ejemplo n.º 7
0
        public async Task <Tuple <bool, string[]> > CreateRoleAsync(ApplicationRole role, IEnumerable <string> claims)
        {
            if (claims == null)
            {
                claims = new string[] { }
            }
            ;

            IEnumerable <string> enumerable = claims as string[] ?? claims.ToArray();

            string[] invalidClaims = enumerable.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
            if (invalidClaims.Any())
            {
                return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) }));
            }


            IdentityResult result = await _roleManager.CreateAsync(role);

            if (!result.Succeeded)
            {
                return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray()));
            }


            role = await _roleManager.FindByNameAsync(role.Name);

            foreach (string claim in enumerable.Distinct())
            {
                result = await _roleManager.AddClaimAsync(role,
                                                          new Claim(CustomClaimTypes.Permission, ApplicationPermissions.GetPermissionByValue(claim)));

                if (result.Succeeded)
                {
                    continue;
                }

                await DeleteRoleAsync(role);

                return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray()));
            }

            return(Tuple.Create(true, new string[] { }));
        }
        private async Task SeedASPIdentityCoreAsync()
        {
            if (!await _context.Users.AnyAsync())
            {
                //Generating inbuilt accounts
                const string adminRoleName       = "Administrator";
                const string userRoleName        = "User";
                const string coordinatorRoleName = "Coordinator";

                await EnsureRoleAsync(adminRoleName, "Default administrator", ApplicationPermissions.GetAllPermissionValues());
                await EnsureRoleAsync(userRoleName, "Default user", new string[] { });
                await EnsureRoleAsync(coordinatorRoleName, "Default coordinator", new string[] { });

                await CreateUserAsync("admin", "Admin123456", "Admin", "YLSPTeam", "Administrator YLSP", "*****@*****.**", "+1 (123) 456-7890", new string[] { adminRoleName });
                await CreateUserAsync("user", "User123456", "User", "YLSPTeam", "User YLSP", "*****@*****.**", "+1 (123) 456-7890`", new string[] { userRoleName });
                await CreateUserAsync("coordinator", "Coordinator123456", "Coordinator", "YLSPTeam", "Coordinator YLSP", "*****@*****.**", "+7 (999) 825-0380`", new string[] { coordinatorRoleName, userRoleName });

                _logger.LogInformation("Inbuilt account generation completed");
            }
            else
            {
                const string adminRoleName = "Administrator";

                IdentityRole <Guid> adminRole = await _roleManager.FindByNameAsync(adminRoleName);

                var AllClaims  = ApplicationPermissions.GetAllPermissionValues().Distinct();
                var RoleClaims = (await _roleManager.GetClaimsAsync(adminRole)).Select(c => c.Value).ToList();
                var NewClaims  = AllClaims.Except(RoleClaims);
                foreach (string claim in NewClaims)
                {
                    await _roleManager.AddClaimAsync(adminRole, new Claim(ClaimConstants.Permission, claim));
                }
                var DeprecatedClaims = RoleClaims.Except(AllClaims);
                var roles            = await _roleManager.Roles.ToListAsync();

                foreach (string claim in DeprecatedClaims)
                {
                    foreach (var role in roles)
                    {
                        await _roleManager.RemoveClaimAsync(role, new Claim(ClaimConstants.Permission, claim));
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Update([FromBody] RoleModel model)
        {
            bool createMode = false;

            // Save role
            ApplicationRole role = _roleManager.Roles.SingleOrDefault(r => r.Id == model.Id);

            if (role == null)
            {
                createMode = true;
                role       = new ApplicationRole();
            }

            role.Name = model.Name;

            // Save permissions
            IdentityRoleClaim <string>          currentPermission  = null;
            IList <PermissionInfo>              permissions        = _securityManager.GetPermissionsList();
            IList <IdentityRoleClaim <string> > currentPermissions = role.Claims.ToList();

            if (createMode)
            {
                await _roleManager.CreateAsync(role);
            }
            else
            {
                await _roleManager.UpdateAsync(role);
            }

            foreach (PermissionInfo permission in permissions)
            {
                currentPermission = currentPermissions.SingleOrDefault(c => c.ClaimType == ModuleConfiguration.ModulePermissionType && c.ClaimValue == permission.PermissionId.ToString());

                if (currentPermission != null)
                {
                    if (!model.Permissions.Any(sp => sp == permission.PermissionId))
                    {
                        await _roleManager.RemoveClaimAsync(role, currentPermission.ToClaim());
                    }
                }
                else
                {
                    if (model.Permissions.Any(sp => sp == permission.PermissionId))
                    {
                        currentPermission            = new IdentityRoleClaim <string>();
                        currentPermission.ClaimType  = ModuleConfiguration.ModulePermissionType;
                        currentPermission.ClaimValue = permission.PermissionId.ToString();
                        currentPermission.RoleId     = role.Id;

                        await _roleManager.AddClaimAsync(role, currentPermission.ToClaim());
                    }
                }
            }

            return(Ok(new { RoleId = role.Id }));
        }
Ejemplo n.º 10
0
        public async Task Configured(IConfigure configure)
        {
            await _unitOfWorkManager.PerformAsyncUow(async() =>
            {
                foreach (var permissionProvider in _permissionProviders)
                {
                    // get and iterate stereotypical groups of permissions
                    var stereotypes = permissionProvider.GetDefaultStereotypes();
                    foreach (var stereotype in stereotypes)
                    {
                        var role = await _roleManager.FindByNameAsync(stereotype.Name);
                        if (role == null)
                        {
                            if (_logger.IsEnabled(LogLevel.Information))
                            {
                                _logger.LogInformation(
                                    $"Defining new role {stereotype.Name} for permission stereotype");
                            }

                            role = new Role {
                                RoleName = stereotype.Name
                            };
                            await _roleManager.CreateAsync(role);
                            await _unitOfWorkManager.Current.SaveChangesAsync();
                        }

                        // and merge the stereotypical permissions into that role
                        var stereotypePermissionNames =
                            (stereotype.Permissions ?? Enumerable.Empty <Permission>()).Select(x => x.Name);
                        var currentPermissionNames = (await _roleManager.GetClaimsAsync(role)).Where(x => x.Type == Permission.ClaimType)
                                                     .Select(x => x.Value).ToList();

                        var distinctPermissionNames = currentPermissionNames
                                                      .Union(stereotypePermissionNames)
                                                      .Distinct();

                        // update role if set of permissions has increased
                        var additionalPermissionNames = distinctPermissionNames.Except(currentPermissionNames).ToList();

                        if (additionalPermissionNames.Any())
                        {
                            foreach (var permissionName in additionalPermissionNames)
                            {
                                if (_logger.IsEnabled(LogLevel.Debug))
                                {
                                    _logger.LogInformation("Default role {0} granted permission {1}", stereotype.Name,
                                                           permissionName);
                                }

                                await _roleManager.AddClaimAsync(role, new Claim(Permission.ClaimType, permissionName));
                            }
                        }
                    }
                }
            });
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> Create(RoleViewModel role)
        {
            try
            {
                // TODO: Add insert logic here
                var adminRole = await _roleManager.FindByNameAsync(role.Name);

                if (adminRole == null)
                {
                    adminRole = new ApplicationRole(role.Name);
                    await _roleManager.CreateAsync(adminRole);

                    var roleList = role.Permissions.Where(r => r.IsSelected == true).ToList();
                    foreach (var r in roleList)
                    {
                        await _roleManager.AddClaimAsync(adminRole, new Claim(r.Type, r.Value));
                    }

                    /*
                     * role.Permissions.Where(r => r.IsSelected == true).ToList().ForEach(r=>
                     * {
                     *   await _roleManager.AddClaimAsync(adminRole, new Claim(r.Type, r.Value));
                     *
                     * });
                     */
                    // await _roleManager.AddClaimAsync(adminRole, new Claim(CustomClaimTypes.Permission, "projects.view"));
                    //await _roleManager.AddClaimAsync(adminRole, new Claim(CustomClaimTypes.Permission, "projects.create"));
                    //await _roleManager.AddClaimAsync(adminRole, new Claim(CustomClaimTypes.Permission, "projects.update"));
                }

                /*if (!await userManager.IsInRoleAsync(user, adminRole.Name))
                 * {
                 *  await userManager.AddToRoleAsync(user, adminRole.Name);
                 * }
                 *
                 * var accountManagerRole = await roleManager.FindByNameAsync("Account Manager");
                 *
                 * if (accountManagerRole == null)
                 * {
                 *  accountManagerRole = new IdentityRole("Account Manager");
                 *  await roleManager.CreateAsync(accountManagerRole);
                 *
                 *  await roleManager.AddClaimAsync(accountManagerRole, new Claim(CustomClaimTypes.Permission, "account.manage"));
                 * }
                 */
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ViewData["Permissions"] = _context.Permissions.Select(p => new PermissionViewModel()
                {
                    Id = p.Id, Type = p.Type, Value = p.Value, IsSelected = false
                }).ToList();
                return(View());
            }
        }
Ejemplo n.º 12
0
        public async Task <RolePermissionModel> AddRole(RolePermissionModel roleRequest)
        {
            Role role = new Role();

            role.Name = roleRequest.Name.Trim();

            var result = await _roleManager.CreateAsync(role);

            if (result.Succeeded)
            {
                foreach (var permission in roleRequest.Permissions)
                {
                    await _roleManager.AddClaimAsync(role, new Claim("permission", permission));
                }
                roleRequest.RoleId = role.Id;
                return(roleRequest);
            }
            return(null);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> addRoleClaim(string RoleName, string[] permissions)
        {
            var role = await _roleMangeer.FindByNameAsync(RoleName);

            foreach (var permission in permissions)
            {
                await _roleMangeer.AddClaimAsync(role, new Claim("permission", permission));
            }
            return(Ok());
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> Index(string id)
        {
            await _roleManager.CreateAsync(new MongoRole("Admin"));

            var role = await _roleManager.FindByNameAsync("Admin");

            await _roleManager.AddClaimAsync(role, new Claim("Permission", "ManageCourses"));

            return(View(_userManager.Users));
        }
Ejemplo n.º 15
0
        //public async Task<ActionResult> Create(tring roleName, string[] permissions)
        public async Task <ActionResult> Create([Bind("Name, Claims")] Role role)
        {
            if (ModelState.IsValid)
            {
                var newRole = new IdentityRole(role.Name);
                var result  = await _roleManager.CreateAsync(newRole);

                if (result.Succeeded)
                {
                    foreach (String perm in role.Claims)
                    {
                        await _roleManager.AddClaimAsync(newRole, new Claim(perm, "Allowed"));
                    }
                }
                return(RedirectToAction("Index"));
            }

            return(View());
        }
Ejemplo n.º 16
0
        public async Task <bool> AddRoleClaims(string RoleName, List <string> Claims)
        {
            var role = await _roleManager.FindByNameAsync(RoleName);

            foreach (var item in Claims)
            {
                await _roleManager.AddClaimAsync(role, new Claim("Permission", item));
            }
            return(true);
        }
        public async Task <IdentityResult> CreateClaims(string id, string claimType, string claimValue)
        {
            var role = await _roleManager.FindByIdAsync(id);

            if (role == null)
            {
                return(null);
            }
            return(await _roleManager.AddClaimAsync(role, new System.Security.Claims.Claim(claimType, claimValue)));
        }
Ejemplo n.º 18
0
        public async Task <Role> Add(string role, List <string> claims, bool active, bool basic)
        {
            Roles roleResult;
            var   roleCheck = await _roleManager.RoleExistsAsync(role);

            if (roleCheck)
            {
                return(null);
            }
            await _roleManager.CreateAsync(new Roles(role) { Active = active, Basic = basic });

            roleResult = await _roleManager.FindByNameAsync(role);

            foreach (var claim in claims)
            {
                await _roleManager.AddClaimAsync(roleResult, new System.Security.Claims.Claim(CustomClaimTypes.Permission, claim));
            }
            return(_mapper.Map <Roles, Role>(roleResult));
        }
        public async Task <IOperationResult <RoleViewModel> > UpdateRoleAsync(RoleViewModel roleView)
        {
            _logger.LogDebug($"Executing {nameof(UpdateRoleAsync)}. Param: {JsonConvert.SerializeObject(roleView)}");

            var roleManagerRole = await _roleManager.FindByIdAsync(roleView.Id);

            if (roleManagerRole == null)
            {
                _logger.LogDebug($"Executed {nameof(UpdateRoleAsync)}.  Returned NoRole.");

                return(OperationResult <RoleViewModel> .Failed(new OperationError()
                {
                    Name = "NoRole", Description = "Specified role does not exist"
                }));
            }

            roleManagerRole.Name = roleView.Name;
            var updateRoleResult = await _roleManager.UpdateAsync(roleManagerRole);

            if (!updateRoleResult.Succeeded)
            {
                _logger.LogDebug($"Executed {nameof(UpdateRoleAsync)}.  Returned IdentityError.");

                return(OperationResult <RoleViewModel> .Failed(updateRoleResult.Errors.Select(err => new OperationError()
                {
                    Name = "IdentityError", Description = err.Description
                }).ToArray()));
            }

            var claims = await _roleManager.GetClaimsAsync(roleManagerRole);

            var claimsToRemove = claims.Where(c => !roleView.Permissions.Any(rp => rp.Equals(c.Value))).ToList();
            var claimsToAdd    = roleView.Permissions.Where(rp => !claims.Any(c => c.Value.Equals(rp))).Select(p => new Claim(CustomClaimTypes.Permission, p));

            var removeTasks = claimsToRemove.Select(claim => _roleManager.RemoveClaimAsync(roleManagerRole, claim));
            var addTasks    = claimsToAdd.Select(claim => _roleManager.AddClaimAsync(roleManagerRole, claim));

            await Task.WhenAll(removeTasks.Union(addTasks).ToList());

            _logger.LogDebug($"Executed {nameof(UpdateRoleAsync)}.  Returned RoleModel.");

            return(OperationResult <RoleViewModel> .Success(roleView));
        }
Ejemplo n.º 20
0
        public static async Task SeedUsers(ApplicationDbContext context, UserManager <ApplicationUser> userManager,
                                           RoleManager <IdentityRole> roleManager, ILogger <DbInitializer> logger)
        {
            string username1 = "*****@*****.**";
            string username2 = "*****@*****.**";
            string username3 = "*****@*****.**";
            string username4 = "*****@*****.**";
            string username5 = "*****@*****.**";
            string username6 = "*****@*****.**";

            string adminRole = "Admin";

            await CreateRole(roleManager, adminRole);

            IdentityRole Admin = context.Roles.FirstOrDefault(x => x.Name == "Admin");
            await roleManager.AddClaimAsync(Admin, new Claim("CanEdit", "CanEdit"));

            ApplicationUser user1 = await userManager.FindByNameAsync(username1);

            var createdUser1 = await MakeUser(user1, username1, userManager);

            await userManager.AddToRoleAsync(createdUser1, adminRole);

            await SetPasswordForUser(userManager, logger, username1, createdUser1);

            ApplicationUser user2 = await userManager.FindByNameAsync(username2);

            var createdUser2 = await MakeUser(user2, username2, userManager);

            await SetPasswordForUser(userManager, logger, username2, createdUser2);

            ApplicationUser user3 = await userManager.FindByNameAsync(username3);

            var createdUser3 = await MakeUser(user3, username3, userManager);

            await SetPasswordForUser(userManager, logger, username3, createdUser3);

            ApplicationUser user4 = await userManager.FindByNameAsync(username4);

            var createdUser4 = await MakeUser(user4, username4, userManager);

            await SetPasswordForUser(userManager, logger, username4, createdUser4);

            ApplicationUser user5 = await userManager.FindByNameAsync(username5);

            var createdUser5 = await MakeUser(user5, username5, userManager);

            await SetPasswordForUser(userManager, logger, username5, createdUser5);

            ApplicationUser user6 = await userManager.FindByNameAsync(username6);

            var createdUser6 = await MakeUser(user6, username6, userManager);

            await SetPasswordForUser(userManager, logger, username6, createdUser6);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Update roles via RoleManager.
        /// </summary>
        /// <returns>A update action task.</returns>
        private async Task UpdateRolesAsync()
        {
            IdentityResult result;

            foreach (var roleInfo in Roles)
            {
                bool exist = await RoleManager.RoleExistsAsync(roleInfo.Name);

                if (!exist)
                {
                    var role = RoleFactory(roleInfo);
                    result = await RoleManager.CreateAsync(role);

                    if (result.Succeeded)
                    {
                        foreach (var claim in roleInfo.Claims)
                        {
                            result = await RoleManager.AddClaimAsync(role, new Claim(claim.Type, claim.Value));

                            if (!result.Succeeded)
                            {
                                HandleIdentityErrors(result.Errors);
                            }
                        }
                    }
                    else
                    {
                        HandleIdentityErrors(result.Errors);
                    }
                }
                else
                {
                    var role = await RoleManager.FindByNameAsync(roleInfo.Name);

                    var claims = await RoleManager.GetClaimsAsync(role);

                    foreach (var claim in roleInfo.Claims)
                    {
                        if (claims.Any(x => x.Type == claim.Type && x.Value == claim.Value))
                        {
                            continue;
                        }
                        else
                        {
                            result = await RoleManager.AddClaimAsync(role, new Claim(claim.Type, claim.Value));

                            if (!result.Succeeded)
                            {
                                HandleIdentityErrors(result.Errors);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public async Task <ActionResult <bool> > CreateRoleClaims([FromServices] RoleManager <IdentityRole> RoleManager)
        {
            string[]       roleNames = { "TC", "Employee", "Finance", "Operation" };
            IdentityResult roleResult;
            List <Claim>   AllClaim = ClaimStore.GetClaims();


            foreach (var roleName in roleNames)
            {
                var roleExist = await RoleManager.RoleExistsAsync(roleName);

                if (!roleExist)
                {
                    IdentityRole identityRole = new IdentityRole(roleName);
                    //create the roles and seed them to the database: Question 1
                    roleResult = await RoleManager.CreateAsync(identityRole);

                    if (roleResult.Succeeded)
                    {
                    }
                }
            }

            var identityRoleTc = RoleManager.Roles.Where(p => p.Name == "TC").FirstOrDefault();
            var AlreadyClaims  = (await RoleManager.GetClaimsAsync(identityRoleTc)).Select(p => p.Type).ToList();
            var toBeInserted   = AllClaim.Where(p => !AlreadyClaims.Contains(p.Type) && p.Type.IndexOf("Gateway_") >= -1).ToList();

            foreach (var t in toBeInserted)
            {
                var result = await RoleManager.AddClaimAsync(identityRoleTc, t);
            }

            var identityRoleEmployee = RoleManager.Roles.Where(p => p.Name == "Employee").FirstOrDefault();
            var toBeInsertedEmp      = AllClaim.Where(p => !AlreadyClaims.Contains(p.Type) && p.Type.IndexOf("Emp_") >= -1).ToList();

            foreach (var t in toBeInsertedEmp)
            {
                var result = await RoleManager.AddClaimAsync(identityRoleEmployee, t);
            }

            return(true);
        }
Ejemplo n.º 23
0
        public async Task <(bool Succeeded, string[] Errors)> CreateRoleAsync(ApplicationRole role,
                                                                              IEnumerable <string> claims)
        {
            if (claims == null)
            {
                claims = new string[] { }
            }
            ;

            var invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();

            if (invalidClaims.Any())
            {
                return(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) });
            }


            var result = await _roleManager.CreateAsync(role);

            if (!result.Succeeded)
            {
                return(false, result.Errors.Select(e => e.Description).ToArray());
            }


            role = await _roleManager.FindByNameAsync(role.Name);

            foreach (var claim in claims.Distinct())
            {
                result = await _roleManager.AddClaimAsync(role,
                                                          new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim)));

                if (!result.Succeeded)
                {
                    await DeleteRoleAsync(role);

                    return(false, result.Errors.Select(e => e.Description).ToArray());
                }
            }

            return(true, new string[] { });
        }
Ejemplo n.º 24
0
        public static async Task <IdentityResult> AddPermissionClaim(this RoleManager <BlazorHeroRole> roleManager, BlazorHeroRole role, string permission)
        {
            var allClaims = await roleManager.GetClaimsAsync(role);

            if (!allClaims.Any(a => a.Type == ApplicationClaimTypes.Permission && a.Value == permission))
            {
                return(await roleManager.AddClaimAsync(role, new Claim(ApplicationClaimTypes.Permission, permission)));
            }

            return(IdentityResult.Failed());
        }
Ejemplo n.º 25
0
        public async Task CreateAsync(RoleDto role)
        {
            var identityRole = new IdentityRole {
                Name = role.Name
            };

            await _roleManager.CreateAsync(identityRole);

            if (role.Claims == null)
            {
                return;
            }

            identityRole = await _roleManager.FindByNameAsync(role.Name);

            await role.Claims.ForEachAsync(async claim =>
            {
                await _roleManager.AddClaimAsync(identityRole, new Claim(claim.Type, claim.Value));
            });
        }
        public async Task <ActionResult> ManageClaim(string id, RoleClaimsViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                if (!String.IsNullOrEmpty(id))
                {
                    IdentityRole identityRole = await _roleManager.FindByIdAsync(id);

                    if (identityRole != null)
                    {
                        //Get claims associated with the role
                        IList <Claim> roleClaimList = await _roleManager.GetClaimsAsync(identityRole);

                        //Extract the claim type
                        List <string> roleClaimTypeList = new List <string>();
                        foreach (var roleClaim in roleClaimList)
                        {
                            roleClaimTypeList.Add(roleClaim.Type);
                        }

                        foreach (var roleClaim in viewModel.RoleClaims)
                        {
                            //create a new claim with the claim name
                            Claim claim = new Claim(roleClaim.ClaimName, "");

                            //get the associated claim from the role's claim list
                            Claim associatedClaim = roleClaimList.Where(x => x.Type == roleClaim.ClaimName).FirstOrDefault();

                            if (roleClaim.HasClaim && !roleClaimTypeList.Contains(roleClaim.ClaimName))
                            {
                                IdentityResult claimResult = await _roleManager.AddClaimAsync(identityRole, claim);

                                if (!claimResult.Succeeded)
                                {
                                    _logger.LogError(LoggingEvents.UserConfiguration, LoggingErrorText.addClaimFailed, roleClaim.ClaimName, identityRole, _userManager.GetUserName(User), GetDataErrors.GetErrors(claimResult));
                                }
                            }
                            else if (!roleClaim.HasClaim && roleClaimTypeList.Contains(roleClaim.ClaimName))
                            {
                                IdentityResult claimResult = await _roleManager.RemoveClaimAsync(identityRole, associatedClaim);

                                if (!claimResult.Succeeded)
                                {
                                    _logger.LogError(LoggingEvents.UserConfiguration, LoggingErrorText.removeClaimFailed, roleClaim.ClaimName, identityRole, _userManager.GetUserName(User), GetDataErrors.GetErrors(claimResult));
                                }
                            }
                        }
                    }
                    return(RedirectToAction("Index"));
                }
            }

            return(View(viewModel));
        }
Ejemplo n.º 27
0
        public async Task <RoleClaim> CreateAsync(RoleClaim entity, CancellationToken cancellationToken = default)
        {
            var role = await GetRoleAsync(entity.RoleId)
                       .ConfigureAwait(false);

            var claim  = entity.ToRoleClaim().ToClaim();
            var result = await _roleManager.AddClaimAsync(role, claim)
                         .ConfigureAwait(false);

            if (result.Succeeded)
            {
                entity.Id = role.Id;
                _logger.LogInformation("Entity {EntityId} created", entity.Id, entity);
                return(entity);
            }
            throw new IdentityException
                  {
                      Errors = result.Errors
                  };
        }
Ejemplo n.º 28
0
        public async Task <ActionResult> ManageClaim(string id, RoleClaimsViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                if (!String.IsNullOrEmpty(id))
                {
                    IdentityRole identityRole = await roleManager.FindByIdAsync(id);

                    if (identityRole != null)
                    {
                        //Get claims associated with the role
                        IList <Claim> roleClaimList = await roleManager.GetClaimsAsync(identityRole);

                        //Extract the claim type
                        List <string> roleClaimTypeList = new List <string>();
                        foreach (var roleClaim in roleClaimList)
                        {
                            roleClaimTypeList.Add(roleClaim.Type);
                        }

                        foreach (var roleClaim in viewModel.RoleClaims)
                        {
                            //create a new claim with the claim name
                            Claim claim = new Claim(roleClaim.ClaimName, "");
                            //get the associated claim from the role's claim list
                            Claim associatedClaim = roleClaimList.Where(x => x.Type == roleClaim.ClaimName).FirstOrDefault();

                            if (roleClaim.HasClaim && !roleClaimTypeList.Contains(roleClaim.ClaimName))
                            {
                                IdentityResult claimResult = await roleManager.AddClaimAsync(identityRole, claim);

                                if (!claimResult.Succeeded)
                                {
                                    //TODO log details and display some sort of error
                                }
                            }
                            else if (!roleClaim.HasClaim && roleClaimTypeList.Contains(roleClaim.ClaimName))
                            {
                                IdentityResult claimResult = await roleManager.RemoveClaimAsync(identityRole, associatedClaim);

                                if (!claimResult.Succeeded)
                                {
                                    //TODO log details and display some sort of error
                                }
                            }
                        }
                    }
                    return(RedirectToAction("Index"));
                }
            }


            return(View(viewModel));
        }
Ejemplo n.º 29
0
        async Task InstallInternalAsync(IEnumerable <IPermissionsProvider <Permission> > permissions)
        {
            // Iterate through all permission providers
            foreach (var permissionProvider in permissions)
            {
                // Get default permissions from provider
                var defaultPermissions = permissionProvider.GetDefaultPermissions();

                // Iterate through default permissions
                // Create a role with the permissions if one does not exist
                // If role exists merge found default permissions with role

                foreach (var defaultPermission in defaultPermissions)
                {
                    // Attempt to get existing role
                    var role = await _roleManager.FindByNameAsync(defaultPermission.RoleName);

                    // No existing role
                    if (role == null)
                    {
                        // Create the role
                        var result = await _roleManager.CreateAsync(new Role
                        {
                            Name = defaultPermission.RoleName
                        });

                        if (result.Succeeded)
                        {
                            // Get the newly created role
                            role = await _roleManager.FindByNameAsync(defaultPermission.RoleName);
                        }
                    }

                    // Merge the default permissions into the new or existing role
                    var defaultPermissionNames = (defaultPermission.Permissions ?? Enumerable.Empty <Permission>()).Select(x => x.Name);
                    var currentPermissionNames = role.RoleClaims.Where(x => x.ClaimType == Permission.ClaimTypeName).Select(x => x.ClaimValue).ToList();

                    var distinctPermissionNames = currentPermissionNames
                                                  .Union(defaultPermissionNames)
                                                  .Distinct();

                    // Update role if set of permissions has increased
                    var additionalPermissionNames = distinctPermissionNames.Except(currentPermissionNames).ToList();

                    if (additionalPermissionNames.Count > 0)
                    {
                        foreach (var permissionName in additionalPermissionNames)
                        {
                            await _roleManager.AddClaimAsync(role, new Claim(Permission.ClaimTypeName, permissionName));
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public async Task <ActionResult <bool> > AddRoles(string roleName)
        {
            try
            {
                await _roleManager.CreateAsync(new IdentityRole(roleName));

                var findRole = await _roleManager.FindByNameAsync(roleName);

                await _roleManager.AddClaimAsync(findRole, new Claim(CustomClaimType.Permission, Permissions.Dashboards.View));

                await _roleManager.AddClaimAsync(findRole, new Claim(CustomClaimType.Permission, Permissions.Dashboards.Create));
            }
            catch (Exception e)
            {
                throw;
            }


            return(Ok(true));
        }