Esempio n. 1
0
        /// <summary>
        /// First, check that a role with this name and another ID doesn't already exist.
        ///
        /// Second, save new data into database.
        /// </summary>
        /// <param name="storage_">Storage interface provided by services container.</param>
        /// <param name="roleManager_">Role manager.</param>
        /// <param name="model_">Model with role name and grant data (extensions and permission level).</param>
        /// <returns>Null if success, otherwise error message.</returns>
        internal static async Task <string> CheckAndUpdateRoleAndGrantsAsync(IStorage storage_, RoleManager <IdentityRole <string> > roleManager_, UpdateRoleAndGrantsViewModel model_)
        {
            if (await CheckThatRoleOfThisNameExistsAsync(roleManager_, model_.RoleName, model_.RoleId))
            {
                return("A role with this name already exists");
            }

            try
            {
                // Update the role name
                var role = await roleManager_.FindByIdAsync(model_.RoleId);

                await roleManager_.SetRoleNameAsync(role, model_.RoleName);

                // Create the new links
                if (model_.Grants != null)
                {
                    // Clear all the linked extensions, save the new links
                    var permRepo = storage_.GetRepository <IRolePermissionRepository>();

                    foreach (var rolePermission in permRepo.FilteredByRoleId(model_.RoleId))
                    {
                        permRepo.Delete(rolePermission.RoleId, rolePermission.Extension);
                    }

                    foreach (ExtensionPermissionValue grantData in model_.Grants)
                    {
                        // Convert the string to the enum
                        if (Enum.TryParse <Common.Enums.Permission>(grantData.PermissionValue, true, out var permissionEnumValue))
                        {
                            var permissionEntity = storage_.GetRepository <IPermissionRepository>()
                                                   .Find(permissionEnumValue);

                            permRepo.Create(new RolePermission
                            {
                                RoleId       = model_.RoleId,
                                PermissionId = permissionEntity.Id,
                                Extension    = grantData.Extension
                            });
                        }
                    }
                }

                await storage_.SaveAsync();

                return(null);
            }
            catch (Exception e)
            {
                return($"{e.Message} {e.StackTrace}");
            }
        }
        public async Task <IActionResult> UpdateRoleAndItsPermissionsAsync([FromBody] UpdateRoleAndGrantsViewModel model_)
        {
            string error = await UpdateRoleAndGrants.CheckAndUpdateRoleAndGrantsAsync(Storage, _roleManager, model_);

            return(StatusCode(string.IsNullOrEmpty(error) ? (int)HttpStatusCode.Created : (int)HttpStatusCode.BadRequest, error));
        }
Esempio n. 3
0
        public async Task CheckAndUpdateRole_NoExtensionInList_NoChangeAsync()
        {
            string firstRoleName            = "New Role 1 " + DateTime.Now.Ticks;
            var    rolePermissionRepository = DatabaseFixture.Storage.GetRepository <IRolePermissionRepository>();
            var    permRepo = DatabaseFixture.Storage.GetRepository <IPermissionRepository>();

            try
            {
                // Arrange
                IdentityRole <string> firstRole = new IdentityRole <string>
                {
                    // Auto-incremented ID
                    Name = firstRoleName
                };
                await DatabaseFixture.RoleManager.CreateAsync(firstRole);

                var writePermissionId = permRepo.All().FirstOrDefault(p_ => p_.Name == Permission.Write.GetPermissionName())?.Id;

                // Create a link to an extension
                rolePermissionRepository.Create(new RolePermission {
                    RoleId = firstRole.Id, PermissionId = writePermissionId, Extension = "Security"
                });
                await DatabaseFixture.Storage.SaveAsync();

                UpdateRoleAndGrantsViewModel model = new UpdateRoleAndGrantsViewModel
                {
                    RoleId = firstRole.Id,

                    // Use same role name
                    RoleName = firstRoleName,
                    Grants   = null
                };

                // Execute
                var result = await UpdateRoleAndGrants.CheckAndUpdateRoleAndGrantsAsync(DatabaseFixture.Storage, DatabaseFixture.RoleManager, model);

                // Assert
                Assert.Null(result);

                // We should find one linked extension, "Security", with Write level
                var record = rolePermissionRepository.FilteredByRoleId(firstRole.Id).FirstOrDefault();
                Assert.NotNull(record);
                Assert.Equal("Security", record.Extension);
                Assert.Equal(writePermissionId, record.PermissionId);
            }
            finally
            {
                // Cleanup created data
                string[] roleNames = { firstRoleName };
                foreach (string roleName in roleNames)
                {
                    var createdRole = await DatabaseFixture.RoleManager.FindByNameAsync(roleName);

                    if (createdRole == null)
                    {
                        continue;
                    }

                    foreach (var rolePermission in rolePermissionRepository.FilteredByRoleId(createdRole.Id))
                    {
                        rolePermissionRepository.Delete(rolePermission.RoleId, rolePermission.Extension);
                    }

                    await DatabaseFixture.RoleManager.DeleteAsync(createdRole);
                }
            }
        }
Esempio n. 4
0
        public async Task CheckAndUpdateRole_Error_NameAlreadyTakenAsync()
        {
            string firstRoleName  = "New Role 1 " + DateTime.Now.Ticks;
            string secondRoleName = "New Role 2 " + DateTime.Now.Ticks;
            var    permRepo       = DatabaseFixture.Storage.GetRepository <IRolePermissionRepository>();

            try
            {
                // Arrange
                IdentityRole <string> firstRole = new IdentityRole <string>
                {
                    // Auto-incremented ID
                    Name = firstRoleName
                };
                await DatabaseFixture.RoleManager.CreateAsync(firstRole);

                IdentityRole <string> secondRole = new IdentityRole <string>
                {
                    // Auto-incremented ID
                    Name = secondRoleName
                };
                await DatabaseFixture.RoleManager.CreateAsync(secondRole);

                // Get back the second role ID
                string secondRoleId = (await DatabaseFixture.RoleManager.FindByNameAsync(secondRoleName)).Id;

                UpdateRoleAndGrantsViewModel model = new UpdateRoleAndGrantsViewModel
                {
                    RoleId = secondRoleId,

                    // Use the first role name
                    RoleName = firstRoleName,
                    Grants   = new List <ExtensionPermissionValue> {
                        new ExtensionPermissionValue {
                            Extension = "Security", PermissionValue = Permission.Write.ToString()
                        }
                    }
                };

                // Execute
                var result = await UpdateRoleAndGrants.CheckAndUpdateRoleAndGrantsAsync(DatabaseFixture.Storage, DatabaseFixture.RoleManager, model);

                // Assert
                Assert.NotNull(result);
                Assert.Equal("A role with this name already exists", result);

                // We should not find linked extension
                var record = permRepo.FilteredByRoleId(secondRoleId).FirstOrDefault();
                Assert.Null(record);
            }
            finally
            {
                // Cleanup created data
                string[] roleNames = { firstRoleName, secondRoleName };
                foreach (string roleName in roleNames)
                {
                    var createdRole = await DatabaseFixture.RoleManager.FindByNameAsync(roleName);

                    if (createdRole == null)
                    {
                        continue;
                    }

                    foreach (var rolePermission in permRepo.FilteredByRoleId(createdRole.Id))
                    {
                        permRepo.Delete(rolePermission.RoleId, rolePermission.Extension);
                    }

                    await DatabaseFixture.RoleManager.DeleteAsync(createdRole);
                }
            }
        }
Esempio n. 5
0
        public async Task CheckAndUpdateRole_ChangeAddDeleteExtensionAsync()
        {
            string roleName = "New Role 1 " + DateTime.Now.Ticks;
            var    rolePermissionRepository = DatabaseFixture.Storage.GetRepository <IRolePermissionRepository>();
            var    permRepo = DatabaseFixture.Storage.GetRepository <IPermissionRepository>();

            try
            {
                // Arrange
                IdentityRole <string> firstRole = new IdentityRole <string>
                {
                    // Auto-incremented ID
                    Name = roleName
                };
                await DatabaseFixture.RoleManager.CreateAsync(firstRole);

                // Get back the second role ID
                string roleId = (await DatabaseFixture.RoleManager.FindByNameAsync(roleName)).Id;

                var readPermissionId  = permRepo.All().FirstOrDefault(p_ => p_.Name == Permission.Read.GetPermissionName())?.Id;
                var writePermissionId = permRepo.All().FirstOrDefault(p_ => p_.Name == Permission.Write.GetPermissionName())?.Id;

                // Add a link to an extension
                rolePermissionRepository.Create(new RolePermission {
                    PermissionId = readPermissionId, RoleId = roleId, Extension = "Security"
                });
                rolePermissionRepository.Create(new RolePermission {
                    PermissionId = readPermissionId, RoleId = roleId, Extension = "Another"
                });
                await DatabaseFixture.Storage.SaveAsync();

                UpdateRoleAndGrantsViewModel model = new UpdateRoleAndGrantsViewModel
                {
                    RoleId   = roleId,
                    RoleName = roleName,
                    Grants   = new List <ExtensionPermissionValue>
                    {
                        new ExtensionPermissionValue {
                            Extension = "Security", PermissionValue = Permission.Write.ToString()
                        },
                        new ExtensionPermissionValue {
                            Extension = "ThirdExtension", PermissionValue = Permission.Write.ToString()
                        }
                    }
                };

                // Execute
                var result = await UpdateRoleAndGrants.CheckAndUpdateRoleAndGrantsAsync(DatabaseFixture.Storage, DatabaseFixture.RoleManager, model);

                // Assert
                Assert.Null(result);

                // We should find two linked extensions
                var records         = rolePermissionRepository.FilteredByRoleId(roleId);
                var rolePermissions = records as RolePermission[] ?? records.ToArray();
                Assert.Equal(2, rolePermissions.Length);
                var record = rolePermissions.FirstOrDefault(r_ => r_.Extension == "Security");
                Assert.NotNull(record);
                Assert.Equal(writePermissionId, record.PermissionId);

                record = rolePermissions.FirstOrDefault(r_ => r_.Extension == "ThirdExtension");
                Assert.NotNull(record);
                Assert.Equal(writePermissionId, record.PermissionId);
            }
            finally
            {
                // Cleanup created data
                var createdRole = await DatabaseFixture.RoleManager.FindByNameAsync(roleName);

                if (createdRole != null)
                {
                    foreach (var rolePermission in rolePermissionRepository.FilteredByRoleId(createdRole.Id))
                    {
                        rolePermissionRepository.Delete(rolePermission.RoleId, rolePermission.Extension);
                    }

                    await DatabaseFixture.RoleManager.DeleteAsync(createdRole);
                }
            }
        }