public void ExportUsers_Csv_Success(UserFilter filter) { // Arrange var helper = new TestHelper(); var controller = helper.CreateController <UserController>(Permissions.PropertyView); var headers = helper.GetService <Mock <Microsoft.AspNetCore.Http.IHeaderDictionary> >(); headers.Setup(m => m["Accept"]).Returns(ContentTypes.CONTENT_TYPE_CSV); var user = new Entity.User(Guid.NewGuid(), "username", "email", "firstname", "lastname"); var users = new[] { user }; var service = helper.GetService <Mock <IPimsAdminService> >(); var mapper = helper.GetService <IMapper>(); var page = new Paged <Entity.User>(users, filter.Page, filter.Quantity); service.Setup(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>())).Returns(page); // Act var result = controller.ExportUsers(filter); // Assert var actionResult = Assert.IsType <ContentResult>(result); var actualResult = Assert.IsType <string>(actionResult.Content); Assert.Equal(ContentTypes.CONTENT_TYPE_CSV, actionResult.ContentType); service.Verify(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>()), Times.Once()); }
public async void GetUsersAsync_Success() { // Arrange var helper = new TestHelper(); var controller = helper.CreateController <UserController>(Permissions.AdminUsers); var mapper = helper.GetService <IMapper>(); var service = helper.GetService <Mock <IPimsKeycloakService> >(); var user = new Entity.User(Guid.NewGuid(), "test", "*****@*****.**"); var users = new[] { user }; service.Setup(m => m.GetUsersAsync(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult((IEnumerable <Entity.User>)users)); // Act var result = await controller.GetUsersAsync(1, 10); // Assert var actionResult = Assert.IsType <JsonResult>(result); Assert.Null(actionResult.StatusCode); var data = Assert.IsType <Model.UserModel[]>(actionResult.Value); Assert.Equal(mapper.Map <Model.UserModel[]>(users), data, new DeepPropertyCompare()); service.Verify(m => m.GetUsersAsync(1, 10, It.IsAny <string>()), Times.Once()); }
public void ExportUsers_ExcelX_Query_Success(Uri uri) { // Arrange var helper = new TestHelper(); var controller = helper.CreateController <UserController>(Permissions.PropertyView, uri); var headers = helper.GetService <Mock <Microsoft.AspNetCore.Http.IHeaderDictionary> >(); headers.Setup(m => m["Accept"]).Returns(ContentTypes.CONTENT_TYPE_EXCELX); var user = new Entity.User(Guid.NewGuid(), "username", "email", "firstname", "lastname"); var users = new[] { user }; var service = helper.GetService <Mock <IPimsAdminService> >(); var mapper = helper.GetService <IMapper>(); var page = new Paged <Entity.User>(users); service.Setup(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>())).Returns(page); // Act var result = controller.ExportUsers(); // Assert var actionResult = Assert.IsType <FileStreamResult>(result); Assert.Equal(ContentTypes.CONTENT_TYPE_EXCELX, actionResult.ContentType); Assert.NotNull(actionResult.FileDownloadName); Assert.True(actionResult.FileStream.Length > 0); service.Verify(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>()), Times.Once()); }
/// <summary> /// Create a new instance of an AccessRequest for the specified user. /// </summary> /// <param name="id"></param> /// <param name="user"></param> /// <returns></returns> public static Entity.AccessRequest CreateAccessRequest(int id, Entity.User user) { var accessRequest = new Entity.AccessRequest() { Id = id, UserId = user.Id, User = user }; accessRequest.Agencies.Add(new Entity.AccessRequestAgency() { AgencyId = 1, Agency = new Entity.Agency() { Id = 1 }, AccessRequestId = id }); var roleId = Guid.NewGuid(); accessRequest.Roles.Add(new Entity.AccessRequestRole() { RoleId = roleId, Role = new Entity.Role() { Id = roleId }, AccessRequestId = id }); return(accessRequest); }
public void GetMyUsers_Success() { // Arrange var helper = new TestHelper(); var controller = helper.CreateController <UserController>(Permissions.AdminUsers); var mapper = helper.GetService <IMapper>(); var service = helper.GetService <Mock <IPimsAdminService> >(); var users = new Entity.User[] { EntityHelper.CreateUser("user1"), EntityHelper.CreateUser("user2") }; var paged = new Entity.Models.Paged <Entity.User>(users); var filter = new Entity.Models.UserFilter(1, 1, "test", "test", "test", "test", "test", "test", false, "test", "test", null); service.Setup(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>())).Returns(paged); // Act var result = controller.GetMyUsers(filter); // Assert var actionResult = Assert.IsType <JsonResult>(result); Assert.Null(actionResult.StatusCode); var actualResult = Assert.IsType <Pims.Api.Models.PageModel <Model.UserModel> >(actionResult.Value); Assert.Equal(mapper.Map <Model.UserModel[]>(users), actualResult.Items, new DeepPropertyCompare()); service.Verify(m => m.User.Get(It.IsAny <Entity.Models.UserFilter>()), Times.Once()); }
/// <summary> /// Create a new instance of an AccessRequest for a default user. /// </summary> /// <param name="id"></param> /// <param name="username"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="role"></param> /// <param name="agency"></param> /// <returns></returns> public static Entity.User CreateUser(Guid id, string username, string firstName = "given name", string lastName = "surname", Entity.Role role = null, Entity.Agency agency = null) { var user = new Entity.User(id, username, $"{firstName}.{lastName}@email.com") { DisplayName = $"{lastName}, {firstName}", RowVersion = new byte[] { 12, 13, 14 } }; user.Roles.Add(new Entity.UserRole(user, role ?? EntityHelper.CreateRole("Real Estate Manager"))); user.Agencies.Add(new Entity.UserAgency(user, agency ?? EntityHelper.CreateAgency())); return(user); }
public async void UpdateUserAsync_Success() { // Arrange var helper = new TestHelper(); var controller = helper.CreateController <UserController>(Permissions.AdminUsers); var mapper = helper.GetService <IMapper>(); var service = helper.GetService <Mock <IPimsKeycloakService> >(); var user = new Entity.User(Guid.NewGuid(), "test", "*****@*****.**"); service.Setup(m => m.UpdateUserAsync(It.IsAny <Entity.User>())).Returns(Task.FromResult(user)); var model = mapper.Map <AdminModels.UserModel>(user); // Act var result = await controller.UpdateUserAsync(user.Id, model); // Assert var actionResult = Assert.IsType <JsonResult>(result); Assert.Null(actionResult.StatusCode); var actualResult = Assert.IsType <AdminModels.UserModel>(actionResult.Value); var expectedResult = mapper.Map <AdminModels.UserModel>(user); Assert.Equal(expectedResult.Id, actualResult.Id); Assert.Equal(expectedResult.DisplayName, actualResult.DisplayName); Assert.Equal(expectedResult.FirstName, actualResult.FirstName); Assert.Equal(expectedResult.MiddleName, actualResult.MiddleName); Assert.Equal(expectedResult.LastName, actualResult.LastName); Assert.Equal(expectedResult.Username, actualResult.Username); Assert.Equal(expectedResult.Email, actualResult.Email); Assert.Equal(expectedResult.IsDisabled, actualResult.IsDisabled); Assert.Equal(expectedResult.EmailVerified, actualResult.EmailVerified); Assert.Equal(expectedResult.Position, actualResult.Position); Assert.Equal(expectedResult.Note, actualResult.Note); Assert.Equal(expectedResult.Agencies, actualResult.Agencies, new DeepPropertyCompare()); Assert.Equal(expectedResult.Roles, actualResult.Roles, new DeepPropertyCompare()); service.Verify(m => m.UpdateUserAsync(It.IsAny <Entity.User>()), Times.Once()); }
/// <summary> /// Update the specified user in keycloak and PIMS. /// </summary> /// <param name="user"></param> /// <exception type="KeyNotFoundException">User does not exist in keycloak or PIMS.</exception> /// <returns></returns> public async Task <Entity.User> UpdateUserAsync(Entity.User user) { var kuser = await _keycloakService.GetUserAsync(user.Id) ?? throw new KeyNotFoundException(); var euser = _pimsAdminService.User.Get(user.Id); if (user.Username != kuser.Username) { throw new InvalidOperationException($"Cannot change the username from '{kuser.Username}' to '{user.Username}'."); } var addRoles = user.Roles.Except(euser.Roles, new UserRoleRoleIdComparer()).ToArray(); var removeRoles = euser.Roles.Except(user.Roles, new UserRoleRoleIdComparer()).ToArray(); var addAgencies = user.Agencies.Except(euser.Agencies, new UserAgencyAgencyIdComparer()).ToArray(); var removeAgencies = euser.Agencies.Except(user.Agencies, new UserAgencyAgencyIdComparer()).ToArray(); // Update PIMS _mapper.Map(user, euser); // Update Roles. addRoles.ForEach(async r => { var role = _pimsAdminService.Role.Find(r.RoleId) ?? throw new KeyNotFoundException("Cannot assign a role to a user, when the role does not exist."); if (role.KeycloakGroupId == null) { throw new KeyNotFoundException("PIMS has not been synced with Keycloak."); } euser.Roles.Add(new Entity.UserRole(euser, role)); await _keycloakService.AddGroupToUserAsync(user.Id, role.KeycloakGroupId.Value); }); removeRoles.ForEach(async r => { var role = _pimsAdminService.Role.Find(r.RoleId) ?? throw new KeyNotFoundException("Cannot remove a role from a user, when the role does not exist."); if (role.KeycloakGroupId == null) { throw new KeyNotFoundException("PIMS has not been synced with Keycloak."); } euser.Roles.Remove(r); await _keycloakService.RemoveGroupFromUserAsync(user.Id, role.KeycloakGroupId.Value); }); // Update Agencies addAgencies.ForEach(a => { var agency = _pimsAdminService.Agency.Find(a.AgencyId) ?? throw new KeyNotFoundException("Cannot assign an agency to a user, when the agency does not exist."); euser.Agencies.Add(new Entity.UserAgency(euser, agency)); }); removeAgencies.ForEach(a => { euser.Agencies.Remove(a); }); _pimsAdminService.User.Update(euser); // Now update keycloak var kmodel = _mapper.Map <KModel.UserModel>(user); kmodel.Attributes = new Dictionary <string, string[]> { ["agencies"] = _pimsService.User.GetAgencies(euser.Id).Select(a => a.ToString()).ToArray(), ["displayName"] = new[] { user.DisplayName } }; await _keycloakService.UpdateUserAsync(kmodel); // TODO: Fix issue where EmailVerified will be set to false. return(euser); }
private void UpdateUser(Model.UserModel model, Entity.User entity) { entity.Agencies.Where(a => a != null).ForEach(a => a.UserId = entity.Id); entity.Roles.Where(r => r != null).ForEach(r => r.UserId = entity.Id); }
/// <summary> /// Update the specified user in keycloak and PIMS. /// </summary> /// <param name="user"></param> /// <exception type="KeyNotFoundException">User does not exist in keycloak or PIMS.</exception> /// <returns></returns> public async Task <Entity.User> UpdateUserAsync(Entity.User user) { var kuser = await _keycloakService.GetUserAsync(user.KeycloakUserId.Value) ?? throw new KeyNotFoundException("User does not exist in Keycloak"); var euser = _pimsAdminService.User.GetForKeycloakUserId(user.KeycloakUserId.Value); if (user.Username != kuser.Username) { throw new InvalidOperationException($"Cannot change the username from '{kuser.Username}' to '{user.Username}'."); } var addRoles = user.Roles.Except(euser.Roles, new UserRoleRoleIdComparer()).ToArray(); var removeRoles = euser.Roles.Except(user.Roles, new UserRoleRoleIdComparer()).ToArray(); var addAgencies = user.Agencies.Except(euser.Agencies, new UserAgencyAgencyIdComparer()).ToArray(); var removeAgencies = euser.Agencies.Except(user.Agencies, new UserAgencyAgencyIdComparer()).ToArray(); // Update PIMS _mapper.Map(user, euser); // Remove all keycloak groups from user. // TODO: Only add/remove the ones that should be removed. var userGroups = await _keycloakService.GetUserGroupsAsync(euser.KeycloakUserId.Value); foreach (var group in userGroups) { await _keycloakService.RemoveGroupFromUserAsync(user.KeycloakUserId.Value, group.Id); } foreach (var r in user.Roles) { var role = _pimsAdminService.Role.Find(r.RoleId) ?? throw new KeyNotFoundException("Cannot assign a role to a user, when the role does not exist."); if (role.KeycloakGroupId == null) { throw new KeyNotFoundException("PIMS has not been synced with Keycloak."); } _logger.LogInformation($"Adding keycloak group '{role.Name}' to user '{euser.Username}'."); await _keycloakService.AddGroupToUserAsync(user.KeycloakUserId.Value, role.KeycloakGroupId.Value); } // Update Roles. removeRoles.ForEach(r => { var role = _pimsAdminService.Role.Find(r.RoleId) ?? throw new KeyNotFoundException("Cannot remove a role from a user, when the role does not exist."); if (role.KeycloakGroupId == null) { throw new KeyNotFoundException("PIMS has not been synced with Keycloak."); } euser.Roles.Remove(r); }); addRoles.ForEach(r => { var role = _pimsAdminService.Role.Find(r.RoleId) ?? throw new KeyNotFoundException("Cannot assign a role to a user, when the role does not exist."); if (role.KeycloakGroupId == null) { throw new KeyNotFoundException("PIMS has not been synced with Keycloak."); } euser.Roles.Add(new Entity.UserRole(euser, role)); }); // Update Agencies addAgencies.ForEach(a => { var agency = _pimsAdminService.Agency.Find(a.AgencyId) ?? throw new KeyNotFoundException("Cannot assign an agency to a user, when the agency does not exist."); euser.Agencies.Add(new Entity.UserAgency(euser, agency)); }); removeAgencies.ForEach(a => { euser.Agencies.Remove(a); }); _pimsAdminService.User.Update(euser); // Now update keycloak var kmodel = _mapper.Map <KModel.UserModel>(user); kmodel.Id = user.KeycloakUserId.Value; kmodel.Attributes = new Dictionary <string, string[]> { ["agencies"] = _pimsService.User.GetAgencies(euser.Id).Select(a => a.ToString()).ToArray(), ["displayName"] = new[] { user.DisplayName } }; _logger.LogInformation($"Updating keycloak agency attribute '{kmodel.Attributes["agencies"]}' for user '{euser.Username}'."); await _keycloakService.UpdateUserAsync(kmodel); // TODO: Fix issue where EmailVerified will be set to false. return(euser); }
/// <summary> /// Creates a new instance of a UserModel object, initializes it with specified arguments. /// </summary> /// <param name="user"></param> public UserModel(Entity.User user) { this.Id = user.Id; }
/// <summary> /// Creates a new instance of a UserModel object, initializes it with specified arguments. /// </summary> /// <param name="user"></param> public UserModel(Entity.User user) { this.Id = user.Id; this.KeycloakUserId = user.KeycloakUserId; }