.setName("Ada Lovelace")
.setScmAccounts(singletonList("al")));
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
verifyThatUserIsDeactivated(user.getLogin());
}
.setName("Ada Lovelace")
.setScmAccounts(singletonList("al")));
- userService.deactivate(user.getLogin(), true);
+ userService.deactivate(user.getUuid(), true);
verifyThatUserIsDeactivated("anonymized");
verifyThatUserIsAnomymized("anonymized");
db.users().insertGroup();
db.users().insertMember(group1, user);
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().groupMembershipDao().selectGroupUuidsByUserUuid(dbSession, user.getUuid())).isEmpty();
}
db.users().insertToken(user);
db.commit();
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(),false);
assertThat(db.getDbClient().userTokenDao().selectByUser(dbSession, user)).isEmpty();
}
db.properties().insertProperty(newUserPropertyDto(user).setEntityUuid(project.uuid()), project.getKey(),
project.name(), project.qualifier(), user.getLogin());
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).build(), dbSession)).isEmpty();
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).setEntityUuid(project.uuid()).build(), dbSession)).isEmpty();
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project);
db.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, project);
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid())).isEmpty();
assertThat(db.getDbClient().userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), project.uuid())).isEmpty();
db.permissionTemplates().addUserToTemplate(template.getUuid(), user.getUuid(), UserRole.USER, template.getName(), user.getLogin());
db.permissionTemplates().addUserToTemplate(anotherTemplate.getUuid(), user.getUuid(), UserRole.CODEVIEWER, anotherTemplate.getName(), user.getLogin());
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().permissionTemplateDao().selectUserPermissionsByTemplateId(dbSession, template.getUuid())).extracting(PermissionTemplateUserDto::getUserUuid)
.isEmpty();
QProfileDto profile = db.qualityProfiles().insert();
db.qualityProfiles().addUserPermission(profile, user);
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().qProfileEditUsersDao().exists(dbSession, profile, user)).isFalse();
}
db.properties().insertProperty(new PropertyDto().setKey("other").setValue(user.getLogin())
.setEntityUuid(anotherProject.uuid()), anotherProject.getKey(), anotherProject.name(), anotherProject.qualifier(), user.getLogin());
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setKey("sonar.issues.defaultAssigneeLogin").build(), db.getSession())).isEmpty();
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().build(), db.getSession())).extracting(PropertyDto::getKey).containsOnly("other");
db.qualityGates().addUserPermission(qualityGate, user);
assertThat(db.countRowsOfTable("qgate_user_permissions")).isOne();
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.countRowsOfTable("qgate_user_permissions")).isZero();
}
UserDto anotherUser = db.users().insertUser();
db.almPats().insert(p -> p.setUserUuid(anotherUser.getUuid()), p -> p.setAlmSettingUuid(almSettingDto.getUuid()));
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(dbSession, user.getUuid(), almSettingDto)).isEmpty();
assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(dbSession, anotherUser.getUuid(), almSettingDto)).isNotNull();
UserDto anotherUser = db.users().insertUser();
SessionTokenDto sessionToken3 = db.users().insertSessionToken(anotherUser);
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(dbSession, sessionToken1.getUuid())).isNotPresent();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(dbSession, sessionToken2.getUuid())).isNotPresent();
UserDismissedMessageDto msg3 = db.users().insertUserDismissedMessageOnProject(anotherUser, project1, MessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
UserDismissedMessageDto msg4 = db.users().insertUserDismissedMessageOnProject(anotherUser, project2, MessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
- userService.deactivate(user.getLogin(), false);
+ userService.deactivate(user.getUuid(), false);
assertThat(db.getDbClient().userDismissedMessagesDao().selectByUser(dbSession, user)).isEmpty();
assertThat(db.getDbClient().userDismissedMessagesDao().selectByUser(dbSession, anotherUser))
db.users().insertGlobalPermissionOnUser(admin, GlobalPermission.ADMINISTER);
assertThatThrownBy(() -> {
- userService.deactivate(admin.getLogin(), false);
+ userService.deactivate(admin.getUuid(), false);
})
.isInstanceOf(BadRequestException.class)
.hasMessage("User is last administrator, and cannot be deactivated");
UserDto anotherAdmin = createAdminUser();
- userService.deactivate(admin.getLogin(), false);
+ userService.deactivate(admin.getUuid(), false);
verifyThatUserIsDeactivated(admin.getLogin());
verifyThatUserExists(anotherAdmin.getLogin());
db.getDbClient().scimUserDao().enableScimForUser(dbSession, user.getUuid());
db.commit();
- userService.deactivate(user.getLogin(), true);
+ userService.deactivate(user.getUuid(), true);
assertThat(db.getDbClient().scimUserDao().findByUserUuid(dbSession, user.getUuid())).isEmpty();
}
UserDto user = db.users().insertUser();
doThrow(new IllegalStateException("User managed")).when(managedInstanceChecker).throwIfUserIsManaged(any(), eq(user.getUuid()));
- String login = user.getLogin();
- assertThatThrownBy(() -> userService.deactivate(login, false))
+ String uuid = user.getUuid();
+ assertThatThrownBy(() -> userService.deactivate(uuid, false))
.isInstanceOf(IllegalStateException.class)
.hasMessage("User managed");
}
when(managedInstanceService.isUserManaged(any(), eq(user.getUuid()))).thenReturn(false);
- UserInformation result = userService.fetchUser(user.getLogin());
+ UserInformation result = userService.fetchUser(user.getUuid());
UserDto resultUser = result.userDto();
Collection<String> resultGroups = result.groups();
updateUser.setEmail("newemail@example.com");
updateUser.setScmAccounts(List.of("account1", "account2"));
- userService.updateUser(user.getLogin(), updateUser);
+ userService.updateUser(user.getUuid(), updateUser);
UserDto updatedUser = db.users().selectUserByLogin(user.getLogin()).orElseThrow();
public UserDto deactivateUser(DbSession dbSession, String login) {
UserDto user = doBeforeDeactivation(dbSession, login);
- deactivateUser(dbSession, user);
- return user;
+ return deactivateUser(dbSession, user);
}
public UserDto deactivateUserWithAnonymization(DbSession dbSession, String login) {
UserDto user = doBeforeDeactivation(dbSession, login);
anonymizeUser(dbSession, user);
- deactivateUser(dbSession, user);
- return user;
+ return deactivateUser(dbSession, user);
}
private UserDto doBeforeDeactivation(DbSession dbSession, String login) {
return user;
}
- private UserDto getUserOrThrow(DbSession dbSession, String login) {
- UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
- return checkFound(user, "User '%s' doesn't exist", login);
- }
-
private void ensureNotLastAdministrator(DbSession dbSession, UserDto user) {
boolean isLastAdmin = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingUser(dbSession, ADMINISTER.getKey(), user.getUuid()) == 0;
checkRequest(!isLastAdmin, "User is last administrator, and cannot be deactivated");
dbClient.scimUserDao().deleteByUserUuid(dbSession, user.getUuid());
}
- private void deactivateUser(DbSession dbSession, UserDto user) {
+ private UserDto deactivateUser(DbSession dbSession, UserDto user) {
dbClient.userDao().deactivateUser(dbSession, user);
dbSession.commit();
+ return getUserOrThrow(dbSession, user.getLogin());
+ }
+
+ private UserDto getUserOrThrow(DbSession dbSession, String login) {
+ UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
+ return checkFound(user, "User '%s' doesn't exist", login);
}
}
return users.stream().map(UserDto::getUuid).collect(Collectors.toSet());
}
- public UserDto deactivate(String login, Boolean anonymize) {
+ public UserDto deactivate(String uuid, Boolean anonymize) {
try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto userDto = findUserOrThrow(login, dbSession);
- managedInstanceChecker.throwIfUserIsManaged(dbSession, userDto.getUuid());
+ UserDto userDto = findUserOrThrow(uuid, dbSession);
+ managedInstanceChecker.throwIfUserIsManaged(dbSession, uuid);
UserDto deactivatedUser;
if (Boolean.TRUE.equals(anonymize)) {
- deactivatedUser = userDeactivator.deactivateUserWithAnonymization(dbSession, login);
+ deactivatedUser = userDeactivator.deactivateUserWithAnonymization(dbSession, userDto.getLogin());
} else {
- deactivatedUser = userDeactivator.deactivateUser(dbSession, login);
+ deactivatedUser = userDeactivator.deactivateUser(dbSession, userDto.getLogin());
}
dbSession.commit();
return deactivatedUser;
}
}
- private UserDto findUserOrThrow(String login, DbSession dbSession) {
- return checkFound(dbClient.userDao().selectByLogin(dbSession, login), USER_NOT_FOUND_MESSAGE, login);
- }
-
- public UserInformation fetchUser(String login) {
- try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto userDto = findUserOrThrow(login, dbSession);
- Collection<String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, Set.of(login)).get(login);
- int tokenCount = dbClient.userTokenDao().selectByUser(dbSession, userDto).size();
- boolean isManaged = managedInstanceService.isUserManaged(dbSession, userDto.getUuid());
- return toUserSearchResult(groups, tokenCount, isManaged, userDto);
- }
- }
-
private UserInformation toUserSearchResult(Collection<String> groups, int tokenCount, boolean managed, UserDto userDto) {
return new UserInformation(
userDto,
if (Boolean.FALSE.equals(userCreateRequest.isLocal())) {
newUserBuilder.setExternalIdentity(new ExternalIdentity(SQ_AUTHORITY, login, login));
}
- return registerUser(dbSession, login, newUserBuilder);
+ return registerUser(dbSession, login, newUserBuilder.build());
}
}
- private UserInformation registerUser(DbSession dbSession, String login, NewUser.Builder newUserBuilder) {
- UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
+ private UserInformation registerUser(DbSession dbSession, String uuid, NewUser newUserBuilder) {
+ UserDto user = dbClient.userDao().selectByLogin(dbSession, newUserBuilder.login());
if (user == null) {
- user = userUpdater.createAndCommit(dbSession, newUserBuilder.build(), u -> {
+ user = userUpdater.createAndCommit(dbSession, newUserBuilder, u -> {
});
} else {
- checkArgument(!user.isActive(), "An active user with login '%s' already exists", login);
- user = userUpdater.reactivateAndCommit(dbSession, user, newUserBuilder.build(), u -> {
+ checkArgument(!user.isActive(), "An active user with login '%s' already exists", user.getLogin());
+ user = userUpdater.reactivateAndCommit(dbSession, user, newUserBuilder, u -> {
});
}
- return fetchUser(user.getLogin());
+ return fetchUser(user.getUuid());
}
public static void validateScmAccounts(List<String> scmAccounts) {
}
}
- public UserInformation updateUser(String login, UpdateUser updateUser) {
+ public UserInformation updateUser(String uuid, UpdateUser updateUser) {
try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto userDto = findUserOrThrow(login, dbSession);
+ UserDto userDto = findUserOrThrow(uuid, dbSession);
userUpdater.updateAndCommit(dbSession, userDto, updateUser, u -> {
});
- return fetchUser(userDto.getLogin());
+ return fetchUser(userDto.getUuid());
}
}
+ public UserInformation fetchUser(String uuid) {
+ try (DbSession dbSession = dbClient.openSession(false)) {
+ UserDto userDto = findUserOrThrow(uuid, dbSession);
+ Collection<String> groups = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, Set.of(userDto.getLogin())).get(userDto.getLogin());
+ int tokenCount = dbClient.userTokenDao().selectByUser(dbSession, userDto).size();
+ boolean isManaged = managedInstanceService.isUserManaged(dbSession, uuid);
+ return toUserSearchResult(groups, tokenCount, isManaged, userDto);
+ }
+ }
+
+ private UserDto findUserOrThrow(String uuid, DbSession dbSession) {
+ return checkFound(dbClient.userDao().selectByUuid(dbSession, uuid), USER_NOT_FOUND_MESSAGE, uuid);
+ }
+
}
}
@Override
- public void deactivate(String login, Boolean anonymize) {
+ public void deactivate(String id, Boolean anonymize) {
userSession.checkLoggedIn().checkIsSystemAdministrator();
- checkRequest(!login.equals(userSession.getLogin()), "Self-deactivation is not possible");
- userService.deactivate(login, anonymize);
+ checkRequest(!id.equals(userSession.getUuid()), "Self-deactivation is not possible");
+ userService.deactivate(id, anonymize);
}
@Override
- public RestUser fetchUser(String login) {
- return usersSearchResponseGenerator.toRestUser(userService.fetchUser(login));
+ public RestUser fetchUser(String id) {
+ return usersSearchResponseGenerator.toRestUser(userService.fetchUser(id));
}
@Override
- public RestUser updateUser(String login, UserUpdateRestRequest updateRequest) {
+ public RestUser updateUser(String id, UserUpdateRestRequest updateRequest) {
userSession.checkLoggedIn().checkIsSystemAdministrator();
UpdateUser update = toUpdateUser(updateRequest);
- UserInformation updatedUser = userService.updateUser(login, update);
+ UserInformation updatedUser = userService.updateUser(id, update);
return usersSearchResponseGenerator.toRestUser(updatedUser);
}
@Valid @ParameterObject UsersSearchRestRequest usersSearchRestRequest,
@Valid @ParameterObject RestPage restPage);
- @DeleteMapping(path = "/{login}")
+ @DeleteMapping(path = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Operation(summary = "Deactivate a user", description = "Deactivates a user. Requires Administer System permission.")
void deactivate(
- @PathVariable("login") @Parameter(description = "The login of the user to delete.", required = true, in = ParameterIn.PATH) String login,
+ @PathVariable("id") @Parameter(description = "The ID of the user to delete.", required = true, in = ParameterIn.PATH) String id,
@RequestParam(value = "anonymize", required = false, defaultValue = "false") @Parameter(description = "Anonymize user in addition to deactivating it.") Boolean anonymize);
- @GetMapping(path = "/{login}")
+ @GetMapping(path = "/{id}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Fetch a single user", description = """
Fetch a single user.
'tokensCount'
Field 'sonarqubeLastConnectionDate' is only updated every hour, so it may not be accurate, for instance when a user authenticates many times in less than one hour.
""")
- RestUser fetchUser(@PathVariable("login") @Parameter(description = "The login of the user to fetch.", required = true, in = ParameterIn.PATH) String login);
+ RestUser fetchUser(@PathVariable("id") @Parameter(description = "The id of the user to fetch.", required = true, in = ParameterIn.PATH) String id);
- @PatchMapping(path = "/{login}", consumes = JSON_MERGE_PATCH_CONTENT_TYPE, produces = MediaType.APPLICATION_JSON_VALUE)
+ @PatchMapping(path = "/{id}", consumes = JSON_MERGE_PATCH_CONTENT_TYPE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Update a user", description = """
Update a user.
Allows updating user's name, email and SCM accounts.
""")
- RestUser updateUser(@PathVariable("login") String login, @Valid @RequestBody UserUpdateRestRequest updateRequest);
+ RestUser updateUser(@PathVariable("id") String id, @Valid @RequestBody UserUpdateRestRequest updateRequest);
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public RestUser toRestUser(UserInformation userInformation) {
UserDto userDto = userInformation.userDto();
+ String id = userDto.getUuid();
String login = userDto.getLogin();
String name = userDto.getName();
if (!userSession.isLoggedIn()) {
- return new RestUserForAnonymousUsers(login, login, name);
+ return new RestUserForAnonymousUsers(id, login, name);
}
String avatar = userInformation.avatar().orElse(null);
String slLastConnectionDate = toDateTime(userDto.getLastSonarlintConnectionDate());
List<String> scmAccounts = userInformation.userDto().getSortedScmAccounts();
return new RestUserForAdmins(
- login,
+ id,
login,
name,
email,
slLastConnectionDate,
scmAccounts);
}
- return new RestUserForLoggedInUsers(login, login, name, email, active, local, externalIdentityProvider, avatar);
+ return new RestUserForLoggedInUsers(id, login, name, email, active, local, externalIdentityProvider, avatar);
}
private static String toDateTime(@Nullable Long dateTimeMs) {
@Test
public void deactivate_whenUserTryingToDeactivateThemself_shouldReturnBadRequest() throws Exception {
- userSession.logIn("userToDelete").setSystemAdministrator();
+ UserSessionRule userToDelete = userSession.logIn("userToDelete").setSystemAdministrator();
- mockMvc.perform(delete(USER_ENDPOINT + "/userToDelete"))
+ mockMvc.perform(delete(USER_ENDPOINT + "/" + userToDelete.getUuid()))
.andExpectAll(
status().isBadRequest(),
content().json("{\"message\":\"Self-deactivation is not possible\"}"));
userSession.logIn().setSystemAdministrator();
UserInformation userInformation = generateUserSearchResult("1", true, true, false, 1, 2);
- when(userService.updateUser(eq("userLogin"), any())).thenReturn(userInformation);
+ when(userService.updateUser(eq("userUuid"), any())).thenReturn(userInformation);
when(responseGenerator.toRestUser(userInformation)).thenReturn(toRestUser(userInformation));
- MvcResult mvcResult = mockMvc.perform(patch(USER_ENDPOINT + "/userLogin")
+ MvcResult mvcResult = mockMvc.perform(patch(USER_ENDPOINT + "/userUuid")
.contentType(JSON_MERGE_PATCH_CONTENT_TYPE)
.content(payload))
.andExpect(
assertThat(responseUser).isEqualTo(toRestUser(userInformation));
ArgumentCaptor<UpdateUser> updateUserCaptor = ArgumentCaptor.forClass(UpdateUser.class);
- verify(userService).updateUser(eq("userLogin"), updateUserCaptor.capture());
+ verify(userService).updateUser(eq("userUuid"), updateUserCaptor.capture());
return updateUserCaptor.getValue();
}
private static RestUserForAdmins buildExpectedResponseForAdmin(UserInformation userInformation) {
UserDto userDto = userInformation.userDto();
return new RestUserForAdmins(
- userDto.getLogin(),
+ userDto.getUuid(),
userDto.getLogin(),
userDto.getName(),
userDto.getEmail(),
private static RestUserForLoggedInUsers buildExpectedResponseForUser(UserInformation userInformation) {
UserDto userDto = userInformation.userDto();
return new RestUserForLoggedInUsers(
- userDto.getLogin(),
+ userDto.getUuid(),
userDto.getLogin(),
userDto.getName(),
userDto.getEmail(),
private static RestUserForAnonymousUsers buildExpectedResponseForAnonymous(UserInformation userInformation) {
UserDto userDto = userInformation.userDto();
return new RestUserForAnonymousUsers(
- userDto.getLogin(),
+ userDto.getUuid(),
userDto.getLogin(),
userDto.getName()
);
deactivate("someone");
})
.isInstanceOf(NotFoundException.class)
- .hasMessage("User 'someone' not found");
+ .hasMessage("User 'someone' doesn't exist");
}
@Test
String login = request.mandatoryParam(PARAM_LOGIN);
checkRequest(!login.equals(userSession.getLogin()), "Self-deactivation is not possible");
boolean shouldAnonymize = request.mandatoryParamAsBoolean(PARAM_ANONYMIZE);
- UserDto deactivatedUser = userService.deactivate(login, shouldAnonymize);
- writeResponse(response, deactivatedUser.getLogin());
+ try (DbSession dbSession = dbClient.openSession(false)) {
+ UserDto userDto = dbClient.userDao().selectByLogin(dbSession, login);
+ checkFound(userDto, "User '%s' doesn't exist", login);
+ UserDto deactivatedUser = userService.deactivate(userDto.getUuid(), shouldAnonymize);
+ writeResponse(response, deactivatedUser);
+ }
}
- private void writeResponse(Response response, String login) {
+ private void writeResponse(Response response, UserDto userDto) {
try (DbSession dbSession = dbClient.openSession(false)) {
- UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
- // safeguard. It exists as the check has already been done earlier
- // when deactivating user
- checkFound(user, "User '%s' doesn't exist", login);
-
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
json.name("user");
- Set<String> groups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(login)).get(login));
- userWriter.write(json, user, groups, UserJsonWriter.FIELDS);
+ Set<String> groups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(userDto.getLogin())).get(userDto.getLogin()));
+ userWriter.write(json, userDto, groups, UserJsonWriter.FIELDS);
json.endObject();
}
}