From 0baf4d2fa163000db7863e9753e4635a49824827 Mon Sep 17 00:00:00 2001 From: Martin Weise <martin.weise@tuwien.ac.at> Date: Mon, 28 Aug 2023 15:39:23 +0200 Subject: [PATCH] Fixed some tests --- dbrepo-metadata-service/Dockerfile | 2 +- .../api/keycloak/UpdateAttributesDto.java | 19 --- .../api/keycloak/UserAttributesDto.java | 35 ----- .../at/tuwien/api/keycloak/UserCreateDto.java | 11 -- .../java/at/tuwien/api/keycloak/UserDto.java | 11 -- .../java/at/tuwien/entities/user/User.java | 54 ++++++++ .../java/at/tuwien/mapper/DatabaseMapper.java | 16 +-- .../java/at/tuwien/mapper/StoreMapper.java | 3 +- .../java/at/tuwien/mapper/UserMapper.java | 48 ++----- .../tuwien/repository/mdb/UserRepository.java | 20 +++ .../tuwien/repository/mdb/ViewRepository.java | 5 +- .../at/tuwien/endpoints/DatabaseEndpoint.java | 13 +- .../at/tuwien/endpoints/StoreEndpoint.java | 9 +- .../at/tuwien/endpoints/UserEndpoint.java | 46 ++++--- .../src/main/resources/application-local.yml | 2 +- .../java/at/tuwien/config/MariaDbConfig.java | 8 +- .../endpoints/AccessEndpointUnitTest.java | 14 +- .../endpoints/ContainerEndpointUnitTest.java | 1 - .../endpoints/DatabaseEndpointUnitTest.java | 39 ++++-- .../IdentifierEndpointIntegrationTest.java | 2 +- .../endpoints/IdentifierEndpointUnitTest.java | 1 - .../endpoints/ImageEndpointUnitTest.java | 1 - .../MaintenanceEndpointUnitTest.java | 3 +- .../endpoints/OntologyEndpointUnitTest.java | 10 +- .../PersistenceEndpointUnitTest.java | 19 ++- .../endpoints/QueryEndpointUnitTest.java | 1 - .../endpoints/SemanticsEndpointUnitTest.java | 6 +- .../endpoints/StoreEndpointUnitTest.java | 42 +++++- .../TableColumnEndpointUnitTest.java | 1 - .../endpoints/TableDataEndpointUnitTest.java | 1 - .../endpoints/TableEndpointUnitTest.java | 1 - .../endpoints/UserEndpointUnitTest.java | 63 +++++---- .../endpoints/ViewEndpointUnitTest.java | 71 +++++----- .../at/tuwien/mapper/DatabaseMapperTest.java | 5 +- .../ViewRepositoryIntegrationTest.java | 2 +- .../service/AccessServiceIntegrationTest.java | 36 ++--- .../tuwien/service/AccessServiceUnitTest.java | 2 +- ...aCiteIdentifierServiceIntegrationTest.java | 3 +- .../DatabaseServiceIntegrationTest.java | 39 +++--- .../service/DatabaseServiceUnitTest.java | 2 +- .../service/IdentifierServiceUnitTest.java | 4 +- .../MessageQueueServiceIntegrationTest.java | 2 +- .../service/UserServiceIntegrationTest.java | 37 +++--- .../tuwien/service/UserServiceUnitTest.java | 101 +++++++++++++- .../validator/EndpointValidatorUnitTest.java | 4 +- .../src/test/resources/init/users.sql | 8 +- .../at/tuwien/gateway/KeycloakGateway.java | 11 -- .../gateway/impl/KeycloakGatewayImpl.java | 86 ------------ .../at/tuwien/service/DatabaseService.java | 3 +- .../tuwien/service/MessageQueueService.java | 3 +- .../java/at/tuwien/service/UserService.java | 20 ++- .../service/impl/AccessServiceImpl.java | 25 ++-- .../service/impl/MariaDbServiceImpl.java | 9 +- .../service/impl/OntologyServiceImpl.java | 3 +- .../service/impl/RabbitMqServiceImpl.java | 4 +- .../tuwien/service/impl/StoreServiceImpl.java | 21 +-- .../tuwien/service/impl/UserServiceImpl.java | 110 ++++++++-------- .../tuwien/service/impl/ViewServiceImpl.java | 4 +- .../main/java/at/tuwien/test/BaseTest.java | 124 +++++++++++++++++- 59 files changed, 681 insertions(+), 565 deletions(-) delete mode 100644 dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateAttributesDto.java delete mode 100644 dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesDto.java create mode 100644 dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/User.java create mode 100644 dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserRepository.java diff --git a/dbrepo-metadata-service/Dockerfile b/dbrepo-metadata-service/Dockerfile index 6b8c732e4c..776b2b5609 100644 --- a/dbrepo-metadata-service/Dockerfile +++ b/dbrepo-metadata-service/Dockerfile @@ -34,7 +34,7 @@ MAINTAINER Martin Weise <martin.weise@tuwien.ac.at> ENV ADMIN_MAIL="noreply@localhost" ENV BASE_URL="http://localhost" -ENV GRANT_PRIVILEGES="ALL PRIVILEGES" +ENV GRANT_PRIVILEGES="SELECT, CREATE, CREATE VIEW, CREATE ROUTINE, CREATE TEMPORARY TABLES, LOCK TABLES, INDEX, TRIGGER, INSERT, UPDATE, DELETE" ENV BROKER_CONSUMERS=2 ENV BROKER_ENDPOINT="http://broker-service:15672" ENV BROKER_USERNAME=fda diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateAttributesDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateAttributesDto.java deleted file mode 100644 index fdf3ebd607..0000000000 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateAttributesDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package at.tuwien.api.keycloak; - -import jakarta.validation.constraints.NotNull; -import lombok.*; -import lombok.extern.jackson.Jacksonized; - -@Getter -@Setter -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Jacksonized -@ToString -public class UpdateAttributesDto { - - @NotNull - private UserAttributesDto attributes; - -} diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesDto.java deleted file mode 100644 index 4fbc2df2e7..0000000000 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesDto.java +++ /dev/null @@ -1,35 +0,0 @@ -package at.tuwien.api.keycloak; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; -import lombok.*; -import lombok.extern.jackson.Jacksonized; - -import java.util.List; - -@Getter -@Setter -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Jacksonized -@ToString -public class UserAttributesDto { - - @NotNull - @JsonProperty("theme_dark") - @Schema(example = "[\"false\"]") - private List<String> themeDark; - - @Schema(example = "[\"https://orcid.org/0000-0002-1825-0097\"]") - private List<String> orcid; - - @Schema(example = "[\"Brown University\"]") - private List<String> affiliation; - - @JsonProperty("mariadb_password") - @Schema(example = "[\"*CC67043C7BCFF5EEA5566BD9B1F3C74FD9A5CF5D\"]") - private List<String> mariadbPassword; - -} diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserCreateDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserCreateDto.java index ebb83864de..0ebaffff10 100644 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserCreateDto.java +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserCreateDto.java @@ -25,21 +25,10 @@ public class UserCreateDto { @Schema(example = "true") private Boolean enabled; - @JsonProperty("given_name") - @Schema(example = "Josiah") - private String firstname; - - @JsonProperty("family_name") - @Schema(example = "Carberry") - private String lastname; - @NotNull @Schema(example = "jcarberry@brown.edu") private String email; - @NotNull - private UserAttributesDto attributes; - @NotNull private List<CredentialDto> credentials; diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserDto.java index 79ac3f4ebf..a96c6932ab 100644 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserDto.java +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserDto.java @@ -1,13 +1,11 @@ package at.tuwien.api.keycloak; -import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; import lombok.*; import lombok.extern.jackson.Jacksonized; -import java.time.Instant; import java.util.UUID; @Getter @@ -26,12 +24,6 @@ public class UserDto { @Schema(example = "jcarberry", description = "Only contains lowercase characters") private String username; - @NotNull - @JsonProperty("createdTimestamp") - @Schema(example = "1693048334898") - @JsonFormat(shape = JsonFormat.Shape.NUMBER, timezone = "UTC") - private Instant created; - @NotNull @Schema(example = "true") private Boolean enabled; @@ -49,9 +41,6 @@ public class UserDto { @Schema(example = "jcarberry@brown.edu") private String email; - @NotNull - private UserAttributesDto attributes; - @NotNull @JsonProperty("notBefore") @Schema(example = "0") diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/User.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/User.java new file mode 100644 index 0000000000..1f6156acf4 --- /dev/null +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/User.java @@ -0,0 +1,54 @@ +package at.tuwien.entities.user; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.JdbcTypeCode; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.util.UUID; + +@Data +@Entity +@Builder +@AllArgsConstructor +@NoArgsConstructor +@ToString +@EntityListeners(AuditingEntityListener.class) +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@Table(name = "mdb_users") +@NamedQueries({ + @NamedQuery(name = "User.findByUsername", query = "select u from User u where u.username = ?1") +}) +public class User { + + @Id + @EqualsAndHashCode.Include + @JdbcTypeCode(java.sql.Types.VARCHAR) + @Column(name = "ID", nullable = false, columnDefinition = "VARCHAR(36)") + private UUID id; + + @Column(nullable = false) + private String username; + + @Column + private String firstname; + + @Column + private String lastname; + + @Column(nullable = false) + private String email; + + @Column + private String orcid; + + @Column + private String affiliation; + + @Column(name = "theme_dark", nullable = false) + private Boolean themeDark; + + @Column(name = "mariadb_password", nullable = false) + private String mariadbPassword; + +} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/DatabaseMapper.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/DatabaseMapper.java index 2550f1a846..3bf6702da7 100644 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/DatabaseMapper.java +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/DatabaseMapper.java @@ -8,6 +8,7 @@ import at.tuwien.entities.database.AccessType; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.database.LanguageType; +import at.tuwien.entities.user.User; import at.tuwien.exception.QueryMalformedException; import org.apache.commons.lang3.RandomStringUtils; import org.apache.http.auth.BasicUserPrincipal; @@ -83,15 +84,15 @@ public interface DatabaseMapper { }) Database databaseCreateDtoToDatabase(DatabaseCreateDto data); - default PreparedStatement userToRawCreateUserQuery(Connection connection, UserDto data) throws QueryMalformedException { - if (data.getAttributes().getMariadbPassword() == null) { + default PreparedStatement userToRawCreateUserQuery(Connection connection, User data) throws QueryMalformedException { + if (data.getMariadbPassword() == null) { log.error("Failed to map create user query: attribute 'mariadb_password' is empty"); throw new QueryMalformedException("Failed to map create user query: attribute 'mariadb_password' is empty"); } final StringBuilder statement = new StringBuilder("CREATE USER IF NOT EXISTS `") .append(data.getUsername()) .append("`@`%` IDENTIFIED BY PASSWORD '") - .append(data.getAttributes().getMariadbPassword()) + .append(data.getMariadbPassword()) .append("';"); log.trace("statement={}", statement); try { @@ -102,15 +103,15 @@ public interface DatabaseMapper { } } - default PreparedStatement userToRawUpdateUserQuery(Connection connection, UserDto data) throws QueryMalformedException { - if (data.getAttributes().getMariadbPassword() == null) { + default PreparedStatement userToRawUpdateUserQuery(Connection connection, User data) throws QueryMalformedException { + if (data.getMariadbPassword() == null) { log.error("Failed to map create user query: attribute 'mariadb_password' is empty"); throw new QueryMalformedException("Failed to map create user query: attribute 'mariadb_password' is empty"); } final StringBuilder statement = new StringBuilder("SET PASSWORD FOR `") .append(data.getUsername()) .append("`@`%` = '") - .append(data.getAttributes().getMariadbPassword()) + .append(data.getMariadbPassword()) .append("';"); log.trace("statement={}", statement); try { @@ -302,8 +303,7 @@ public interface DatabaseMapper { return access; } - default DatabaseAccess databaseModifyAccessDtoToDatabaseAccess(Database database, UserDto user, - DatabaseModifyAccessDto data) { + default DatabaseAccess databaseModifyAccessDtoToDatabaseAccess(Database database, User user, DatabaseModifyAccessDto data) { final DatabaseAccess access = DatabaseAccess.builder() .hdbid(database.getId()) .huserid(user.getId()) diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/StoreMapper.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/StoreMapper.java index 07ed149a5a..2307371f21 100644 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/StoreMapper.java +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/StoreMapper.java @@ -2,6 +2,7 @@ package at.tuwien.mapper; import at.tuwien.api.database.query.ExecuteStatementDto; import at.tuwien.api.user.UserDto; +import at.tuwien.entities.user.User; import at.tuwien.exception.QueryStoreException; import at.tuwien.exception.TableMalformedException; import at.tuwien.querystore.Query; @@ -21,7 +22,7 @@ public interface StoreMapper { DateTimeFormatter mariaDbFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]") .withZone(ZoneId.of("UTC")); - default CallableStatement queryStoreRawInsertQuery(Connection connection, UserDto user, ExecuteStatementDto data) + default CallableStatement queryStoreRawInsertQuery(Connection connection, User user, ExecuteStatementDto data) throws QueryStoreException { final String statement = "{call _store_query(?, ?, ?, ?)}"; log.trace("statement={}", statement); diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/UserMapper.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/UserMapper.java index 61595eb78b..bef71a2bbf 100644 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/UserMapper.java +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/mapper/UserMapper.java @@ -6,14 +6,13 @@ import at.tuwien.api.keycloak.*; import at.tuwien.api.user.*; import at.tuwien.api.user.UserAttributesDto; import at.tuwien.api.user.UserDto; -import org.apache.commons.codec.digest.DigestUtils; +import at.tuwien.entities.user.User; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -34,11 +33,6 @@ public interface UserMapper { return authority; } - @Mappings({ - @Mapping(target = "attributes", expression = "java(data)") - }) - UpdateAttributesDto userAttributesDtoToUpdateAttributesDto(at.tuwien.api.keycloak.UserAttributesDto data); - default UpdateCredentialsDto passwordToUpdateCredentialsDto(String password) { return UpdateCredentialsDto.builder() .credentials(List.of(CredentialDto.builder() @@ -49,19 +43,6 @@ public interface UserMapper { .build(); } - default at.tuwien.api.keycloak.UserAttributesDto userUpdateDtoToUserAttributesDto(UserUpdateDto data) { - return at.tuwien.api.keycloak.UserAttributesDto.builder() - .orcid(List.of(data.getOrcid())) - .affiliation(List.of(data.getAffiliation())) - .build(); - } - - default at.tuwien.api.keycloak.UserAttributesDto userThemeSetDtoToUserAttributesDto(UserThemeSetDto data) { - return at.tuwien.api.keycloak.UserAttributesDto.builder() - .themeDark(List.of(String.valueOf(data.getThemeDark()))) - .build(); - } - default UserCreateDto signupRequestDtoToUserCreateDto(SignupRequestDto data) { return UserCreateDto.builder() .username(data.getUsername()) @@ -72,39 +53,26 @@ public interface UserMapper { .value(data.getPassword()) .build())) .enabled(true) - .attributes(at.tuwien.api.keycloak.UserAttributesDto.builder() - .themeDark(List.of("false")) - .mariadbPassword(List.of("*" + DigestUtils.sha1Hex(DigestUtils.sha1( - data.getPassword().getBytes(StandardCharsets.UTF_8))).toUpperCase())) - .affiliation(List.of()) - .orcid(List.of()) - .build()) .build(); } /* keep */ UserBriefDto keycloakUserDtoToUserBriefDto(at.tuwien.api.keycloak.UserDto data); - /* keep */ - UserDto keycloakUserDtoToUserDto(at.tuwien.api.keycloak.UserDto data); - - /* keep */ - default UserAttributesDto map(at.tuwien.api.keycloak.UserAttributesDto data) { - return UserAttributesDto.builder() - .themeDark(Boolean.getBoolean(data.getThemeDark().get(0))) - .orcid(data.getOrcid().get(0)) - .affiliation(data.getAffiliation().get(0)) - .build(); - } - /* keep */ @Mappings({ @Mapping(target = "id", expression = "java(data.getId().toString())") }) UserDetailsDto userDtoToUserDetailsDto(UserDto data); + /* keep */ + UserBriefDto userToUserBriefDto(User data); + UserBriefDto userDtoToUserBriefDto(UserDto data); + /* keep */ + UserDto userToUserDto(User data); + default UserDetailsDto tokenIntrospectDtoToUserDetailsDto(TokenIntrospectDto data) { return UserDetailsDto.builder() .id(data.getSub()) @@ -115,4 +83,6 @@ public interface UserMapper { .build(); } + User signupRequestDtoToUser(SignupRequestDto data); + } diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserRepository.java new file mode 100644 index 0000000000..9417d95cc4 --- /dev/null +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserRepository.java @@ -0,0 +1,20 @@ +package at.tuwien.repository.mdb; + +import at.tuwien.entities.user.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface UserRepository extends JpaRepository<User, UUID> { + + Optional<User> findByUsername(String username); + + boolean existsByUsername(String username); + + boolean existsByEmail(String email); + +} + diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/ViewRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/ViewRepository.java index 322602ee2d..46600d244e 100644 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/ViewRepository.java +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/ViewRepository.java @@ -6,17 +6,18 @@ import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; +import java.util.UUID; @Repository public interface ViewRepository extends JpaRepository<View, Long> { List<View> findAllPublicByDatabaseId(Long databaseId); - List<View> findAllPublicOrMineByDatabaseId(Long databaseId, String username); + List<View> findAllPublicOrMineByDatabaseId(Long databaseId, UUID userId); Optional<View> findPublicByDatabaseIdAndId(Long databaseId, Long id); - Optional<View> findPublicOrMineByDatabaseIdAndId(Long databaseId, Long id, String username); + Optional<View> findPublicOrMineByDatabaseIdAndId(Long databaseId, Long id, UUID userId); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/DatabaseEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/DatabaseEndpoint.java index dd2a6692b2..5b31688b8a 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/DatabaseEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/DatabaseEndpoint.java @@ -5,6 +5,7 @@ import at.tuwien.api.error.ApiErrorDto; import at.tuwien.api.user.UserDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.DatabaseMapper; import at.tuwien.repository.mdb.DatabaseAccessRepository; @@ -143,7 +144,7 @@ public class DatabaseEndpoint { BrokerVirtualHostGrantException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint create database, createDto={}, principal={}", createDto, principal); - final UserDto user = userService.findByUsername(principal.getName()); + final User user = userService.findByUsername(principal.getName()); final Database database = databaseService.create(createDto, principal); messageQueueService.createUser(user.getUsername()); messageQueueService.createExchange(database, principal); @@ -181,10 +182,10 @@ public class DatabaseEndpoint { public ResponseEntity<DatabaseDto> visibility(@NotNull @PathVariable Long id, @Valid @RequestBody DatabaseModifyVisibilityDto data, @NotNull Principal principal) throws DatabaseNotFoundException, - UserNotFoundException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { + UserNotFoundException, NotAllowedException { log.debug("endpoint update database, id={}, data={}, principal={}", id, data, principal); final Database database = databaseService.findById(id); - final UserDto user = userService.findByUsername(principal.getName()); + final User user = userService.findByUsername(principal.getName()); if (!database.getOwnedBy().equals(UserUtil.getId(principal))) { log.error("Failed to create database: not owner"); throw new NotAllowedException(("Failed to create database: not owner")); @@ -223,8 +224,8 @@ public class DatabaseEndpoint { UserNotFoundException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint update database, id={}, transferDto={}, principal={}", id, transferDto, principal); final Database database = databaseService.findById(id); - final UserDto user = userService.findByUsername(principal.getName()); - if (!database.getOwnedBy().equals(UserUtil.getId(principal))) { + final User user = userService.findByUsername(principal.getName()); + if (!database.getOwnedBy().equals(user.getId())) { log.error("Failed to create database: not owner"); throw new NotAllowedException(("Failed to create database: not owner")); } @@ -325,7 +326,7 @@ public class DatabaseEndpoint { log.debug("endpoint delete database, id={}, principal={}", id, principal); final Database database = databaseService.findById(id); - final UserDto user = userService.findByUsername(principal.getName()); + final User user = userService.findByUsername(principal.getName()); messageQueueService.deleteExchange(database); databaseService.delete(id, user.getId()); messageQueueService.updatePermissions(user); diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/StoreEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/StoreEndpoint.java index a2792223e5..3f01923447 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/StoreEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/StoreEndpoint.java @@ -5,7 +5,6 @@ import at.tuwien.api.database.query.QueryDto; import at.tuwien.api.database.query.QueryPersistDto; import at.tuwien.api.error.ApiErrorDto; import at.tuwien.api.identifier.IdentifierBriefDto; -import at.tuwien.api.user.UserDto; import at.tuwien.entities.identifier.Identifier; import at.tuwien.exception.*; import at.tuwien.mapper.IdentifierMapper; @@ -46,6 +45,7 @@ import java.util.stream.Collectors; @RequestMapping("/api/database/{databaseId}/query") public class StoreEndpoint { + private final UserMapper userMapper; private final QueryMapper queryMapper; private final UserService userService; private final StoreService storeService; @@ -55,9 +55,10 @@ public class StoreEndpoint { private final IdentifierService identifierService; @Autowired - public StoreEndpoint(QueryMapper queryMapper, UserService userService, StoreService storeService, + public StoreEndpoint(UserMapper userMapper, QueryMapper queryMapper, UserService userService, StoreService storeService, AccessService accessService, IdentifierMapper identifierMapper, EndpointValidator endpointValidator, IdentifierService identifierService) { + this.userMapper = userMapper; this.queryMapper = queryMapper; this.userService = userService; this.storeService = storeService; @@ -184,7 +185,7 @@ public class StoreEndpoint { /* find */ final Query query = storeService.findOne(databaseId, queryId, principal); final QueryDto dto = queryMapper.queryToQueryDto(query); - dto.setCreator(userService.findByUsername(query.getCreatedBy())); + dto.setCreator(userMapper.userToUserDto(userService.findByUsername(query.getCreatedBy()))); final List<Identifier> identifiers = identifierService.findByDatabaseIdAndQueryId(databaseId, queryId); if (!identifiers.isEmpty()) { dto.setIdentifier(identifierMapper.identifierToIdentifierDto(identifiers.get(0))); @@ -251,7 +252,7 @@ public class StoreEndpoint { /* persist */ final Query query = storeService.persist(databaseId, queryId, data); final QueryDto dto = queryMapper.queryToQueryDto(query); - dto.setCreator(userService.findByUsername(query.getCreatedBy())); + dto.setCreator(userMapper.userToUserDto(userService.findByUsername(query.getCreatedBy()))); log.trace("persist query resulted in query {}", dto); return ResponseEntity.status(HttpStatus.ACCEPTED) .body(dto); diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/UserEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/UserEndpoint.java index db2b793cbf..88f29fa457 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/UserEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/UserEndpoint.java @@ -3,7 +3,10 @@ package at.tuwien.endpoints; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.error.ApiErrorDto; import at.tuwien.api.user.*; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; +import at.tuwien.mapper.UserMapper; +import at.tuwien.service.DatabaseService; import at.tuwien.service.UserService; import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; @@ -34,11 +37,16 @@ import java.util.UUID; @RequestMapping("/api/user") public class UserEndpoint { + private final UserMapper userMapper; private final UserService userService; + private final DatabaseService databaseService; + @Autowired - public UserEndpoint(UserService userService) { + public UserEndpoint(UserMapper userMapper, UserService userService, DatabaseService databaseService) { + this.userMapper = userMapper; this.userService = userService; + this.databaseService = databaseService; } @GetMapping @@ -52,9 +60,12 @@ public class UserEndpoint { mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = UserBriefDto.class)))}), }) - public ResponseEntity<List<UserBriefDto>> findAll() throws KeycloakRemoteException, AccessDeniedException { + public ResponseEntity<List<UserBriefDto>> findAll() { log.debug("endpoint find all users"); - final List<UserBriefDto> users = userService.findAll(); + final List<UserBriefDto> users = userService.findAll() + .stream() + .map(userMapper::userToUserBriefDto) + .toList(); log.trace("find all users resulted in users {}", users); return ResponseEntity.ok(users); } @@ -86,7 +97,7 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserDto> create(@NotNull @Valid @RequestBody SignupRequestDto data) + public ResponseEntity<UserBriefDto> create(@NotNull @Valid @RequestBody SignupRequestDto data) throws RealmNotFoundException, UserAlreadyExistsException, UserEmailAlreadyExistsException, UserNotFoundException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint create a user, data={}", data); @@ -94,7 +105,8 @@ public class UserEndpoint { userService.validateUsernameNotExists(data.getUsername()); userService.validateEmailNotExists(data.getEmail()); /* create */ - final UserDto dto = userService.create(data); + final User user = userService.create(data); + final UserBriefDto dto = userMapper.userToUserBriefDto(user); log.trace("create user resulted in dto {}", dto); return ResponseEntity.status(HttpStatus.CREATED) .body(dto); @@ -127,8 +139,9 @@ public class UserEndpoint { KeycloakRemoteException, AccessDeniedException { log.debug("endpoint find a user, id={}, principal={}", id, principal); /* check */ - final UserDto dto = userService.find(id); - if (id.equals(UserUtil.getId(principal))) { + final User user = userService.find(id); + final UserDto dto = userMapper.userToUserDto(user); + if (user.getUsername().equals(principal.getName())) { log.trace("find user resulted in dto {}", dto); return ResponseEntity.ok() .body(dto); @@ -166,7 +179,8 @@ public class UserEndpoint { public ResponseEntity<UserDto> modify(@NotNull @PathVariable("id") UUID id, @NotNull @Valid @RequestBody UserUpdateDto data, @NotNull Principal principal) throws UserNotFoundException, - ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException { + ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException, + QueryMalformedException, DatabaseMalformedException { log.debug("endpoint modify a user, id={}, data={}, principal={}", id, data, principal); /* check */ if (!id.equals(UserUtil.getId(principal))) { @@ -174,7 +188,9 @@ public class UserEndpoint { throw new ForeignUserException("Failed to modify user: attempting to modify other user"); } /* modify */ - final UserDto dto = userService.modify(id, data); + final User user = userService.modify(id, data); + databaseService.updatePassword(user); + final UserDto dto = userMapper.userToUserDto(user); log.trace("modify user resulted in dto {}", dto); return ResponseEntity.status(HttpStatus.ACCEPTED) .body(dto); @@ -204,9 +220,8 @@ public class UserEndpoint { }) public ResponseEntity<UserDto> theme(@NotNull @PathVariable("id") UUID id, @NotNull @Valid @RequestBody UserThemeSetDto data, - @NotNull Principal principal) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, - AccessDeniedException { + @NotNull Principal principal) throws UserNotFoundException, + ForeignUserException { log.debug("endpoint modify a user theme, id={}, data={}, principal={}", id, data, principal); /* check */ if (!id.equals(UserUtil.getId(principal))) { @@ -214,7 +229,8 @@ public class UserEndpoint { throw new ForeignUserException("Failed to modify user: attempting to modify other user"); } /* modify theme */ - final UserDto dto = userService.toggleTheme(id, data); + final User user = userService.toggleTheme(id, data); + final UserDto dto = userMapper.userToUserDto(user); log.trace("modify user theme resulted in dto {}", dto); return ResponseEntity.accepted() .body(dto); @@ -243,8 +259,8 @@ public class UserEndpoint { schema = @Schema(implementation = ApiErrorDto.class))}), }) public ResponseEntity<?> password(@NotNull @PathVariable("id") UUID id, - @NotNull @Valid @RequestBody UserPasswordDto data, - @NotNull Principal principal) + @NotNull @Valid @RequestBody UserPasswordDto data, + @NotNull Principal principal) throws UserNotFoundException, ForeignUserException, KeycloakRemoteException, AccessDeniedException, QueryMalformedException, DatabaseMalformedException { log.debug("endpoint modify a user password, id={}, data={}, principal={}", id, data, principal); diff --git a/dbrepo-metadata-service/rest-service/src/main/resources/application-local.yml b/dbrepo-metadata-service/rest-service/src/main/resources/application-local.yml index 0d3c040d25..9727e95610 100644 --- a/dbrepo-metadata-service/rest-service/src/main/resources/application-local.yml +++ b/dbrepo-metadata-service/rest-service/src/main/resources/application-local.yml @@ -47,7 +47,7 @@ logging: at.tuwien.: trace org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver: debug fda: - privileges: ALL PRIVILEGES + privileges: SELECT, CREATE, CREATE VIEW, CREATE ROUTINE, CREATE TEMPORARY TABLES, LOCK TABLES, INDEX, TRIGGER, INSERT, UPDATE, DELETE pid: base: https://example.com/pid/ broker: diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/config/MariaDbConfig.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/config/MariaDbConfig.java index 9277a146f9..36b2dfa62b 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/config/MariaDbConfig.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/config/MariaDbConfig.java @@ -7,6 +7,7 @@ import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.Table; import at.tuwien.exception.QueryMalformedException; import at.tuwien.mapper.DatabaseMapper; +import at.tuwien.mapper.DatabaseMapperImpl; import at.tuwien.querystore.Query; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -68,6 +69,7 @@ public class MariaDbConfig { statement.executeUpdate(); statement.close(); } + log.debug("created database {}", database); } public static void createInitDatabase(Container container, Database database) throws SQLException { @@ -78,6 +80,7 @@ public class MariaDbConfig { populator.setSeparator(";\n"); populator.populate(connection); } + log.debug("created init database {}", database.getInternalName()); } public static void dropAllDatabases(Container container) { @@ -103,6 +106,7 @@ public class MariaDbConfig { } catch (SQLException e) { log.error("could not drop all databases", e); } + log.debug("dropped all databases"); } public static void dropDatabase(Container container, String database) @@ -116,12 +120,14 @@ public class MariaDbConfig { statement.executeUpdate(); statement.close(); } + log.debug("dropped database {}", database); } - public void mockGrantUserPermissions(Container container, Database database, String username) throws SQLException, + public static void grantUserPermissions(Container container, Database database, String username) throws SQLException, QueryMalformedException { final String jdbc = "jdbc:mariadb://" + container.getHost() + ":" + container.getPort() + "/" + database.getInternalName(); log.trace("connect to database {}", jdbc); + final DatabaseMapper databaseMapper = new DatabaseMapperImpl(); try (Connection connection = DriverManager.getConnection(jdbc, container.getPrivilegedUsername(), container.getPrivilegedPassword())) { final PreparedStatement statement1 = databaseMapper.rawGrantUserAccessQuery(connection, username, AccessTypeDto.WRITE_ALL); statement1.executeUpdate(); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/AccessEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/AccessEndpointUnitTest.java index 33020d8f90..5dbc7b07d3 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/AccessEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/AccessEndpointUnitTest.java @@ -57,7 +57,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void create_anonymous_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_create(DATABASE_1_ID, DATABASE_1, null, USER_2_ID, null); }); } @@ -67,7 +67,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void create_noRoleNoAccess_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_create(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, USER_4_PRINCIPAL); }); } @@ -91,7 +91,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void find_anonymous_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_find(DATABASE_1_ID, DATABASE_1, null, null, null); }); } @@ -119,7 +119,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void update_anonymous_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, null); }); } @@ -139,7 +139,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void update_noRoleNoAccess_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, USER_4_PRINCIPAL); }); } @@ -163,7 +163,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void revoke_anonymous_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_ID, USER_1_PRINCIPAL); }); } @@ -173,7 +173,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { public void revoke_noRoleNoAccess_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_ID, USER_4_PRINCIPAL); }); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ContainerEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ContainerEndpointUnitTest.java index 7cc21d255f..4c6d13f496 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ContainerEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ContainerEndpointUnitTest.java @@ -18,7 +18,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/DatabaseEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/DatabaseEndpointUnitTest.java index f77e048247..fbff73859a 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/DatabaseEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/DatabaseEndpointUnitTest.java @@ -8,7 +8,9 @@ import at.tuwien.api.user.UserDto; import at.tuwien.entities.container.Container; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; +import at.tuwien.gateway.KeycloakGateway; import at.tuwien.repository.mdb.DatabaseAccessRepository; import at.tuwien.repository.mdb.IdentifierRepository; import at.tuwien.repository.sdb.DatabaseIdxRepository; @@ -50,6 +52,9 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { @MockBean private AccessService accessService; + @MockBean + private KeycloakGateway keycloakGateway; + @MockBean private ContainerService containerService; @@ -81,7 +86,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { create_generic(DATABASE_1_ID, null, request, null, null); }); } @@ -96,8 +101,8 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - create_generic(DATABASE_3_ID, null, request, USER_4_DTO, USER_4_PRINCIPAL); + assertThrows(AccessDeniedException.class, () -> { + create_generic(DATABASE_3_ID, null, request, USER_4, USER_4_PRINCIPAL); }); } @@ -127,15 +132,17 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .createExchange(DATABASE_1, USER_1_PRINCIPAL); doNothing() .when(messageQueueService) - .updatePermissions(USER_1_DTO); + .updatePermissions(USER_1); doNothing() .when(queryStoreService) .create(DATABASE_1_ID, USER_1_PRINCIPAL); when(databaseAccessRepository.save(any(DatabaseAccess.class))) .thenReturn(DATABASE_1_USER_1_WRITE_ALL_ACCESS); + when(keycloakGateway.findByUsername(USER_1_USERNAME)) + .thenReturn(USER_1_KEYCLOAK_DTO); /* test */ - create_generic(DATABASE_1_ID, null, request, USER_1_DTO, USER_1_PRINCIPAL); + create_generic(DATABASE_1_ID, null, request, USER_1, USER_1_PRINCIPAL); } @Test @@ -179,7 +186,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, null); }); } @@ -192,6 +199,10 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .isPublic(true) .build(); + /* mock */ + when(keycloakGateway.findByUsername(USER_1_USERNAME)) + .thenReturn(USER_1_KEYCLOAK_DTO); + /* test */ visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, USER_1_PRINCIPAL); } @@ -204,7 +215,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, USER_4_PRINCIPAL); }); } @@ -217,7 +228,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(NotAllowedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, USER_2_PRINCIPAL); }); } @@ -230,7 +241,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { databaseEndpoint.transfer(DATABASE_3_ID, request, USER_4_PRINCIPAL); }); } @@ -247,7 +258,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .thenReturn(DATABASE_1); /* test */ - assertThrows(NotAllowedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { databaseEndpoint.transfer(DATABASE_1_ID, request, USER_2_PRINCIPAL); }); } @@ -263,6 +274,8 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { /* mock */ when(databaseService.findById(DATABASE_1_ID)) .thenReturn(DATABASE_1); + when(keycloakGateway.findByUsername(USER_1_USERNAME)) + .thenReturn(USER_1_KEYCLOAK_DTO); /* test */ databaseEndpoint.transfer(DATABASE_1_ID, request, USER_1_PRINCIPAL); @@ -349,7 +362,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { public void delete_anonymous_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { delete_generic(DATABASE_1_ID, DATABASE_1, null); }); } @@ -359,7 +372,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { public void delete_noRole_fails() { /* test */ - assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { delete_generic(DATABASE_1_ID, DATABASE_1, USER_1_PRINCIPAL); }); } @@ -395,7 +408,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { assertEquals(databases.size(), body.size()); } - public void create_generic(Long databaseId, Database database, DatabaseCreateDto data, UserDto user, + public void create_generic(Long databaseId, Database database, DatabaseCreateDto data, User user, Principal principal) throws UserNotFoundException, DatabaseNameExistsException, NotAllowedException, ContainerConnectionException, DatabaseMalformedException, QueryStoreException, DatabaseConnectionException, QueryMalformedException, DatabaseNotFoundException, ImageNotSupportedException, diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointIntegrationTest.java index 91ff1841a9..880daf5d18 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointIntegrationTest.java @@ -7,6 +7,7 @@ import at.tuwien.api.identifier.IdentifierDescriptionDto; import at.tuwien.api.identifier.IdentifierDto; import at.tuwien.api.identifier.IdentifierTitleDto; import at.tuwien.api.identifier.IdentifierTypeDto; +import at.tuwien.exception.AccessDeniedException; import at.tuwien.exception.NotAllowedException; import at.tuwien.repository.mdb.*; import lombok.extern.log4j.Log4j2; @@ -17,7 +18,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.annotation.DirtiesContext; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointUnitTest.java index a87a56def3..8a50a2bbca 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/IdentifierEndpointUnitTest.java @@ -26,7 +26,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointUnitTest.java index 4ac0ea8753..aba6c1953e 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointUnitTest.java @@ -18,7 +18,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MaintenanceEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MaintenanceEndpointUnitTest.java index 6c4ee9444d..4531d4a48c 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MaintenanceEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MaintenanceEndpointUnitTest.java @@ -8,8 +8,8 @@ import at.tuwien.api.maintenance.BannerMessageCreateDto; import at.tuwien.api.maintenance.BannerMessageDto; import at.tuwien.api.maintenance.BannerMessageUpdateDto; import at.tuwien.entities.maintenance.BannerMessage; +import at.tuwien.exception.AccessDeniedException; import at.tuwien.exception.BannerMessageNotFoundException; -import at.tuwien.repository.sdb.UserIdxRepository; import at.tuwien.service.BannerMessageService; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -21,7 +21,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/OntologyEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/OntologyEndpointUnitTest.java index 837a159676..e9720ec7dd 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/OntologyEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/OntologyEndpointUnitTest.java @@ -1,12 +1,11 @@ - package at.tuwien.endpoints; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.semantics.*; -import at.tuwien.api.user.UserDto; import at.tuwien.entities.semantics.Ontology; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.service.EntityService; import at.tuwien.service.OntologyService; @@ -22,7 +21,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -115,7 +113,7 @@ public class OntologyEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - create_generic(ONTOLOGY_1_CREATE_DTO, USER_4_PRINCIPAL, USER_4_USERNAME, USER_4_DTO, ONTOLOGY_1); + create_generic(ONTOLOGY_1_CREATE_DTO, USER_4_PRINCIPAL, USER_4_USERNAME, USER_4, ONTOLOGY_1); }); } @@ -125,7 +123,7 @@ public class OntologyEndpointUnitTest extends BaseUnitTest { at.tuwien.exception.AccessDeniedException { /* test */ - create_generic(ONTOLOGY_1_CREATE_DTO, USER_3_PRINCIPAL, USER_3_USERNAME, USER_3_DTO, ONTOLOGY_1); + create_generic(ONTOLOGY_1_CREATE_DTO, USER_3_PRINCIPAL, USER_3_USERNAME, USER_3, ONTOLOGY_1); } @Test @@ -313,7 +311,7 @@ public class OntologyEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - public void create_generic(OntologyCreateDto createDto, Principal principal, String username, UserDto user, + public void create_generic(OntologyCreateDto createDto, Principal principal, String username, User user, Ontology ontology) throws UserNotFoundException, KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/PersistenceEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/PersistenceEndpointUnitTest.java index 397419a410..5ec031a117 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/PersistenceEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/PersistenceEndpointUnitTest.java @@ -7,8 +7,8 @@ import at.tuwien.api.identifier.BibliographyTypeDto; import at.tuwien.api.identifier.CreatorDto; import at.tuwien.api.identifier.IdentifierDto; import at.tuwien.api.identifier.IdentifierSaveDto; -import at.tuwien.api.user.UserDto; import at.tuwien.entities.identifier.Identifier; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.service.AccessService; import at.tuwien.service.IdentifierService; @@ -25,7 +25,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -567,7 +566,7 @@ public class PersistenceEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_4_USERNAME, USER_4_DTO, USER_4_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_4_USERNAME, USER_4, USER_4_PRINCIPAL); }); } @@ -575,11 +574,10 @@ public class PersistenceEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_3_USERNAME, authorities = {"modify-identifier-metadata"}) public void update_hasRoleNoAccess_succeeds() throws UserNotFoundException, NotAllowedException, IdentifierNotFoundException, IdentifierRequestException, QueryNotFoundException, DatabaseNotFoundException, - RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException, - KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { /* test */ - generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3_DTO, USER_3_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3, USER_3_PRINCIPAL); } @Test @@ -587,14 +585,14 @@ public class PersistenceEndpointUnitTest extends BaseUnitTest { public void update_hasRoleHasAccess_succeeds() throws IdentifierNotFoundException, IdentifierRequestException, UserNotFoundException, at.tuwien.exception.AccessDeniedException, NotAllowedException, QueryNotFoundException, DatabaseNotFoundException, RemoteUnavailableException, QueryStoreException, - DatabaseConnectionException, ImageNotSupportedException, KeycloakRemoteException { + DatabaseConnectionException, ImageNotSupportedException { /* mock */ when(accessService.find(IDENTIFIER_3_DATABASE_ID, USER_3_ID)) .thenReturn(DATABASE_3_USER_3_READ_ACCESS); /* test */ - generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3_DTO, USER_3_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3, USER_3_PRINCIPAL); } @Test @@ -633,11 +631,10 @@ public class PersistenceEndpointUnitTest extends BaseUnitTest { return IOUtils.toString(inputStream, StandardCharsets.UTF_8); } - protected void generic_update(Long id, Identifier identifier, IdentifierSaveDto data, String username, UserDto user, + protected void generic_update(Long id, Identifier identifier, IdentifierSaveDto data, String username, User user, Principal principal) throws IdentifierNotFoundException, IdentifierRequestException, UserNotFoundException, NotAllowedException, QueryNotFoundException, DatabaseNotFoundException, - RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException, - KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { /* mock */ if (identifier != null) { diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/QueryEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/QueryEndpointUnitTest.java index 818594023d..ab3639a7e5 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/QueryEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/QueryEndpointUnitTest.java @@ -27,7 +27,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/SemanticsEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/SemanticsEndpointUnitTest.java index 95e2974bb3..cadaac12da 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/SemanticsEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/SemanticsEndpointUnitTest.java @@ -12,10 +12,7 @@ import at.tuwien.api.semantics.EntityDto; import at.tuwien.api.semantics.TableColumnEntityDto; import at.tuwien.entities.database.table.columns.TableColumnConcept; import at.tuwien.entities.database.table.columns.TableColumnUnit; -import at.tuwien.exception.DatabaseNotFoundException; -import at.tuwien.exception.QueryMalformedException; -import at.tuwien.exception.TableColumnNotFoundException; -import at.tuwien.exception.TableNotFoundException; +import at.tuwien.exception.*; import at.tuwien.service.EntityService; import at.tuwien.service.SemanticService; import lombok.extern.log4j.Log4j2; @@ -29,7 +26,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/StoreEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/StoreEndpointUnitTest.java index 10943ca258..2be43a9af8 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/StoreEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/StoreEndpointUnitTest.java @@ -10,10 +10,13 @@ import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.exception.*; import at.tuwien.querystore.Query; +import at.tuwien.repository.mdb.UserRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.impl.StoreServiceImpl; +import jakarta.persistence.Access; import lombok.extern.log4j.Log4j2; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -40,6 +43,9 @@ import static org.mockito.Mockito.*; @MockOpensearch public class StoreEndpointUnitTest extends BaseUnitTest { + @MockBean + private UserRepository userRepository; + @Autowired private StoreEndpoint storeEndpoint; @@ -94,12 +100,14 @@ public class StoreEndpointUnitTest extends BaseUnitTest { public void findAll_privateNoAccess_fails() throws AccessDeniedException { /* mock */ - doThrow(NotAllowedException.class) + doThrow(AccessDeniedException.class) .when(accessService) .find(DATABASE_1_ID, USER_2_ID); + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); /* test */ - assertThrows(NotAllowedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { findAll_generic(DATABASE_1_ID, DATABASE_1, USER_2_PRINCIPAL); }); } @@ -111,7 +119,7 @@ public class StoreEndpointUnitTest extends BaseUnitTest { ImageNotSupportedException, ContainerNotFoundException, AccessDeniedException { /* mock */ - doThrow(NotAllowedException.class) + doThrow(AccessDeniedException.class) .when(accessService) .find(DATABASE_3_ID, USER_2_ID); @@ -139,6 +147,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { DatabaseNotFoundException, ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = find_generic(DATABASE_3_ID, DATABASE_3, QUERY_4_ID, QUERY_4, null); assertEquals(QUERY_4_ID, response.getId()); @@ -161,6 +173,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_PRINCIPAL); assertEquals(QUERY_1_ID, response.getId()); @@ -173,6 +189,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_PRINCIPAL); assertEquals(QUERY_1_ID, response.getId()); @@ -205,6 +225,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_ID, USER_1_PRINCIPAL, DATABASE_1_USER_1_READ_ACCESS); assertEquals(QUERY_1_ID, response.getId()); @@ -217,6 +241,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_ID, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_OWN_ACCESS); assertEquals(QUERY_1_ID, response.getId()); @@ -229,6 +257,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_ID, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_ALL_ACCESS); assertEquals(QUERY_1_ID, response.getId()); @@ -241,6 +273,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { + /* mock */ + when(userRepository.findByUsername(USER_1_USERNAME)) + .thenReturn(Optional.of(USER_1)); + /* test */ persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_1_USER_2_WRITE_ALL_ACCESS); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableColumnEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableColumnEndpointUnitTest.java index 504fb5717c..45b553d59f 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableColumnEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableColumnEndpointUnitTest.java @@ -27,7 +27,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableDataEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableDataEndpointUnitTest.java index 00fef071eb..28d17f8568 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableDataEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableDataEndpointUnitTest.java @@ -26,7 +26,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointUnitTest.java index f45d9a9670..3fb00dd487 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointUnitTest.java @@ -24,7 +24,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/UserEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/UserEndpointUnitTest.java index be2861cfd0..edd7402e80 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/UserEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/UserEndpointUnitTest.java @@ -5,6 +5,7 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.user.*; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.service.UserService; import lombok.extern.log4j.Log4j2; @@ -17,7 +18,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -45,7 +45,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser - public void findAll_anonymous_succeeds() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + public void findAll_anonymous_succeeds() { /* test */ findAll_generic(); @@ -53,7 +53,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME) - public void findAll_noRole_succeeds() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + public void findAll_noRole_succeeds() { /* test */ findAll_generic(); @@ -95,7 +95,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - find_generic(USER_1_ID, USER_1_DTO, null); + find_generic(USER_1_ID, USER_1, null); }); } @@ -105,7 +105,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { at.tuwien.exception.AccessDeniedException { /* test */ - find_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL); + find_generic(USER_1_ID, USER_1, USER_1_PRINCIPAL); } @Test @@ -114,7 +114,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - find_generic(USER_2_ID, USER_2_DTO, USER_1_PRINCIPAL); + find_generic(USER_2_ID, USER_2, USER_1_PRINCIPAL); }); } @@ -124,7 +124,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - find_generic(USER_2_ID, USER_2_DTO, USER_3_PRINCIPAL); + find_generic(USER_2_ID, USER_2, USER_3_PRINCIPAL); }); } @@ -140,7 +140,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - modify_generic(USER_1_ID, USER_1_DTO, null, request); + modify_generic(USER_1_ID, USER_1, null, request); }); } @@ -156,7 +156,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - modify_generic(USER_1_ID, USER_1_DTO, USER_4_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1, USER_4_PRINCIPAL, request); }); } @@ -172,14 +172,15 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - modify_generic(USER_1_ID, USER_1_DTO, USER_2_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1, USER_2_PRINCIPAL, request); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-user-information"}) public void modify_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, - KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException, QueryMalformedException, + DatabaseMalformedException { final UserUpdateDto request = UserUpdateDto.builder() .firstname(USER_1_FIRSTNAME) .lastname(USER_1_LASTNAME) @@ -188,7 +189,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - modify_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1, USER_1_PRINCIPAL, request); } @Test @@ -200,7 +201,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - theme_generic(USER_1_ID, USER_1_DTO, null, request); + theme_generic(USER_1_ID, USER_1, null, request); }); } @@ -213,7 +214,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - theme_generic(USER_4_ID, USER_4_DTO, USER_4_PRINCIPAL, request); + theme_generic(USER_4_ID, USER_4, USER_4_PRINCIPAL, request); }); } @@ -226,20 +227,19 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - theme_generic(USER_1_ID, USER_1_DTO, USER_2_PRINCIPAL, request); + theme_generic(USER_1_ID, USER_1, USER_2_PRINCIPAL, request); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-user-theme"}) - public void theme_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, - KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + public void theme_succeeds() throws UserNotFoundException, ForeignUserException { final UserThemeSetDto request = UserThemeSetDto.builder() .themeDark(USER_1_THEME_DARK) .build(); /* test */ - theme_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); + theme_generic(USER_1_ID, USER_1, USER_1_PRINCIPAL, request); } @Test @@ -251,7 +251,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - password_generic(USER_1_ID, USER_1_DTO, null, request); + password_generic(USER_1_ID, USER_1, null, request); }); } @@ -264,7 +264,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - password_generic(USER_1_ID, USER_1_DTO, USER_4_PRINCIPAL, request); + password_generic(USER_1_ID, USER_1, USER_4_PRINCIPAL, request); }); } @@ -277,18 +277,18 @@ public class UserEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - password_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); + password_generic(USER_1_ID, USER_1, USER_1_PRINCIPAL, request); } /* ################################################################################################### */ /* ## GENERIC TEST CASES ## */ /* ################################################################################################### */ - protected void findAll_generic() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { + protected void findAll_generic() { /* mock */ when(userService.findAll()) - .thenReturn(List.of(USER_1_BRIEF_DTO, USER_2_BRIEF_DTO)); + .thenReturn(List.of(USER_1, USER_2)); /* test */ final ResponseEntity<List<UserBriefDto>> response = userEndpoint.findAll(); @@ -303,13 +303,13 @@ public class UserEndpointUnitTest extends BaseUnitTest { at.tuwien.exception.AccessDeniedException { /* test */ - final ResponseEntity<UserDto> response = userEndpoint.create(data); + final ResponseEntity<UserBriefDto> response = userEndpoint.create(data); assertEquals(HttpStatus.CREATED, response.getStatusCode()); - final UserDto body = response.getBody(); + final UserBriefDto body = response.getBody(); assertNotNull(body); } - protected void find_generic(UUID id, UserDto user, Principal principal) throws UserNotFoundException, + protected void find_generic(UUID id, User user, Principal principal) throws UserNotFoundException, NotAllowedException, KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* mock */ @@ -329,9 +329,9 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void modify_generic(UUID id, UserDto user, Principal principal, UserUpdateDto data) + protected void modify_generic(UUID id, User user, Principal principal, UserUpdateDto data) throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, - at.tuwien.exception.AccessDeniedException { + at.tuwien.exception.AccessDeniedException, QueryMalformedException, DatabaseMalformedException { /* mock */ if (user != null) { @@ -352,9 +352,8 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void theme_generic(UUID id, UserDto user, Principal principal, UserThemeSetDto data) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, - at.tuwien.exception.AccessDeniedException { + protected void theme_generic(UUID id, User user, Principal principal, UserThemeSetDto data) + throws UserNotFoundException, ForeignUserException { /* mock */ if (user != null) { @@ -375,7 +374,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void password_generic(UUID id, UserDto user, Principal principal, UserPasswordDto data) + protected void password_generic(UUID id, User user, Principal principal, UserPasswordDto data) throws UserNotFoundException, ForeignUserException, KeycloakRemoteException, at.tuwien.exception.AccessDeniedException, QueryMalformedException, DatabaseMalformedException { diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ViewEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ViewEndpointUnitTest.java index 8e936cbc7d..9f1d45eed8 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ViewEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ViewEndpointUnitTest.java @@ -22,7 +22,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -59,7 +58,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser - public void findAll_publicAnonymous_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_publicAnonymous_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_3_ID, DATABASE_3, null, null, null); @@ -67,7 +66,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"list-views"}) - public void findAll_publicHasRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_publicHasRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_3_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, null); @@ -76,7 +75,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"list-views"}) public void findAll_publicHasRoleHasAccess_succeeds() throws UserNotFoundException, DatabaseNotFoundException, - at.tuwien.exception.AccessDeniedException { + AccessDeniedException { /* test */ findAll_generic(DATABASE_3_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_3_USER_2_READ_ACCESS); @@ -85,7 +84,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) public void findAll_publicNoRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, - at.tuwien.exception.AccessDeniedException { + AccessDeniedException { /* test */ findAll_generic(DATABASE_3_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, null); @@ -134,7 +133,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser public void find_publicAnonymous_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, null, null, null); @@ -143,7 +142,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"find-database-view"}) public void find_publicHasRole_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -152,7 +151,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) public void find_publicNoRole_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -161,7 +160,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) public void find_publicHasRoleHasAccess_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -201,7 +200,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_3_USERNAME, authorities = {"delete-database-view"}) public void delete_publicOwner_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, ViewMalformedException, - QueryMalformedException, at.tuwien.exception.AccessDeniedException { + QueryMalformedException, AccessDeniedException { /* test */ delete_generic(DATABASE_3_ID, VIEW_5_ID, DATABASE_3, USER_3_ID, USER_3_PRINCIPAL, DATABASE_3_USER_1_WRITE_ALL_ACCESS); @@ -212,7 +211,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_publicAnonymous_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, null, null, null); @@ -223,7 +222,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_publicNoRole_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -234,7 +233,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_publicHasRole_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -245,7 +244,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_publicHasRoleHasAccess_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_3_ID, VIEW_1_ID, DATABASE_3, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -257,7 +256,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser - public void findAll_privateAnonymous_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_privateAnonymous_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_1_ID, DATABASE_1, null, null, null); @@ -265,7 +264,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"list-views"}) - public void findAll_privateHasRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_privateHasRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, null); @@ -273,7 +272,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"list-views"}) - public void findAll_privateHasRoleHasAccess_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_privateHasRoleHasAccess_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_1_USER_2_READ_ACCESS); @@ -281,7 +280,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) - public void findAll_privateNoRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, at.tuwien.exception.AccessDeniedException { + public void findAll_privateNoRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, AccessDeniedException { /* test */ findAll_generic(DATABASE_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, null); @@ -330,7 +329,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser public void find_privateAnonymous_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, null, null, null); @@ -339,7 +338,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"find-database-view"}) public void find_privateHasRole_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -348,7 +347,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) public void find_privateNoRole_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -357,7 +356,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_2_USERNAME) public void find_privateHasRoleHasAccess_succeeds() throws UserNotFoundException, NotAllowedException, - DatabaseNotFoundException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + DatabaseNotFoundException, ViewNotFoundException, AccessDeniedException { /* test */ find_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -397,7 +396,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = {"delete-database-view"}) public void delete_privateOwner_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, ViewMalformedException, - QueryMalformedException, at.tuwien.exception.AccessDeniedException { + QueryMalformedException, AccessDeniedException { /* test */ delete_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_1_ID, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_ALL_ACCESS); @@ -418,7 +417,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_privateNoRole_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -429,7 +428,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_privateHasRole_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -440,7 +439,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { public void data_privateHasRoleHasAccess_succeeds() throws UserNotFoundException, NotAllowedException, DatabaseNotFoundException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, - ContainerNotFoundException, PaginationException, ViewMalformedException, at.tuwien.exception.AccessDeniedException { + ContainerNotFoundException, PaginationException, ViewMalformedException, AccessDeniedException { /* test */ data_generic(DATABASE_1_ID, VIEW_1_ID, DATABASE_1, USER_2_ID, USER_2_PRINCIPAL, DATABASE_2_USER_1_READ_ACCESS); @@ -452,7 +451,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { protected void findAll_generic(Long databaseId, Database database, UUID userId, Principal principal, DatabaseAccess access) throws UserNotFoundException, DatabaseNotFoundException, - at.tuwien.exception.AccessDeniedException { + AccessDeniedException { /* mock */ when(databaseService.find(databaseId)) @@ -466,7 +465,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { } else { log.trace("mock no access of database with id {} and user id {}", databaseId, userId); when(accessService.find(databaseId, userId)) - .thenThrow(NotAllowedException.class); + .thenThrow(AccessDeniedException.class); when(viewService.findAll(databaseId, principal)) .thenReturn(List.of(VIEW_1)); } @@ -485,7 +484,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { protected void create_generic(Long databaseId, Database database, UUID userId, Principal principal, DatabaseAccess access) throws DatabaseNotFoundException, UserNotFoundException, DatabaseConnectionException, ViewMalformedException, QueryMalformedException, NotAllowedException, - at.tuwien.exception.AccessDeniedException { + AccessDeniedException { final ViewCreateDto request = ViewCreateDto.builder() .name(VIEW_1_NAME) .query(VIEW_1_QUERY) @@ -502,7 +501,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { } else { log.trace("mock no access of database with id {} and user id {}", databaseId, userId); when(accessService.find(databaseId, userId)) - .thenThrow(NotAllowedException.class); + .thenThrow(AccessDeniedException.class); } when(viewService.create(databaseId, request, principal)) .thenReturn(VIEW_1); @@ -517,7 +516,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { protected void find_generic(Long databaseId, Long viewId, Database database, UUID userId, Principal principal, DatabaseAccess access) throws DatabaseNotFoundException, - UserNotFoundException, NotAllowedException, ViewNotFoundException, at.tuwien.exception.AccessDeniedException { + UserNotFoundException, NotAllowedException, ViewNotFoundException, AccessDeniedException { /* mock */ when(databaseService.find(databaseId)) @@ -529,7 +528,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { } else { log.trace("mock no access of database with id {} and user id {}", databaseId, userId); when(accessService.find(databaseId, userId)) - .thenThrow(NotAllowedException.class); + .thenThrow(AccessDeniedException.class); } when(viewService.findById(databaseId, viewId, principal)) .thenReturn(VIEW_1); @@ -545,7 +544,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { protected void delete_generic(Long databaseId, Long viewId, Database database, UUID userId, Principal principal, DatabaseAccess access) throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, ViewNotFoundException, DatabaseConnectionException, - ViewMalformedException, QueryMalformedException, at.tuwien.exception.AccessDeniedException { + ViewMalformedException, QueryMalformedException, AccessDeniedException { /* mock */ when(databaseService.find(databaseId)) @@ -557,7 +556,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { } else { log.trace("mock no access of database with id {} and user id {}", databaseId, userId); when(accessService.find(databaseId, userId)) - .thenThrow(NotAllowedException.class); + .thenThrow(AccessDeniedException.class); } doNothing() .when(viewService) @@ -573,7 +572,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { UserNotFoundException, NotAllowedException, ViewNotFoundException, DatabaseConnectionException, QueryMalformedException, QueryStoreException, TableMalformedException, ColumnParseException, ImageNotSupportedException, ContainerNotFoundException, PaginationException, ViewMalformedException, - at.tuwien.exception.AccessDeniedException { + AccessDeniedException { final Long page = 0L; final Long size = 2L; @@ -587,7 +586,7 @@ public class ViewEndpointUnitTest extends BaseUnitTest { } else { log.trace("mock no access of database with id {} and user id {}", databaseId, userId); when(accessService.find(databaseId, userId)) - .thenThrow(NotAllowedException.class); + .thenThrow(AccessDeniedException.class); } when(viewService.findById(databaseId, viewId, principal)) .thenReturn(VIEW_1); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/DatabaseMapperTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/DatabaseMapperTest.java index 34bf4677b1..78dcd07ea9 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/DatabaseMapperTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/DatabaseMapperTest.java @@ -48,13 +48,10 @@ public class DatabaseMapperTest extends BaseUnitTest { @Test public void userToRawCreateUserQuery_fails () { - final UserDto request = UserDto.builder() - .username("mock") - .build(); /* test */ assertThrows(QueryMalformedException.class, () -> { - databaseMapper.userToRawCreateUserQuery(null, request); + databaseMapper.userToRawCreateUserQuery(null, USER_1); }); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewRepositoryIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewRepositoryIntegrationTest.java index a3c11ad09b..9fc3776669 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewRepositoryIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewRepositoryIntegrationTest.java @@ -77,7 +77,7 @@ public class ViewRepositoryIntegrationTest extends BaseUnitTest { public void findAllPublicOrMineByDatabaseId_succeeds() { /* test */ - final List<View> response = viewRepository.findAllPublicOrMineByDatabaseId(DATABASE_1_ID, USER_1_USERNAME); + final List<View> response = viewRepository.findAllPublicOrMineByDatabaseId(DATABASE_1_ID, USER_1_ID); assertEquals(3, response.size()); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceIntegrationTest.java index cf2e31e059..bdce53ceb3 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceIntegrationTest.java @@ -10,6 +10,7 @@ import at.tuwien.config.MariaDbConfig; import at.tuwien.entities.database.AccessType; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.exception.*; +import at.tuwien.gateway.KeycloakGateway; import at.tuwien.repository.mdb.*; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; @@ -19,6 +20,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.MariaDBContainer; @@ -42,6 +44,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @MockOpensearch public class AccessServiceIntegrationTest extends BaseUnitTest { + @MockBean + private KeycloakGateway keycloakGateway; + @Autowired private ImageRepository imageRepository; @@ -73,46 +78,47 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { public static Stream<Arguments> create_succeeds_parameters() { return Stream.of( - Arguments.arguments("general", AccessTypeDto.READ, AccessType.READ, USER_3_USERNAME, USER_3_ID) + Arguments.arguments("general", AccessTypeDto.READ, AccessType.READ, USER_3_ID) ); } public static Stream<Arguments> create_fails_parameters() { return Stream.of( - Arguments.arguments("general", NotAllowedException.class, AccessTypeDto.READ, USER_2_USERNAME) + Arguments.arguments("general", NotAllowedException.class, AccessTypeDto.READ, USER_2_ID) ); } public static Stream<Arguments> update_succeeds_parameters() { return Stream.of( Arguments.arguments("same access", DATABASE_1_ID, AccessTypeDto.READ, AccessType.READ, - USER_2_USERNAME, USER_2_ID), + USER_2_ID), Arguments.arguments("write own access", DATABASE_1_ID, AccessTypeDto.WRITE_OWN, - AccessType.WRITE_OWN, USER_2_USERNAME, USER_2_ID), + AccessType.WRITE_OWN, USER_2_ID), Arguments.arguments("write all access", DATABASE_1_ID, AccessTypeDto.WRITE_ALL, - AccessType.WRITE_ALL, USER_2_USERNAME, USER_2_ID) + AccessType.WRITE_ALL, USER_2_ID) ); } public static Stream<Arguments> update_fails_parameters() { return Stream.of( Arguments.arguments("user not found", UserNotFoundException.class, DATABASE_1_ID, - AccessTypeDto.READ, "l33tsp34k"), + AccessTypeDto.READ, UUID.fromString("deadbeef-fc88-4abd-a289-455e34b0e80d"), null), Arguments.arguments("database not found", DatabaseNotFoundException.class, DATABASE_2_ID, - AccessTypeDto.READ, USER_2_USERNAME) + AccessTypeDto.READ, USER_1_ID) ); } public static Stream<Arguments> delete_fails_parameters() { return Stream.of( - Arguments.arguments("user not found", UserNotFoundException.class, "l33tsp34k"), - Arguments.arguments("is owner", NotAllowedException.class, USER_1_USERNAME) + Arguments.arguments("user not found", UserNotFoundException.class, + UUID.fromString("deadbeef-fc88-4abd-a289-455e34b0e80d"), null), + Arguments.arguments("is owner", NotAllowedException.class, USER_1_ID) ); } public static Stream<Arguments> delete_succeeds_parameters() { return Stream.of( - Arguments.arguments("general", USER_2_USERNAME) + Arguments.arguments("general", USER_2_ID) ); } @@ -181,8 +187,8 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @ParameterizedTest @MethodSource("update_fails_parameters") - protected <T extends Throwable> void update_fails(String name, Class<T> expectedException, - Long databaseId, AccessTypeDto accessTypeDto, UUID userId) { + protected <T extends Throwable> void update_fails(String name, Class<T> expectedException, Long databaseId, + AccessTypeDto accessTypeDto, UUID userId) { final DatabaseModifyAccessDto request = DatabaseModifyAccessDto.builder() .type(accessTypeDto) .build(); @@ -205,9 +211,9 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @ParameterizedTest @MethodSource("delete_succeeds_parameters") - protected <T extends Throwable> void delete_succeeds(String name, UUID userId) throws UserNotFoundException, - NotAllowedException, QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, - KeycloakRemoteException, AccessDeniedException { + protected <T extends Throwable> void delete_succeeds(String name, UUID userId) + throws UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseNotFoundException, + DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException { /* test */ accessService.delete(DATABASE_1_ID, userId); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceUnitTest.java index 60fd2a8f06..98f12a337b 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/AccessServiceUnitTest.java @@ -86,7 +86,7 @@ public class AccessServiceUnitTest extends BaseUnitTest { .thenReturn(Optional.empty()); /* test */ - assertThrows(NotAllowedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { accessService.find(DATABASE_1_ID, USER_1_ID); }); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceIntegrationTest.java index ac337d5d52..d05fbd5a36 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceIntegrationTest.java @@ -89,7 +89,6 @@ public class DataCiteIdentifierServiceIntegrationTest extends BaseUnitTest { QueryNotFoundException, IdentifierPublishingNotAllowedException, RemoteUnavailableException, IdentifierRequestException, ViewNotFoundException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { - final Principal principal = new BasicUserPrincipal(USER_1_USERNAME); final DataCiteBody<DataCiteDoi> response = new DataCiteBody<>(new DataCiteData<>(null, "dois", new DataCiteDoi(IDENTIFIER_1_DOI_NOT_NULL))); @@ -100,7 +99,7 @@ public class DataCiteIdentifierServiceIntegrationTest extends BaseUnitTest { when(restTemplateBuilder.build()).thenReturn(restTemplate); /* test */ - Identifier result = dataCiteIdentifierService.create(IDENTIFIER_1_DTO_REQUEST, principal); + Identifier result = dataCiteIdentifierService.create(IDENTIFIER_1_DTO_REQUEST, USER_1_PRINCIPAL); assertTrue(identifierRepository.existsById(result.getId())); assertEquals(IDENTIFIER_1_DOI_NOT_NULL, result.getDoi()); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceIntegrationTest.java index 9903d8377d..6e37ebf464 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceIntegrationTest.java @@ -4,8 +4,6 @@ import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.database.*; -import at.tuwien.api.user.UserAttributesDto; -import at.tuwien.api.user.UserDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.entities.database.Database; import at.tuwien.exception.*; @@ -113,7 +111,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { when(databaseIdxRepository.save(any(DatabaseDto.class))) .thenReturn(DATABASE_1_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); /* test */ generic_create(DATABASE_1_CREATE, DATABASE_1); @@ -129,7 +127,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { when(databaseIdxRepository.save(any(DatabaseDto.class))) .thenReturn(DATABASE_1_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); /* test */ generic_create(DATABASE_1_CREATE, DATABASE_1); @@ -147,7 +145,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { .thenReturn(DATABASE_2_DTO) .thenReturn(DATABASE_3_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); /* test */ generic_create(DATABASE_2_CREATE, DATABASE_2); @@ -165,7 +163,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { .thenReturn(DATABASE_3_DTO) .thenReturn(DATABASE_2_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); /* test */ generic_create(DATABASE_3_CREATE, DATABASE_3); @@ -181,7 +179,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { when(databaseIdxRepository.save(any(DatabaseDto.class))) .thenReturn(DATABASE_1_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); final Database database = generic_create(DATABASE_1_CREATE, DATABASE_1); @@ -191,13 +189,6 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { @Test public void updatePassword_canLogin_succeeds() throws Exception { - final UserDto request = UserDto.builder() - .id(USER_1_ID) - .username(USER_1_USERNAME) - .attributes(UserAttributesDto.builder() - .mariadbPassword(USER_2_DATABASE_PASSWORD) - .build()) - .build(); /* mock */ MariaDbConfig.dropDatabase(CONTAINER_1, DATABASE_1_INTERNALNAME); @@ -206,8 +197,8 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { when(databaseIdxRepository.save(any(DatabaseDto.class))) .thenReturn(DATABASE_1_DTO); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); - databaseService.updatePassword(request); + .thenReturn(USER_1); + databaseService.updatePassword(USER_1); /* test */ assertThrows(SQLInvalidAuthorizationSpecException.class, () -> { @@ -259,6 +250,9 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { public void create_userProcedureUser_succeeds() throws SQLException, QueryMalformedException { /* mock */ + MariaDbConfig.dropDatabase(CONTAINER_1, DATABASE_3_INTERNALNAME); + MariaDbConfig.createInitDatabase(CONTAINER_1, DATABASE_3); + MariaDbConfig.grantUserPermissions(CONTAINER_1, DATABASE_3, "junit1"); databaseAccessRepository.save(DATABASE_3_USER_1_WRITE_ALL_ACCESS); /* test */ @@ -291,8 +285,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { } @Test - public void transfer_succeeds() throws DatabaseNotFoundException, UserNotFoundException, SQLException, - KeycloakRemoteException, AccessDeniedException { + public void transfer_succeeds() throws DatabaseNotFoundException, UserNotFoundException{ final DatabaseTransferDto request = DatabaseTransferDto.builder() .username(USER_2_USERNAME) .build(); @@ -300,9 +293,9 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { /* mock */ databaseRepository.save(DATABASE_1_SIMPLE); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); when(userService.findByUsername(USER_2_USERNAME)) - .thenReturn(USER_2_DTO); + .thenReturn(USER_2); /* test */ final Database response = databaseService.transfer(DATABASE_1_ID, request); @@ -316,7 +309,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { protected void generic_insert(String query, Long assertQueryId) throws SQLException, QueryMalformedException { /* mock */ - mariaDbConfig.mockGrantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); + mariaDbConfig.grantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); /* test */ final Long response = MariaDbConfig.mockSystemQueryInsert(DATABASE_3, query); @@ -336,7 +329,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { protected void generic_system_insert(String username, String password) throws SQLException, QueryMalformedException { /* mock */ - mariaDbConfig.mockGrantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); + mariaDbConfig.grantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); /* test */ final Long queryId = MariaDbConfig.mockSystemQueryInsert(DATABASE_3, QUERY_4_STATEMENT, username, password); @@ -346,7 +339,7 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { protected void generic_user_insert(String username, String password) throws SQLException, QueryMalformedException { /* mock */ - mariaDbConfig.mockGrantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); + mariaDbConfig.grantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); /* test */ final Long queryId = MariaDbConfig.mockUserQueryInsert(DATABASE_3, QUERY_4_STATEMENT, username, password); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceUnitTest.java index c63a62509f..7342996925 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceUnitTest.java @@ -108,7 +108,7 @@ public class DatabaseServiceUnitTest extends BaseUnitTest { /* mock */ when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); when(containerRepository.findById(CONTAINER_1_ID)) .thenReturn(Optional.empty()); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceUnitTest.java index ed996b9ca1..3ced0a81a4 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceUnitTest.java @@ -180,7 +180,7 @@ public class IdentifierServiceUnitTest extends BaseUnitTest { throws DatabaseNotFoundException, UserNotFoundException, IdentifierAlreadyExistsException, QueryNotFoundException, IdentifierPublishingNotAllowedException, RemoteUnavailableException, IdentifierRequestException, ViewNotFoundException, QueryStoreException, DatabaseConnectionException, - ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { + ImageNotSupportedException { /* mock */ when(databaseService.find(DATABASE_1_ID)) @@ -188,7 +188,7 @@ public class IdentifierServiceUnitTest extends BaseUnitTest { when(restTemplate.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), eq(QueryDto.class))) .thenReturn(ResponseEntity.ok(QUERY_1_DTO)); when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1_DTO); + .thenReturn(USER_1); when(identifierRepository.save(any(Identifier.class))) .thenReturn(IDENTIFIER_1); when(identifierIdxRepository.save(any(IdentifierDto.class))) diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceIntegrationTest.java index 86767db28d..5c94c0f746 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceIntegrationTest.java @@ -168,7 +168,7 @@ public class MessageQueueServiceIntegrationTest extends BaseUnitTest { amqpUtils.setPermissions(REALM_DBREPO_NAME, USER_1_USERNAME, USER_1_RABBITMQ_GRANT_DTO); /* test */ - messageQueueService.updatePermissions(USER_1_DTO); + messageQueueService.updatePermissions(USER_1); return amqpUtils.getPermissions(USER_1_USERNAME); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceIntegrationTest.java index 18817fad43..cd8763f03d 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceIntegrationTest.java @@ -5,6 +5,7 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.user.*; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -35,10 +36,10 @@ public class UserServiceIntegrationTest extends BaseUnitTest { private UserService userService; @Test - public void findByUsername_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { + public void findByUsername_succeeds() throws UserNotFoundException { /* test */ - final UserDto response = userService.findByUsername(USER_1_USERNAME); + final User response = userService.findByUsername(USER_1_USERNAME); assertEquals(USER_1_ID, response.getId()); assertEquals(USER_1_USERNAME, response.getUsername()); } @@ -56,7 +57,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { public void findAll_succeeds() throws KeycloakRemoteException, AccessDeniedException { /* test */ - final List<UserBriefDto> response = userService.findAll(); + final List<User> response = userService.findAll(); assertEquals(1, response.size()); } @@ -70,7 +71,8 @@ public class UserServiceIntegrationTest extends BaseUnitTest { .build(); /* test */ - final UserDto response = userService.create(request); + final User response = userService.create(request); + assertEquals(USER_2_USERNAME, response.getUsername()); } @Test @@ -103,8 +105,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { @Test @Transactional - public void modify_succeeds() throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, - AccessDeniedException { + public void modify_succeeds() throws UserNotFoundException { final UserUpdateDto request = UserUpdateDto.builder() .firstname(USER_1_FIRSTNAME) .lastname(USER_1_LASTNAME) @@ -113,12 +114,12 @@ public class UserServiceIntegrationTest extends BaseUnitTest { .build(); /* test */ - final UserDto response = userService.modify(USER_1_ID, request); + final User response = userService.modify(USER_1_ID, request); assertEquals(USER_1_ID, response.getId()); assertEquals(USER_1_FIRSTNAME, response.getFirstname()); assertEquals(USER_1_LASTNAME, response.getLastname()); - assertEquals("NASA", response.getAttributes().getAffiliation()); - assertNull(response.getAttributes().getOrcid()); + assertEquals("NASA", response.getAffiliation()); + assertNull(response.getOrcid()); } @Test @@ -127,7 +128,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { .firstname(USER_2_FIRSTNAME) .lastname(USER_2_LASTNAME) .affiliation(USER_2_AFFILIATION) - .orcid(USER_2_ORCID) + .orcid(USER_2_ORCID_URL) .build(); /* test */ @@ -137,8 +138,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { } @Test - public void updatePassword_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException, - QueryMalformedException, DatabaseMalformedException { + public void updatePassword_succeeds() throws KeycloakRemoteException, AccessDeniedException { final UserPasswordDto request = UserPasswordDto.builder() .password(USER_1_PASSWORD) .build(); @@ -161,15 +161,14 @@ public class UserServiceIntegrationTest extends BaseUnitTest { @Test @Transactional - public void toggleTheme_succeeds() throws UserNotFoundException, UserAttributeNotFoundException, - KeycloakRemoteException, AccessDeniedException { + public void toggleTheme_succeeds() throws UserNotFoundException { final UserThemeSetDto request = UserThemeSetDto.builder() .themeDark(true) .build(); /* test */ - final UserDto response = userService.toggleTheme(USER_1_ID, request); - assertNotNull(response.getAttributes()); + final User response = userService.toggleTheme(USER_1_ID, request); + assertTrue(response.getThemeDark()); } @Test @@ -185,11 +184,11 @@ public class UserServiceIntegrationTest extends BaseUnitTest { } @Test - public void find_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { + public void find_succeeds() throws UserNotFoundException { /* test */ - final UserDto user = userService.find(USER_1_ID); - assertEquals(USER_1_ID, user.getId()); + final User user = userService.find(USER_1_ID); + assertEquals(USER_1_USERNAME, user.getUsername()); } @Test diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceUnitTest.java index c6cb1398ed..515795e3c0 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserServiceUnitTest.java @@ -3,18 +3,23 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; +import at.tuwien.api.user.UserBriefDto; import at.tuwien.api.user.UserDto; -import at.tuwien.exception.AccessDeniedException; -import at.tuwien.exception.KeycloakRemoteException; -import at.tuwien.exception.UserNotFoundException; +import at.tuwien.entities.user.User; +import at.tuwien.exception.*; +import at.tuwien.gateway.KeycloakGateway; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; +import java.util.List; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; @ExtendWith(SpringExtension.class) @SpringBootTest @@ -22,18 +27,95 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @MockOpensearch public class UserServiceUnitTest extends BaseUnitTest { + @MockBean + private KeycloakGateway keycloakGateway; + @Autowired private UserService userService; @Test - public void findByUsername_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { + public void findByUsername_succeeds() throws UserNotFoundException { + + /* test */ + final User response = userService.findByUsername(USER_1_USERNAME); + assertEquals(USER_1_ID, response.getId()); + assertEquals(USER_1_USERNAME, response.getUsername()); + } + + @Test + public void find_succeeds() throws UserNotFoundException { + + /* test */ + final User response = userService.find(USER_1_ID); + assertEquals(USER_1_ID, response.getId()); + assertEquals(USER_1_USERNAME, response.getUsername()); + } + + @Test + public void findAll_succeeds() throws UserNotFoundException { + + /* test */ + final List<User> response = userService.findAll(); + assertEquals(1, response.size()); + } + + @Test + public void create_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException, + UserAlreadyExistsException { + + /* mock */ + doNothing() + .when(keycloakGateway) + .createUser(USER_1_KEYCLOAK_SIGNUP_REQUEST); + when(keycloakGateway.findByUsername(USER_1_USERNAME)) + .thenReturn(USER_1_KEYCLOAK_DTO); /* test */ - final UserDto response = userService.findByUsername(USER_1_USERNAME); + final User response = userService.create(USER_1_SIGNUP_REQUEST_DTO); assertEquals(USER_1_ID, response.getId()); assertEquals(USER_1_USERNAME, response.getUsername()); } + @Test + public void modify_succeeds() throws UserNotFoundException { + + /* test */ + final User response = userService.modify(USER_1_ID, USER_1_UPDATE_DTO); + assertEquals(USER_1_ID, response.getId()); + assertEquals(USER_1_USERNAME, response.getUsername()); + } + + @Test + public void modify_notExists_succeeds() { + + /* test */ + assertThrows(KeycloakRemoteException.class, () -> { + userService.modify(USER_1_ID, USER_1_UPDATE_DTO); + }); + } + + @Test + public void toggleTheme_succeeds() throws UserNotFoundException { + + /* test */ + final User response = userService.toggleTheme(USER_1_ID, USER_1_THEME_SET_DTO); + assertEquals(USER_1_ID, response.getId()); + assertEquals(USER_1_USERNAME, response.getUsername()); + assertEquals(USER_1_THEME_DARK, response.getThemeDark()); + } + + @Test + public void updatePassword_succeeds() throws KeycloakRemoteException, AccessDeniedException { + + /* mock */ + doNothing() + .when(keycloakGateway) + .updateUserCredentials(USER_1_ID, USER_1_PASSWORD_DTO); + + /* test */ + userService.updatePassword(USER_1_ID, USER_1_PASSWORD_DTO); + } + @Test public void findByUsername_fails() { @@ -43,5 +125,14 @@ public class UserServiceUnitTest extends BaseUnitTest { }); } + @Test + public void find_fails() { + + /* test */ + assertThrows(UserNotFoundException.class, () -> { + userService.find(USER_1_ID); + }); + } + } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/validator/EndpointValidatorUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/validator/EndpointValidatorUnitTest.java index f47a371280..9a22b2bad4 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/validator/EndpointValidatorUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/validator/EndpointValidatorUnitTest.java @@ -163,12 +163,12 @@ public class EndpointValidatorUnitTest extends BaseUnitTest { /* mock */ when(databaseService.find(DATABASE_1_ID)) .thenReturn(DATABASE_1); - doThrow(NotAllowedException.class) + doThrow(AccessDeniedException.class) .when(accessService) .find(DATABASE_1_ID, USER_1_ID); /* test */ - assertThrows(NotAllowedException.class, () -> { + assertThrows(AccessDeniedException.class, () -> { endpointValidator.validateOnlyAccessOrPublic(DATABASE_1_ID, USER_1_PRINCIPAL); }); } diff --git a/dbrepo-metadata-service/rest-service/src/test/resources/init/users.sql b/dbrepo-metadata-service/rest-service/src/test/resources/init/users.sql index 45f7b53a0f..62063400df 100644 --- a/dbrepo-metadata-service/rest-service/src/test/resources/init/users.sql +++ b/dbrepo-metadata-service/rest-service/src/test/resources/init/users.sql @@ -1,4 +1,4 @@ -CREATE USER junit1 IDENTIFIED BY 'junit1'; -CREATE USER junit2 IDENTIFIED BY 'junit2'; -CREATE USER junit3 IDENTIFIED BY 'junit3'; -CREATE USER junit4 IDENTIFIED BY 'junit4'; \ No newline at end of file +CREATE USER IF NOT EXISTS junit1 IDENTIFIED BY 'junit1'; +CREATE USER IF NOT EXISTS junit2 IDENTIFIED BY 'junit2'; +CREATE USER IF NOT EXISTS junit3 IDENTIFIED BY 'junit3'; +CREATE USER IF NOT EXISTS junit4 IDENTIFIED BY 'junit4'; \ No newline at end of file diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/KeycloakGateway.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/KeycloakGateway.java index b1e4a00a36..53216689d5 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/KeycloakGateway.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/KeycloakGateway.java @@ -1,6 +1,5 @@ package at.tuwien.gateway; -import at.tuwien.api.keycloak.UserAttributesDto; import at.tuwien.api.keycloak.UserCreateDto; import at.tuwien.api.keycloak.UserDto; import at.tuwien.api.user.UserPasswordDto; @@ -8,25 +7,15 @@ import at.tuwien.exception.AccessDeniedException; import at.tuwien.exception.KeycloakRemoteException; import at.tuwien.exception.UserNotFoundException; -import java.util.List; import java.util.UUID; public interface KeycloakGateway { void createUser(UserCreateDto data) throws AccessDeniedException, KeycloakRemoteException; - void updateUserAttributes(UUID id, UserAttributesDto data) throws AccessDeniedException, KeycloakRemoteException; - void updateUserCredentials(UUID id, UserPasswordDto password) throws AccessDeniedException, KeycloakRemoteException; UserDto findByUsername(String username) throws AccessDeniedException, UserNotFoundException, KeycloakRemoteException; - - UserDto findByEmail(String email) throws AccessDeniedException, UserNotFoundException, - KeycloakRemoteException; - - UserDto findById(UUID id) throws AccessDeniedException, UserNotFoundException, KeycloakRemoteException; - - List<UserDto> findAllUsers() throws AccessDeniedException, KeycloakRemoteException; } diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/impl/KeycloakGatewayImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/impl/KeycloakGatewayImpl.java index 3ab32919ef..6068f1e106 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/impl/KeycloakGatewayImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/impl/KeycloakGatewayImpl.java @@ -18,8 +18,6 @@ import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -import java.util.Arrays; -import java.util.List; import java.util.UUID; @Log4j2 @@ -75,28 +73,6 @@ public class KeycloakGatewayImpl implements KeycloakGateway { } } - @Override - public void updateUserAttributes(UUID id, UserAttributesDto data) throws AccessDeniedException, - KeycloakRemoteException { - /* obtain admin token */ - final HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); - final UpdateAttributesDto payload = userMapper.userAttributesDtoToUpdateAttributesDto(data); - final ResponseEntity<Void> response; - try { - response = restTemplate.exchange("/api/auth/admin/realms/dbrepo/users/" + id, HttpMethod.PUT, - new HttpEntity<>(payload, headers), Void.class); - } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { - log.error("Failed to update user attributes: {}", e.getMessage()); - throw new KeycloakRemoteException("Failed to update user attributes: " + e.getMessage()); - } - if (!response.getStatusCode().equals(HttpStatus.ACCEPTED)) { - log.error("Failed to update user attributes: status {} was not expected", response.getStatusCode().value()); - throw new KeycloakRemoteException("Failed to update user attributes: status " + response.getStatusCode().value() + "was not expected"); - } - } - @Override public void updateUserCredentials(UUID id, UserPasswordDto data) throws AccessDeniedException, KeycloakRemoteException { @@ -142,66 +118,4 @@ public class KeycloakGatewayImpl implements KeycloakGateway { return body[0]; } - @Override - public UserDto findByEmail(String email) throws AccessDeniedException, UserNotFoundException, - KeycloakRemoteException { - /* obtain admin token */ - final HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); - final ResponseEntity<UserDto[]> response; - try { - response = restTemplate.exchange("/api/auth/admin/realms/dbrepo/users/?email=" + email, - HttpMethod.GET, new HttpEntity<>(null, headers), UserDto[].class); - } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { - log.error("Failed to find user: {}", e.getMessage()); - throw new KeycloakRemoteException("Failed to find user: " + e.getMessage()); - } - final UserDto[] body = response.getBody(); - if (body == null || body.length != 1) { - log.error("Failed to find user with email {}: response is not exactly 1 but is {}", email, body.length); - throw new UserNotFoundException("Failed to find user with email " + email); - } - return body[0]; - } - - @Override - public UserDto findById(UUID id) throws AccessDeniedException, UserNotFoundException, KeycloakRemoteException { - /* obtain admin token */ - final HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); - final ResponseEntity<UserDto> response; - try { - response = restTemplate.exchange("/api/auth/admin/realms/dbrepo/users/" + id, HttpMethod.GET, - new HttpEntity<>(null, headers), UserDto.class); - } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { - log.error("Failed to find user: {}", e.getMessage()); - throw new KeycloakRemoteException("Failed to find user: " + e.getMessage()); - } - return response.getBody(); - } - - @Override - public List<UserDto> findAllUsers() throws AccessDeniedException, KeycloakRemoteException { - /* obtain admin token */ - final HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); - final ResponseEntity<UserDto[]> response; - try { - response = restTemplate.exchange("/api/auth/admin/realms/dbrepo/users/", HttpMethod.GET, - new HttpEntity<>(null, headers), UserDto[].class); - } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { - log.error("Failed to find users: {}", e.getMessage()); - throw new KeycloakRemoteException("Failed to find users: " + e.getMessage()); - } - final UserDto[] body = response.getBody(); - if (body == null) { - log.error("Failed to find users: body is empty"); - throw new KeycloakRemoteException("Failed to find users: body is empty"); - } - return Arrays.asList(body); - } - } diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/DatabaseService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/DatabaseService.java index db43743d78..a7d41e2443 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/DatabaseService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/DatabaseService.java @@ -5,6 +5,7 @@ import at.tuwien.api.database.DatabaseModifyVisibilityDto; import at.tuwien.api.database.DatabaseTransferDto; import at.tuwien.api.user.UserDto; import at.tuwien.entities.database.Database; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import org.springframework.stereotype.Service; @@ -89,7 +90,7 @@ public interface DatabaseService { DatabaseMalformedException, AmqpException, ContainerConnectionException, UserNotFoundException, DatabaseNameExistsException, DatabaseConnectionException, QueryMalformedException, KeycloakRemoteException, AccessDeniedException; - void updatePassword(UserDto user) throws DatabaseMalformedException, QueryMalformedException; + void updatePassword(User user) throws DatabaseMalformedException, QueryMalformedException; /** * Updates the visibility of the database. diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/MessageQueueService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/MessageQueueService.java index 2cfa8eef79..00f989a5bf 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/MessageQueueService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/MessageQueueService.java @@ -3,6 +3,7 @@ package at.tuwien.service; import at.tuwien.api.user.UserDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.Table; +import at.tuwien.entities.user.User; import at.tuwien.exception.AmqpException; import at.tuwien.exception.BrokerVirtualHostCreationException; import at.tuwien.exception.BrokerVirtualHostGrantException; @@ -54,7 +55,7 @@ public interface MessageQueueService { * @param user The user. * @throws BrokerVirtualHostGrantException The Broker Service refused to grant the permissions. */ - void updatePermissions(UserDto user) throws BrokerVirtualHostGrantException; + void updatePermissions(User user) throws BrokerVirtualHostGrantException; /** * Deletes an exchange for a database. diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserService.java index 7aee0608b0..4b0b453617 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserService.java @@ -2,6 +2,7 @@ package at.tuwien.service; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.user.*; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import java.util.List; @@ -14,7 +15,7 @@ public interface UserService { * * @return The list of users. */ - List<UserBriefDto> findAll() throws KeycloakRemoteException, AccessDeniedException; + List<User> findAll(); /** * Finds a user by username. @@ -23,7 +24,7 @@ public interface UserService { * @return The user, if successfully. * @throws UserNotFoundException The user with this username was not found in the metadata database. */ - UserDto findByUsername(String username) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; + User findByUsername(String username) throws UserNotFoundException; /** * Finds a specific user in the metadata database by given id. @@ -32,16 +33,16 @@ public interface UserService { * @return The user if successful. False otherwise. * @throws UserNotFoundException The user was not found. */ - UserDto find(UUID id) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; + User find(UUID id) throws UserNotFoundException; /** * Creates a user in the metadata database managed by Keycloak in the given realm. * - * @param data The user data. + * @param data The user data. * @return The user, if successful. False otherwise. * @throws UserAlreadyExistsException The user already exists in the metadata database. */ - UserDto create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, + User create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, KeycloakRemoteException, UserNotFoundException; /** @@ -51,18 +52,16 @@ public interface UserService { * @param data The user information. * @return The user if successful. False otherwise. * @throws UserNotFoundException The user was not found. - * @throws UserAttributeNotFoundException One or more user attributes for the user information were not found. */ - UserDto modify(UUID id, UserUpdateDto data) throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException; + User modify(UUID id, UserUpdateDto data) throws UserNotFoundException; /** * Updates the user password for a user with given id. * * @param id The user id. * @param data The new password. - * @throws UserNotFoundException The user was not found. */ - void updatePassword(UUID id, UserPasswordDto data) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException, QueryMalformedException, DatabaseMalformedException; + void updatePassword(UUID id, UserPasswordDto data) throws KeycloakRemoteException, AccessDeniedException; /** * Updates the user theme for a user with given id. @@ -71,9 +70,8 @@ public interface UserService { * @param data The user theme. * @return The user if successful. False otherwise. * @throws UserNotFoundException The user was not found. - * @throws UserAttributeNotFoundException One or more user attributes for the user information were not found. */ - UserDto toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException; + User toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException; /** * Validates if a user with the given username already exists in the metadata database. diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/AccessServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/AccessServiceImpl.java index be5b7cf1a5..ca0ee9a3b7 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/AccessServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/AccessServiceImpl.java @@ -2,14 +2,12 @@ package at.tuwien.service.impl; import at.tuwien.api.database.DatabaseGiveAccessDto; import at.tuwien.api.database.DatabaseModifyAccessDto; -import at.tuwien.api.user.UserDto; import at.tuwien.entities.container.Container; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; -import at.tuwien.gateway.KeycloakGateway; import at.tuwien.mapper.DatabaseMapper; -import at.tuwien.mapper.UserMapper; import at.tuwien.repository.mdb.DatabaseAccessRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; @@ -31,19 +29,17 @@ import java.util.UUID; @Service public class AccessServiceImpl extends HibernateConnector implements AccessService { - private final UserMapper userMapper; + private final UserService userService; private final DatabaseMapper databaseMapper; private final DatabaseService databaseService; - private final KeycloakGateway keycloakGateway; private final DatabaseAccessRepository databaseAccessRepository; @Autowired - public AccessServiceImpl(UserMapper userMapper, DatabaseMapper databaseMapper, DatabaseService databaseService, - KeycloakGateway keycloakGateway, DatabaseAccessRepository databaseAccessRepository) { - this.userMapper = userMapper; + public AccessServiceImpl(UserService userService, DatabaseMapper databaseMapper, DatabaseService databaseService, + DatabaseAccessRepository databaseAccessRepository) { + this.userService = userService; this.databaseMapper = databaseMapper; this.databaseService = databaseService; - this.keycloakGateway = keycloakGateway; this.databaseAccessRepository = databaseAccessRepository; } @@ -83,10 +79,10 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); - final UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(accessDto.getUserId())); + final User user = userService.find(accessDto.getUserId()); if (databaseAccessRepository.findByDatabaseIdAndUserId(databaseId, user.getId()).isPresent()) { - log.error("Failed to give access to user with id {}, has already permission", accessDto.getUserId()); - throw new NotAllowedException("Failed to give access"); + log.error("Failed to give access to user with id {}: has already permission", accessDto.getUserId()); + throw new NotAllowedException("Failed to give access to user with id " + accessDto.getUserId() + ": has already permission"); } final ComboPooledDataSource dataSource = getPrivilegedDataSource(container.getImage(), container, database); try { @@ -121,13 +117,12 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); + final User user = userService.find(userId); if (database.getOwnedBy().equals(userId)) { log.error("Failed to modify database access of user with id {}: is the owner", userId); throw new NotAllowedException("Failed to modify database access of user with id " + userId + ": is the owner"); } - final at.tuwien.api.user.UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(userId)); final ComboPooledDataSource dataSource = getPrivilegedDataSource(container.getImage(), container, database); - final DatabaseGiveAccessDto giveAccess = databaseMapper.databaseModifyAccessToDatabaseGiveAccessDto(userId, accessDto.getType()); try { final Connection connection = dataSource.getConnection(); /* create user if not exists */ @@ -159,11 +154,11 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); + final User user = userService.find(userId); if (database.getOwnedBy().equals(userId)) { log.error("Failed to revoke database access of user with id {}: is the owner", userId); throw new NotAllowedException("Failed to revoke database access of user with id " + userId + ": is the owner"); } - final at.tuwien.api.user.UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(userId)); final ComboPooledDataSource dataSource = getPrivilegedDataSource(container.getImage(), container); try { final Connection connection = dataSource.getConnection(); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/MariaDbServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/MariaDbServiceImpl.java index 016bb85c43..88f490be5d 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/MariaDbServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/MariaDbServiceImpl.java @@ -7,6 +7,7 @@ import at.tuwien.api.user.UserDto; import at.tuwien.config.QueryConfig; import at.tuwien.entities.container.Container; import at.tuwien.entities.database.Database; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.DatabaseMapper; import at.tuwien.repository.mdb.DatabaseRepository; @@ -140,7 +141,7 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe /* start the object */ final Database database = databaseMapper.databaseCreateDtoToDatabase(createDto); final Container container = containerService.find(database.getCid()); - final UserDto owner = userService.findByUsername(principal.getName()); + final User owner = userService.findByUsername(principal.getName()); database.setContainer(container); database.setOwnedBy(owner.getId()); database.setCreatedBy(owner.getId()); @@ -176,7 +177,7 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe @Override @Transactional(readOnly = true) - public void updatePassword(UserDto user) throws DatabaseMalformedException, QueryMalformedException { + public void updatePassword(User user) throws DatabaseMalformedException, QueryMalformedException { /* start the object */ final List<Database> databases = databaseRepository.findReadAccess(user.getId()) .stream() @@ -219,10 +220,10 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe @Override @Transactional public Database transfer(Long databaseId, DatabaseTransferDto transferDto) throws DatabaseNotFoundException, - UserNotFoundException, KeycloakRemoteException, AccessDeniedException { + UserNotFoundException { /* check */ final Database database = findById(databaseId); - final UserDto user = userService.findByUsername(transferDto.getUsername()); + final User user = userService.findByUsername(transferDto.getUsername()); /* update in metadata database */ database.setOwnedBy(user.getId()); final Database entity = databaseRepository.save(database); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/OntologyServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/OntologyServiceImpl.java index b52c92527d..424343dfc0 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/OntologyServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/OntologyServiceImpl.java @@ -4,6 +4,7 @@ import at.tuwien.api.semantics.OntologyCreateDto; import at.tuwien.api.semantics.OntologyModifyDto; import at.tuwien.api.user.UserDto; import at.tuwien.entities.semantics.Ontology; +import at.tuwien.entities.user.User; import at.tuwien.exception.AccessDeniedException; import at.tuwien.exception.KeycloakRemoteException; import at.tuwien.exception.OntologyNotFoundException; @@ -54,7 +55,7 @@ public class OntologyServiceImpl implements OntologyService { @Override public Ontology create(OntologyCreateDto data, Principal principal) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { - final UserDto user = userService.findByUsername(principal.getName()); + final User user = userService.findByUsername(principal.getName()); final Ontology entity = ontologyMapper.ontologyCreateDtoToOntology(data); entity.setCreatedBy(user.getId()); final Ontology ontology = ontologyRepository.save(entity); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RabbitMqServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RabbitMqServiceImpl.java index 5cfec6e09b..db43f317d5 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RabbitMqServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RabbitMqServiceImpl.java @@ -3,10 +3,10 @@ package at.tuwien.service.impl; import at.tuwien.amqp.RabbitMqConsumer; import at.tuwien.api.amqp.ConsumerDto; import at.tuwien.api.amqp.GrantVirtualHostPermissionsDto; -import at.tuwien.api.user.UserDto; import at.tuwien.config.AmqpConfig; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.Table; +import at.tuwien.entities.user.User; import at.tuwien.exception.AmqpException; import at.tuwien.exception.BrokerVirtualHostCreationException; import at.tuwien.exception.BrokerVirtualHostGrantException; @@ -104,7 +104,7 @@ public class RabbitMqServiceImpl implements MessageQueueService { } @Override - public void updatePermissions(UserDto user) throws BrokerVirtualHostGrantException { + public void updatePermissions(User user) throws BrokerVirtualHostGrantException { final GrantVirtualHostPermissionsDto permissions = GrantVirtualHostPermissionsDto.builder() .configure(amqpMapper.databaseListToPermissionString(databaseRepository.findConfigureAccess(user.getId()))) .write(amqpMapper.databaseListToPermissionString(databaseRepository.findWriteAccess(user.getId()))) diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/StoreServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/StoreServiceImpl.java index ecd4617929..9c89af11d7 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/StoreServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/StoreServiceImpl.java @@ -2,15 +2,14 @@ package at.tuwien.service.impl; import at.tuwien.api.database.query.ExecuteStatementDto; import at.tuwien.api.database.query.QueryPersistDto; -import at.tuwien.api.user.UserDto; import at.tuwien.entities.database.Database; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; -import at.tuwien.gateway.KeycloakGateway; import at.tuwien.mapper.StoreMapper; -import at.tuwien.mapper.UserMapper; import at.tuwien.querystore.Query; import at.tuwien.service.DatabaseService; import at.tuwien.service.StoreService; +import at.tuwien.service.UserService; import com.mchange.v2.c3p0.ComboPooledDataSource; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; @@ -26,18 +25,15 @@ import java.util.List; @Service public class StoreServiceImpl extends HibernateConnector implements StoreService { - private final UserMapper userMapper; private final StoreMapper storeMapper; + private final UserService userService; private final DatabaseService databaseService; - private final KeycloakGateway keycloakGateway; @Autowired - public StoreServiceImpl(UserMapper userMapper, StoreMapper storeMapper, DatabaseService databaseService, - KeycloakGateway keycloakGateway) { - this.userMapper = userMapper; + public StoreServiceImpl(StoreMapper storeMapper, UserService userService, DatabaseService databaseService) { this.storeMapper = storeMapper; + this.userService = userService; this.databaseService = databaseService; - this.keycloakGateway = keycloakGateway; } @Override @@ -109,16 +105,13 @@ public class StoreServiceImpl extends HibernateConnector implements StoreService log.error("Currently only MariaDB is supported"); throw new ImageNotSupportedException("Currently only MariaDB is supported"); } - log.trace("insert into database id {}, metadata {}", databaseId, metadata); - /* user */ - final UserDto creator = userMapper.keycloakUserDtoToUserDto( - keycloakGateway.findByUsername(principal.getName())); + final User user = userService.findByUsername(principal.getName()); /* save */ final ComboPooledDataSource dataSource = getPrivilegedDataSource(database.getContainer().getImage(), database.getContainer(), database); try { final Connection connection = dataSource.getConnection(); - final CallableStatement callableStatement = storeMapper.queryStoreRawInsertQuery(connection, creator, metadata); + final CallableStatement callableStatement = storeMapper.queryStoreRawInsertQuery(connection, user, metadata); callableStatement.executeUpdate(); final Long queryId = callableStatement.getLong(4); callableStatement.close(); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserServiceImpl.java index 9ee82a9106..c29f1b7d01 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserServiceImpl.java @@ -2,17 +2,19 @@ package at.tuwien.service.impl; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.user.*; +import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.gateway.KeycloakGateway; import at.tuwien.mapper.UserMapper; +import at.tuwien.repository.mdb.UserRepository; import at.tuwien.repository.sdb.UserIdxRepository; -import at.tuwien.service.DatabaseService; import at.tuwien.service.UserService; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; +import java.util.Optional; import java.util.UUID; @Log4j2 @@ -20,104 +22,104 @@ import java.util.UUID; public class UserServiceImpl implements UserService { private final UserMapper userMapper; + private final UserRepository userRepository; private final KeycloakGateway keycloakGateway; - private final DatabaseService databaseService; private final UserIdxRepository userIdxRepository; @Autowired - public UserServiceImpl(UserMapper userMapper, KeycloakGateway keycloakGateway, DatabaseService databaseService, + public UserServiceImpl(UserMapper userMapper, UserRepository userRepository, KeycloakGateway keycloakGateway, UserIdxRepository userIdxRepository) { this.userMapper = userMapper; + this.userRepository = userRepository; this.keycloakGateway = keycloakGateway; - this.databaseService = databaseService; this.userIdxRepository = userIdxRepository; } @Override - public List<UserBriefDto> findAll() throws KeycloakRemoteException, AccessDeniedException { - return keycloakGateway.findAllUsers() - .stream() - .map(userMapper::keycloakUserDtoToUserBriefDto) - .toList(); + public List<User> findAll() { + return userRepository.findAll(); } @Override - public UserDto findByUsername(String username) throws UserNotFoundException, KeycloakRemoteException, - AccessDeniedException { - return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findByUsername(username)); + public User findByUsername(String username) throws UserNotFoundException { + final Optional<User> optional = userRepository.findByUsername(username); + if (optional.isEmpty()) { + log.error("Failed to find user with username {}: not present in metadata database", username); + throw new UserNotFoundException("Failed to find user with username " + username + ": not present in metadata database"); + } + return optional.get(); } @Override - public UserDto find(UUID id) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { - return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); + public User find(UUID id) throws UserNotFoundException { + final Optional<User> optional = userRepository.findById(id); + if (optional.isEmpty()) { + log.error("Failed to find user with id {}: not present in metadata database", id); + throw new UserNotFoundException("Failed to find user with id " + id + ": not present in metadata database"); + } + return optional.get(); } @Override - public UserDto create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, + public User create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, KeycloakRemoteException, UserNotFoundException { - /* create */ + /* create at authentication service */ + final User entity = User.builder() + .username(data.getUsername()) + .email(data.getEmail()) + .themeDark(true) + .build(); keycloakGateway.createUser(userMapper.signupRequestDtoToUserCreateDto(data)); - final at.tuwien.api.keycloak.UserDto keycloakUser = keycloakGateway.findByUsername(data.getUsername()); - final UserDto userDto = userMapper.keycloakUserDtoToUserDto(keycloakUser); + /* create at metadata database */ + entity.setId(keycloakGateway.findByUsername(data.getUsername()).getId()); + final User user = userRepository.save(entity); + log.info("Created user with id {} in metadata database", user.getId()); /* save in open search database */ - userIdxRepository.save(userMapper.keycloakUserDtoToUserDto(keycloakUser)); - log.info("Created user with id {} in open search database", userDto.getId()); - return userDto; + userIdxRepository.save(userMapper.userToUserDto(user)); + log.info("Created user with id {} in open search database", user.getId()); + return user; } @Override - public UserDto modify(UUID id, UserUpdateDto data) throws UserNotFoundException, UserAttributeNotFoundException, - KeycloakRemoteException, AccessDeniedException { - /* save */ - keycloakGateway.updateUserAttributes(id, userMapper.userUpdateDtoToUserAttributesDto(data)); - log.info("Updated user attributes for user with id {}", id); - /* save in open search database */ - final UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); - userIdxRepository.save(user); + public User modify(UUID id, UserUpdateDto data) throws UserNotFoundException { + final User entity = find(id); + entity.setFirstname(data.getFirstname()); + entity.setLastname(data.getLastname()); + entity.setAffiliation(data.getAffiliation()); + entity.setOrcid(data.getOrcid()); + final User user = userRepository.save(entity); + log.info("Updated user data for user with id {}", user.getId()); return user; } @Override - public void updatePassword(UUID id, UserPasswordDto data) throws KeycloakRemoteException, AccessDeniedException, - UserNotFoundException, QueryMalformedException, DatabaseMalformedException { - /* save */ + public void updatePassword(UUID id, UserPasswordDto data) throws KeycloakRemoteException, AccessDeniedException { keycloakGateway.updateUserCredentials(id, data); - final UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); - /* update in containers */ - databaseService.updatePassword(user); log.info("Updated user password with id {}", id); } @Override - public UserDto toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, KeycloakRemoteException, - AccessDeniedException { - /* save */ - keycloakGateway.updateUserAttributes(id, userMapper.userThemeSetDtoToUserAttributesDto(data)); + public User toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException { + final User entity = find(id); + entity.setThemeDark(data.getThemeDark()); + final User user = userRepository.save(entity); log.info("Updated theme by updating attribute with id {}", id); - return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); + return user; } @Override public void validateUsernameNotExists(String username) throws UserAlreadyExistsException { - try { - keycloakGateway.findByUsername(username); - } catch (KeycloakRemoteException | AccessDeniedException e) { - log.error("User with username {} already exists", username); - throw new UserAlreadyExistsException("User with username " + username + " already exists"); - } catch (UserNotFoundException e) { - /* ignore */ + if (userRepository.existsByUsername(username)) { + log.error("User with username {} already exists in metadata database", username); + throw new UserAlreadyExistsException("User with username " + username + " already exists in metadata database"); } } @Override public void validateEmailNotExists(String email) throws UserEmailAlreadyExistsException { - try { - keycloakGateway.findByEmail(email); - } catch (KeycloakRemoteException | AccessDeniedException e) { - log.error("User with email {} already exists", email); - throw new UserEmailAlreadyExistsException("User with email " + email + " already exists"); - } catch (UserNotFoundException e) { - /* ignore */ + if (userRepository.existsByEmail(email)) { + log.error("User with email {} already exists in metadata database", email); + throw new UserEmailAlreadyExistsException("User with email " + email + " already exists in metadata database"); } } } diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/ViewServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/ViewServiceImpl.java index 2cc7bb651c..af1c574167 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/ViewServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/ViewServiceImpl.java @@ -69,7 +69,7 @@ public class ViewServiceImpl extends HibernateConnector implements ViewService { return viewRepository.findAllPublicByDatabaseId(databaseId); } log.trace("principal is not null, list public views and mine"); - return viewRepository.findAllPublicOrMineByDatabaseId(databaseId, principal.getName()); + return viewRepository.findAllPublicOrMineByDatabaseId(databaseId, UserUtil.getId(principal)); } @Override @@ -81,7 +81,7 @@ public class ViewServiceImpl extends HibernateConnector implements ViewService { optional = viewRepository.findPublicByDatabaseIdAndId(databaseId, id); } else { log.trace("principal is not null, find public view or mine"); - optional = viewRepository.findPublicOrMineByDatabaseIdAndId(databaseId, id, principal.getName()); + optional = viewRepository.findPublicOrMineByDatabaseIdAndId(databaseId, id, UserUtil.getId(principal)); } if (optional.isEmpty()) { log.error("Failed to find view with id {}", id); diff --git a/dbrepo-metadata-service/test/src/main/java/at/tuwien/test/BaseTest.java b/dbrepo-metadata-service/test/src/main/java/at/tuwien/test/BaseTest.java index fb6568c9a0..f6001aed8e 100644 --- a/dbrepo-metadata-service/test/src/main/java/at/tuwien/test/BaseTest.java +++ b/dbrepo-metadata-service/test/src/main/java/at/tuwien/test/BaseTest.java @@ -26,6 +26,9 @@ import at.tuwien.api.database.table.constraints.ConstraintsDto; import at.tuwien.api.database.table.constraints.foreignKey.ForeignKeyCreateDto; import at.tuwien.api.database.table.constraints.unique.UniqueDto; import at.tuwien.api.identifier.*; +import at.tuwien.api.keycloak.CredentialDto; +import at.tuwien.api.keycloak.CredentialTypeDto; +import at.tuwien.api.keycloak.UserCreateDto; import at.tuwien.api.maintenance.BannerMessageCreateDto; import at.tuwien.api.maintenance.BannerMessageTypeDto; import at.tuwien.api.maintenance.BannerMessageUpdateDto; @@ -49,6 +52,7 @@ import at.tuwien.entities.identifier.*; import at.tuwien.entities.maintenance.BannerMessage; import at.tuwien.entities.maintenance.BannerMessageType; import at.tuwien.entities.semantics.Ontology; +import at.tuwien.entities.user.User; import at.tuwien.querystore.Query; import at.tuwien.test.utils.ArrayUtil; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -235,6 +239,8 @@ public abstract class BaseTest { public final static String USER_1_TITLES_BEFORE = "Dr."; public final static String USER_1_TITLES_AFTER = "MSc BSc"; public final static Boolean USER_1_VERIFIED = false; + public final static Boolean USER_1_TOTP = false; + public final static Long USER_1_NOT_BEFORE = 0L; public final static Boolean USER_1_ENABLED = true; public final static Boolean USER_1_THEME_DARK = false; public final static Instant USER_1_CREATED = Instant.ofEpochSecond(1677399441) /* 2023-02-26 08:17:21 (UTC) */; @@ -259,6 +265,31 @@ public abstract class BaseTest { .mariadbPassword(USER_1_DATABASE_PASSWORD) .build(); + public final static CredentialDto USER_1_KEYCLOAK_CREDENTIAL_1 = CredentialDto.builder() + .type(CredentialTypeDto.PASSWORD) + .temporary(false) + .value(USER_1_PASSWORD) + .build(); + + public final static UserCreateDto USER_1_KEYCLOAK_SIGNUP_REQUEST = UserCreateDto.builder() + .username(USER_1_USERNAME) + .email(USER_1_EMAIL) + .enabled(USER_1_ENABLED) + .credentials(List.of(USER_1_KEYCLOAK_CREDENTIAL_1)) + .build(); + + public final static User USER_1 = User.builder() + .id(USER_1_ID) + .username(USER_1_USERNAME) + .email(USER_1_EMAIL) + .firstname(USER_1_FIRSTNAME) + .lastname(USER_1_LASTNAME) + .affiliation(USER_1_AFFILIATION) + .orcid(USER_1_ORCID) + .themeDark(USER_1_THEME_DARK) + .mariadbPassword(USER_1_DATABASE_PASSWORD) + .build(); + public final static UserDto USER_1_DTO = UserDto.builder() .id(USER_1_ID) .username(USER_1_USERNAME) @@ -269,6 +300,30 @@ public abstract class BaseTest { .attributes(USER_1_ATTRIBUTES_DTO) .build(); + public final static UserUpdateDto USER_1_UPDATE_DTO = UserUpdateDto.builder() + .firstname(USER_1_FIRSTNAME) + .lastname(USER_1_LASTNAME) + .affiliation(USER_1_AFFILIATION) + .orcid(USER_1_ORCID) + .build(); + + public final static UserThemeSetDto USER_1_THEME_SET_DTO = UserThemeSetDto.builder() + .themeDark(USER_1_THEME_DARK) + .build(); + + public final static UserPasswordDto USER_1_PASSWORD_DTO = UserPasswordDto.builder() + .password(USER_1_PASSWORD) + .build(); + + public final static at.tuwien.api.keycloak.UserDto USER_1_KEYCLOAK_DTO = at.tuwien.api.keycloak.UserDto.builder() + .id(USER_1_ID) + .username(USER_1_USERNAME) + .email(USER_1_EMAIL) + .emailVerified(USER_1_VERIFIED) + .notBefore(USER_1_NOT_BEFORE) + .totp(USER_1_TOTP) + .build(); + public final static UserBriefDto USER_1_BRIEF_DTO = UserBriefDto.builder() .id(USER_1_ID) .username(USER_1_USERNAME) @@ -310,12 +365,12 @@ public abstract class BaseTest { public final static String USER_2_FIRSTNAME = "Jane"; public final static String USER_2_LASTNAME = "Doe"; public final static String USER_2_AFFILIATION = "TU Wien"; - public final static String USER_2_ORCID = "0000000292726225"; - public final static String USER_2_ORCID_UNCOMPRESSED = "0000-0002-9272-6225"; - public final static String USER_2_ORCID_URL = "https://orcid.org/" + USER_2_ORCID_UNCOMPRESSED; + public final static String USER_2_ORCID_URL = "https://orcid.org/0000-0002-9272-6225"; public final static String USER_2_PASSWORD = "junit2"; public final static String USER_2_DATABASE_PASSWORD = "*9AA70A8B0EEFAFCB5BED5BDEF6EE264D5DA915AE" /* junit2 */; public final static Boolean USER_2_VERIFIED = true; + public final static Boolean USER_2_TOTP = false; + public final static Long USER_2_NOT_BEFORE = 0L; public final static Boolean USER_2_ENABLED = true; public final static Boolean USER_2_THEME_DARK = false; public final static Instant USER_2_CREATED = Instant.ofEpochSecond(1677399528) /* 2023-02-26 08:18:48 (UTC) */; @@ -324,11 +379,23 @@ public abstract class BaseTest { public final static UserAttributesDto USER_2_ATTRIBUTES_DTO = UserAttributesDto.builder() .themeDark(USER_2_THEME_DARK) - .orcid(USER_2_ORCID_UNCOMPRESSED) + .orcid(USER_2_ORCID_URL) .affiliation(USER_2_AFFILIATION) .mariadbPassword(USER_2_DATABASE_PASSWORD) .build(); + public final static User USER_2 = User.builder() + .id(USER_2_ID) + .username(USER_2_USERNAME) + .email(USER_2_EMAIL) + .firstname(USER_2_FIRSTNAME) + .lastname(USER_2_LASTNAME) + .affiliation(USER_2_AFFILIATION) + .orcid(USER_2_ORCID_URL) + .themeDark(USER_2_THEME_DARK) + .mariadbPassword(USER_2_DATABASE_PASSWORD) + .build(); + public final static UserDto USER_2_DTO = UserDto.builder() .id(USER_2_ID) .username(USER_2_USERNAME) @@ -360,6 +427,15 @@ public abstract class BaseTest { .authorities(AUTHORITY_DEFAULT_DEVELOPER_AUTHORITIES) .build(); + public final static at.tuwien.api.keycloak.UserDto USER_2_KEYCLOAK_DTO = at.tuwien.api.keycloak.UserDto.builder() + .id(USER_2_ID) + .username(USER_2_USERNAME) + .email(USER_2_EMAIL) + .emailVerified(USER_2_VERIFIED) + .notBefore(USER_2_NOT_BEFORE) + .totp(USER_2_TOTP) + .build(); + public final static at.tuwien.api.amqp.UserDetailsDto USER_2_DETAILS_DTO = at.tuwien.api.amqp.UserDetailsDto.builder() .name(USER_2_USERNAME) .tags(new String[]{}) @@ -373,11 +449,14 @@ public abstract class BaseTest { public final static String USER_3_FIRSTNAME = "System"; public final static String USER_3_LASTNAME = "System"; public final static String USER_3_AFFILIATION = "TU Wien"; + public final static String USER_3_ORCID_URL = null; public final static String USER_3_ORCID_UNCOMPRESSED = null; public final static String USER_3_EMAIL = "system@example.com"; public final static String USER_3_PASSWORD = "password"; public final static String USER_3_DATABASE_PASSWORD = "*D65FCA043964B63E849DD6334699ECB065905DA4" /* junit3 */; public final static Boolean USER_3_VERIFIED = true; + public final static Boolean USER_3_TOTP = false; + public final static Long USER_3_NOT_BEFORE = 0L; public final static Boolean USER_3_ENABLED = true; public final static Boolean USER_3_THEME_DARK = false; public final static Instant USER_3_CREATED = Instant.ofEpochSecond(1677399559) /* 2023-02-26 08:19:19 (UTC) */; @@ -390,6 +469,18 @@ public abstract class BaseTest { .mariadbPassword(USER_3_DATABASE_PASSWORD) .build(); + public final static User USER_3 = User.builder() + .id(USER_3_ID) + .username(USER_3_USERNAME) + .email(USER_3_EMAIL) + .firstname(USER_3_FIRSTNAME) + .lastname(USER_3_LASTNAME) + .affiliation(USER_3_AFFILIATION) + .orcid(USER_3_ORCID_URL) + .themeDark(USER_3_THEME_DARK) + .mariadbPassword(USER_3_DATABASE_PASSWORD) + .build(); + public final static UserDto USER_3_DTO = UserDto.builder() .id(USER_3_ID) .username(USER_3_USERNAME) @@ -407,6 +498,15 @@ public abstract class BaseTest { .authorities(AUTHORITY_DEFAULT_DATA_STEWARD_AUTHORITIES) .build(); + public final static at.tuwien.api.keycloak.UserDto USER_3_KEYCLOAK_DTO = at.tuwien.api.keycloak.UserDto.builder() + .id(USER_3_ID) + .username(USER_3_USERNAME) + .email(USER_3_EMAIL) + .emailVerified(USER_3_VERIFIED) + .notBefore(USER_3_NOT_BEFORE) + .totp(USER_3_TOTP) + .build(); + public final static Principal USER_3_PRINCIPAL = new UsernamePasswordAuthenticationToken(USER_3_DETAILS, USER_3_PASSWORD, USER_3_DETAILS.getAuthorities()); @@ -420,7 +520,7 @@ public abstract class BaseTest { public final static String USER_4_FIRSTNAME = "JUnit"; public final static String USER_4_LASTNAME = "4"; public final static String USER_4_AFFILIATION = "TU Wien"; - public final static String USER_4_ORCID_UNCOMPRESSED = null; + public final static String USER_4_ORCID_URL = null; public final static String USER_4_PASSWORD = "junit4"; public final static String USER_4_DATABASE_PASSWORD = "*C20EF5C6875857DEFA9BE6E9B62DD76AAAE51882" /* junit4 */; public final static String USER_4_EMAIL = "junit4@ossdip.at"; @@ -432,8 +532,20 @@ public abstract class BaseTest { public final static UserAttributesDto USER_4_ATTRIBUTES_DTO = UserAttributesDto.builder() .themeDark(USER_4_THEME_DARK) - .orcid(USER_4_ORCID_UNCOMPRESSED) + .orcid(USER_4_ORCID_URL) + .affiliation(USER_4_AFFILIATION) + .mariadbPassword(USER_4_DATABASE_PASSWORD) + .build(); + + public final static User USER_4 = User.builder() + .id(USER_4_ID) + .username(USER_4_USERNAME) + .email(USER_4_EMAIL) + .firstname(USER_4_FIRSTNAME) + .lastname(USER_4_LASTNAME) .affiliation(USER_4_AFFILIATION) + .orcid(USER_4_ORCID_URL) + .themeDark(USER_4_THEME_DARK) .mariadbPassword(USER_4_DATABASE_PASSWORD) .build(); -- GitLab