diff --git a/dbrepo-metadata-service/Dockerfile b/dbrepo-metadata-service/Dockerfile index 8712f6f9bd1ed4285f33f91b43f6fa35b87bbd1e..9311ca4e67f32650f288bae11b8b3c0660b59380 100644 --- a/dbrepo-metadata-service/Dockerfile +++ b/dbrepo-metadata-service/Dockerfile @@ -55,6 +55,8 @@ ENV SEARCH_USERNAME=admin ENV SHARED_FILESYSTEM=/tmp ENV USER_NETWORK=userdb ENV WEBSITE=http://localhost +ENV KEYCLOAK_ADMIN=fda +ENV KEYCLOAK_ADMIN_PASSWORD=fda WORKDIR /app diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialCreateDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialDto.java similarity index 92% rename from dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialCreateDto.java rename to dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialDto.java index 40e23c1426ca71dd181b95f1161223cc13cbc580..172b844e1bf4e6b3fd77ab1530a9a8578255d2c6 100644 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialCreateDto.java +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/CredentialDto.java @@ -12,7 +12,7 @@ import lombok.extern.jackson.Jacksonized; @AllArgsConstructor @Jacksonized @ToString -public class CredentialCreateDto { +public class CredentialDto { @NotNull private CredentialTypeDto type; diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/TokenDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/TokenDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ebb10a804f87e589503c51f97d78db93f9e27407 --- /dev/null +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/TokenDto.java @@ -0,0 +1,24 @@ +package at.tuwien.api.keycloak; + +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.NotNull; +import lombok.*; +import lombok.extern.jackson.Jacksonized; + +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Jacksonized +@ToString +public class TokenDto { + + @NotNull + @JsonProperty("access_token") + private String accessToken; + + @NotNull + private String scope; + +} 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 new file mode 100644 index 0000000000000000000000000000000000000000..fdf3ebd6079e0fa7b10f4ac1169343aa85621baa --- /dev/null +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateAttributesDto.java @@ -0,0 +1,19 @@ +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/UpdateCredentialsDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateCredentialsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c8bac04d455afa80bc061b7e391ed38e10f2edd1 --- /dev/null +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UpdateCredentialsDto.java @@ -0,0 +1,21 @@ +package at.tuwien.api.keycloak; + +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 UpdateCredentialsDto { + + @NotNull + private List<CredentialDto> credentials; + +} 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 new file mode 100644 index 0000000000000000000000000000000000000000..4fbc2df2e717b3acbd0a622e9fce20aabc891323 --- /dev/null +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesDto.java @@ -0,0 +1,35 @@ +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 4569d87d426b983d343df69493fecb9f419286ca..ebb83864def8d222e5870afc87bd8a7f6cbac84a 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 @@ -38,9 +38,9 @@ public class UserCreateDto { private String email; @NotNull - private UserAttributesCreateDto attributes; + private UserAttributesDto attributes; @NotNull - private List<CredentialCreateDto> credentials; + 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 new file mode 100644 index 0000000000000000000000000000000000000000..79ac3f4ebf89c99772f33471ca757f00b219b617 --- /dev/null +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserDto.java @@ -0,0 +1,60 @@ +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 +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Jacksonized +@ToString +public class UserDto { + + @NotNull + private UUID id; + + @NotNull + @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; + + @NotNull + @Schema(example = "false") + private Boolean totp; + + @NotNull + @JsonProperty("emailVerified") + @Schema(example = "false") + private Boolean emailVerified; + + @NotNull + @Schema(example = "jcarberry@brown.edu") + private String email; + + @NotNull + private UserAttributesDto attributes; + + @NotNull + @JsonProperty("notBefore") + @Schema(example = "0") + private Long notBefore; + +} diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributeDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributeDto.java deleted file mode 100644 index 2a46d764eebedaac8473772ec2b2d0e7b2bbb1b5..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributeDto.java +++ /dev/null @@ -1,36 +0,0 @@ -package at.tuwien.api.user; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.*; - -import jakarta.validation.constraints.NotNull; -import lombok.extern.jackson.Jacksonized; - -import java.util.UUID; - -@Getter -@Setter -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Jacksonized -@ToString -public class UserAttributeDto { - - @NotNull - @JsonIgnore - private UUID id; - - @NotNull - @JsonIgnore - @Schema(example = "1ffc7b0e-9aeb-4e8b-b8f1-68f3936155b4") - private UUID userId; - - @Schema(example = "theme_dark") - private String name; - - @Schema(example = "true") - private String value; - -} diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesCreateDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributesDto.java similarity index 73% rename from dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesCreateDto.java rename to dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributesDto.java index dda69549406200f5407dcb5a53088ef6c93169c4..794bdd12e8a47c08deb4ec9bc2c9907c8a75d449 100644 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/keycloak/UserAttributesCreateDto.java +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserAttributesDto.java @@ -1,4 +1,4 @@ -package at.tuwien.api.keycloak; +package at.tuwien.api.user; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; @@ -13,7 +13,7 @@ import lombok.extern.jackson.Jacksonized; @AllArgsConstructor @Jacksonized @ToString -public class UserAttributesCreateDto { +public class UserAttributesDto { @NotNull @JsonProperty("theme_dark") @@ -26,4 +26,8 @@ public class UserAttributesCreateDto { @Schema(example = "Brown University") private String affiliation; + @JsonProperty("mariadb_password") + @Schema(example = "*CC67043C7BCFF5EEA5566BD9B1F3C74FD9A5CF5D") + private String mariadbPassword; + } diff --git a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserDto.java b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserDto.java index 17bca6670c3e6a38ec216aaa58a1fb99319c422d..c5fc2b0797dbf255546694ba5d84f9909c963ce8 100644 --- a/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserDto.java +++ b/dbrepo-metadata-service/api/src/main/java/at/tuwien/api/user/UserDto.java @@ -55,8 +55,7 @@ public class UserDto { private String lastname; @NotNull - @org.springframework.data.annotation.Transient - private List<UserAttributeDto> attributes; + private UserAttributesDto attributes; @NotNull @org.springframework.data.annotation.Transient diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/Database.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/Database.java index d6700516f8fb22046d5432dc35eea4a27d9e25b0..d9e1b007f3b90731eea76fc503e12b7c3d141507 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/Database.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/Database.java @@ -3,7 +3,6 @@ package at.tuwien.entities.database; import at.tuwien.entities.container.Container; import at.tuwien.entities.database.table.Table; import at.tuwien.entities.identifier.Identifier; -import at.tuwien.entities.user.User; import jakarta.persistence.CascadeType; import jakarta.persistence.*; import jakarta.persistence.NamedQueries; @@ -33,8 +32,8 @@ import java.util.UUID; @NamedQueries({ @NamedQuery(name = "Database.findReadAccess", query = "select distinct d from Database d join DatabaseAccess a on a.hdbid = d.id and a.huserid = ?1"), @NamedQuery(name = "Database.findWriteAccess", query = "select distinct d from Database d join DatabaseAccess a on a.hdbid = d.id and a.huserid = ?1 where a.type = 'WRITE_OWN' or a.type = 'WRITE_ALL'"), - @NamedQuery(name = "Database.findConfigureAccess", query = "select distinct d from Database d where d.owner.id = ?1"), - @NamedQuery(name = "Database.findPublicOrMine", query = "select distinct d from Database d where d.id = ?1 and (d.isPublic = true or d.owner.id = ?2)"), + @NamedQuery(name = "Database.findConfigureAccess", query = "select distinct d from Database d where d.ownedBy = ?1"), + @NamedQuery(name = "Database.findPublicOrMine", query = "select distinct d from Database d where d.id = ?1 and (d.isPublic = true or d.ownedBy = ?2)"), @NamedQuery(name = "Database.findPublic", query = "select distinct d from Database d where d.isPublic = true and d.id = ?1"), }) @Document(indexName = "database") @@ -47,32 +46,17 @@ public class Database implements Serializable { @Column(updatable = false, nullable = false) private Long id; - @ToString.Exclude @JdbcTypeCode(java.sql.Types.VARCHAR) @Column(name = "created_by", columnDefinition = "VARCHAR(36)") private UUID createdBy; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) - @JoinColumns({ - @JoinColumn(name = "created_by", referencedColumnName = "ID", insertable = false, updatable = false) - }) - private User creator; - - @ToString.Exclude @JdbcTypeCode(java.sql.Types.VARCHAR) @Column(name = "owned_by", columnDefinition = "VARCHAR(36)") private UUID ownedBy; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) - @JoinColumns({ - @JoinColumn(name = "owned_by", referencedColumnName = "ID", insertable = false, updatable = false) - }) - private User owner; - @Column(nullable = false) private Long cid; - @ToString.Exclude @org.springframework.data.annotation.Transient @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumns({ @@ -92,17 +76,10 @@ public class Database implements Serializable { @Column(columnDefinition = "TEXT") private String description; - @ToString.Exclude @JdbcTypeCode(java.sql.Types.VARCHAR) @Column(name = "contact_person", columnDefinition = "VARCHAR(36)") private UUID contactPerson; - @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST) - @JoinColumns({ - @JoinColumn(name = "contact_person", referencedColumnName = "ID", updatable = false, insertable = false) - }) - private User contact; - @ToString.Exclude @org.springframework.data.annotation.Transient @OneToOne(fetch = FetchType.LAZY) diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/DatabaseAccess.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/DatabaseAccess.java index ca06be6c9c9233c801d75d8652428f46983e90f3..d139fc41cb980a6b2416bb0464829a88255b9b1b 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/DatabaseAccess.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/DatabaseAccess.java @@ -1,6 +1,5 @@ package at.tuwien.entities.database; -import at.tuwien.entities.user.User; import lombok.*; import org.hibernate.annotations.JdbcTypeCode; import org.springframework.data.annotation.CreatedDate; @@ -32,13 +31,6 @@ public class DatabaseAccess { @Column(name = "database_id", updatable = false) private Long hdbid; - @org.springframework.data.annotation.Transient - @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE}) - @JoinColumns({ - @JoinColumn(name = "user_id", referencedColumnName = "ID", updatable = false, insertable = false) - }) - private User user; - @Column(nullable = false, name = "access_type", columnDefinition = "enum('READ', 'WRITE_OWN', 'WRITE_ALL')") @Enumerated(EnumType.STRING) private AccessType type; diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/View.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/View.java index c6684755e241bf710c486143b55c6a7ac513ca94..569ae61ea7100f246f85da3ac3cabe5f8f4d589f 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/View.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/View.java @@ -2,7 +2,6 @@ package at.tuwien.entities.database; import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.entities.identifier.Identifier; -import at.tuwien.entities.user.User; import jakarta.persistence.*; import jakarta.persistence.CascadeType; import jakarta.persistence.NamedQueries; @@ -30,9 +29,9 @@ import java.util.UUID; @Table(name = "mdb_view") @NamedQueries({ @NamedQuery(name = "View.findAllPublicByDatabaseId", query = "select v from View v where v.database.id = ?1 and v.isPublic = true"), - @NamedQuery(name = "View.findAllPublicOrMineByDatabaseId", query = "select v from View v where v.database.id = ?1 and (v.isPublic = true or v.creator.username = ?2)"), + @NamedQuery(name = "View.findAllPublicOrMineByDatabaseId", query = "select v from View v where v.database.id = ?1 and (v.isPublic = true or v.createdBy = ?2)"), @NamedQuery(name = "View.findPublicByDatabaseIdAndId", query = "select v from View v where v.database.id = ?1 and v.id = ?2 and v.isPublic = true"), - @NamedQuery(name = "View.findPublicOrMineByDatabaseIdAndId", query = "select v from View v where v.database.id = ?1 and v.id = ?2 and (v.isPublic = true or v.creator.username = ?3)") + @NamedQuery(name = "View.findPublicOrMineByDatabaseIdAndId", query = "select v from View v where v.database.id = ?1 and v.id = ?2 and (v.isPublic = true or v.createdBy = ?3)") }) public class View { @@ -47,20 +46,11 @@ public class View { @Column(updatable = false, nullable = false) private Long vdbid; - @ToString.Exclude @JdbcTypeCode(java.sql.Types.VARCHAR) @Field(name = "created_by") @Column(name = "createdBy", nullable = false, columnDefinition = "VARCHAR(36)") private UUID createdBy; - @ToString.Exclude - @org.springframework.data.annotation.Transient - @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST}) - @JoinColumns({ - @JoinColumn(name = "createdBy", referencedColumnName = "ID", insertable = false, updatable = false) - }) - private User creator; - @Column(name = "vname", nullable = false) private String name; diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/table/Table.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/table/Table.java index 8e27294867e8b099b6650959a6ac59a7d6dc12e1..f3141e1ab1112c7baf4d8307d7cb097390ad66ef 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/table/Table.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/database/table/Table.java @@ -3,11 +3,11 @@ package at.tuwien.entities.database.table; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.entities.database.table.constraints.Constraints; -import at.tuwien.entities.user.User; import lombok.*; import lombok.extern.log4j.Log4j2; import net.sf.jsqlparser.statement.select.FromItem; import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.JdbcTypeCode; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.elasticsearch.annotations.Field; @@ -16,6 +16,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; import jakarta.persistence.*;; import java.time.Instant; import java.util.List; +import java.util.UUID; @Data @Entity @@ -39,19 +40,13 @@ public class Table { @Column(updatable = false, nullable = false) private Long tdbid; - @ToString.Exclude - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumns({ - @JoinColumn(name = "createdBy", referencedColumnName = "ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false) - }) - private User creator; + @JdbcTypeCode(java.sql.Types.VARCHAR) + @Column(name = "created_by", columnDefinition = "VARCHAR(36)") + private UUID createdBy; - @ToString.Exclude - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumns({ - @JoinColumn(name = "ownedBy", referencedColumnName = "ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false) - }) - private User owner; + @JdbcTypeCode(java.sql.Types.VARCHAR) + @Column(name = "owned_by", columnDefinition = "VARCHAR(36)") + private UUID ownedBy; @Column(name = "tname", nullable = false) private String name; @@ -97,11 +92,6 @@ public class Table { @Column(columnDefinition = "TIMESTAMP") private Instant lastModified; - @PreRemove - public void preRemove() { - this.creator = null; - } - /** * KEEP THIS FUNCTION HERE! IT WILL BREAK CODE! * Custom equality function implementation. diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/identifier/Identifier.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/identifier/Identifier.java index 3a268785e8af97181258a61e8749d1f2441c42d9..df3ee6fff9b9dc93d0b7526af5d8abe4f698aab5 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/identifier/Identifier.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/identifier/Identifier.java @@ -3,11 +3,11 @@ package at.tuwien.entities.identifier; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.LanguageType; import at.tuwien.entities.database.License; -import at.tuwien.entities.user.User; import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import lombok.*; import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.JdbcTypeCode; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.elasticsearch.annotations.Field; @@ -16,6 +16,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.io.Serializable; import java.time.Instant; import java.util.List; +import java.util.UUID; @Data @Entity @@ -140,11 +141,9 @@ public class Identifier implements Serializable { @Column private String doi; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumns({ - @JoinColumn(name = "createdBy", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false) - }) - private User creator; + @JdbcTypeCode(java.sql.Types.VARCHAR) + @Column(name = "createdBy", nullable = false, columnDefinition = "VARCHAR(36)") + private UUID createdBy; @CreatedDate @Column(nullable = false, updatable = false, columnDefinition = "TIMESTAMP") @@ -155,11 +154,6 @@ public class Identifier implements Serializable { @Column(columnDefinition = "TIMESTAMP") private Instant lastModified; - @PreRemove - private void preRemove() { - this.creator = null; - } - } diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/semantics/Ontology.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/semantics/Ontology.java index 88367f33c17adabf051f62bdbc6b8570db6612d9..708dd8f64b8dd48aa21e1255a874929fa9a72fa7 100644 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/semantics/Ontology.java +++ b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/semantics/Ontology.java @@ -1,6 +1,5 @@ package at.tuwien.entities.semantics; -import at.tuwien.entities.user.User; import jakarta.persistence.*; import lombok.*; import org.hibernate.annotations.GenericGenerator; @@ -44,17 +43,10 @@ public class Ontology { @Column private String sparqlEndpoint; - @ToString.Exclude @JdbcTypeCode(java.sql.Types.VARCHAR) @Column(name = "createdBy", nullable = false, columnDefinition = "VARCHAR(36)") private UUID createdBy; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) - @JoinColumns({ - @JoinColumn(name = "createdBy", referencedColumnName = "ID", insertable = false, updatable = false) - }) - private User creator; - @CreatedDate @Column(nullable = false, updatable = false, columnDefinition = "TIMESTAMP") private Instant created; diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Credential.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Credential.java deleted file mode 100644 index d5df3c33b996988dd9c603a900b87b64d1637b7a..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Credential.java +++ /dev/null @@ -1,54 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.*; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import jakarta.persistence.*;; -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "credential") -public class Credential { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID id; - - @Column(nullable = false) - private String type; - - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "user_id", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID userId; - - @Column(nullable = false) - private Long createdDate; - - @Column(nullable = false, columnDefinition = "LONGTEXT") - private String secretData; - - @Column(nullable = false, columnDefinition = "LONGTEXT") - private String credentialData; - - @Column(nullable = false) - private Integer priority; - - @ToString.Exclude - @org.springframework.data.annotation.Transient - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumns({ - @JoinColumn(name = "user_id", referencedColumnName = "id", insertable = false, updatable = false) - }) - private User user; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Group.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Group.java deleted file mode 100644 index 4aeec6f250f3945d98ab9d96896a2e0fee64c66b..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Group.java +++ /dev/null @@ -1,44 +0,0 @@ -package at.tuwien.entities.user; - -import jakarta.persistence.*; -import lombok.*; -import org.hibernate.annotations.Immutable; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.util.List; -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@Immutable -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "keycloak_group") -@NamedQueries({ - @NamedQuery(name = "Group.findDefault", query = "select g from Group g join Realm r on r.id = g.realmId and r.name = 'dbrepo' join RealmDefaultGroup d on d.realmId = r.id and d.groupId = g.id") -}) -public class Group { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID id; - - @Column(name = "NAME", nullable = false) - private String name; - - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "REALM_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID realmId; - - @ToString.Exclude - @ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups") - private List<User> users; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembership.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembership.java deleted file mode 100644 index cd51ea313c2eacf5ae0482d829aee7af955e12b5..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembership.java +++ /dev/null @@ -1,36 +0,0 @@ -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 -@IdClass(GroupMembershipKey.class) -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "user_group_membership", uniqueConstraints = { - @UniqueConstraint(columnNames = {"USER_ID", "GROUP_ID"}) -}) -public class GroupMembership { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "USER_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID userId; - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "GROUP_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID groupId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembershipKey.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembershipKey.java deleted file mode 100644 index cbcb493f8771d1582beae4cf456069026a788057..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/GroupMembershipKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.EqualsAndHashCode; - -import java.io.Serializable; -import java.util.UUID; - -@EqualsAndHashCode -public class GroupMembershipKey implements Serializable { - - private UUID userId; - - private UUID groupId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Realm.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Realm.java deleted file mode 100644 index 7933695c0a62d4a4fb74e41198f5a54d1924d5c2..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Realm.java +++ /dev/null @@ -1,41 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.*; -import org.hibernate.annotations.Immutable; -import org.hibernate.annotations.JdbcTypeCode; - -import jakarta.persistence.*; - -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@Immutable -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "realm") -@NamedQueries({ - @NamedQuery(name = "Realm.findAll", query = "select r from Realm r where r.name = 'dbrepo'") -}) -public class Realm { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID id; - - @Column(nullable = false) - private Boolean enabled; - - @Column(nullable = false) - private String name; - - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "DEFAULT_ROLE", columnDefinition = "VARCHAR(36)") - private UUID defaultRole; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroup.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroup.java deleted file mode 100644 index 71d86d056941d887745a49e8efd33404786c0ae3..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroup.java +++ /dev/null @@ -1,34 +0,0 @@ -package at.tuwien.entities.user; - -import jakarta.persistence.*; -import lombok.*; -import org.hibernate.annotations.Immutable; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@Immutable -@IdClass(RealmDefaultGroupKey.class) -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "realm_default_groups") -public class RealmDefaultGroup { - - @Id - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "GROUP_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID groupId; - - @Id - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "REALM_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID realmId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroupKey.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroupKey.java deleted file mode 100644 index 65d677285253bfc8f00d5a2038a39b245fae7da7..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RealmDefaultGroupKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.EqualsAndHashCode; - -import java.io.Serializable; -import java.util.UUID; - -@EqualsAndHashCode -public class RealmDefaultGroupKey implements Serializable { - - private UUID groupId; - - private UUID realmId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Role.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Role.java deleted file mode 100644 index aa8c7bf19e8753f016f22ed8f57b0aed526a5da8..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/Role.java +++ /dev/null @@ -1,39 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.*; -import org.hibernate.annotations.Immutable; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import jakarta.persistence.*; -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@Immutable -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "keycloak_role") -@NamedQueries({ - @NamedQuery(name = "Role.findDefault", query = "select r from Role r join Realm rr on rr.name = 'dbrepo' and rr.id = r.realmId and rr.defaultRole = r.id") -}) -public class Role { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID id; - - @Column(name = "NAME", nullable = false) - private String name; - - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "REALM_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID realmId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMapping.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMapping.java deleted file mode 100644 index 6e167d2e170bf947b15dcb4ad4461c84913a631b..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMapping.java +++ /dev/null @@ -1,36 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.*; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import jakarta.persistence.*;; -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@IdClass(RoleMappingKey.class) -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "user_role_mapping", uniqueConstraints = { - @UniqueConstraint(columnNames = {"USER_ID", "ROLE_ID"}) -}) -public class RoleMapping { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "USER_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID userId; - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "ROLE_ID", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID roleId; - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMappingKey.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMappingKey.java deleted file mode 100644 index ffe719a7106640cd38999a148bfcbb9902a39f3d..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/RoleMappingKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.EqualsAndHashCode; - -import java.io.Serializable; -import java.util.UUID; - -@EqualsAndHashCode -public class RoleMappingKey implements Serializable { - - private UUID userId; - - private UUID roleId; - -} 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 deleted file mode 100644 index 87112cbdaac51d88d65a5939ac1570a11133d535..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/User.java +++ /dev/null @@ -1,148 +0,0 @@ -package at.tuwien.entities.user; - -import at.tuwien.entities.database.Database; -import at.tuwien.entities.identifier.Identifier; -import jakarta.persistence.*; -import lombok.*; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import org.springframework.security.core.Authentication; - -import java.security.Principal; -import java.util.List; -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "user_entity", uniqueConstraints = { - @UniqueConstraint(columnNames = {"REALM_ID", "EMAIL"}), - @UniqueConstraint(columnNames = {"REALM_ID", "USERNAME"}) -}) -@NamedQueries({ - @NamedQuery(name = "User.findAll", query = "select u from User u join Realm r on r.name = 'dbrepo' and u.enabled = true"), - @NamedQuery(name = "User.findById", query = "select u from User u join Realm r on r.name = 'dbrepo' and u.id = ?1 and u.enabled = true"), - @NamedQuery(name = "User.findByUsername", query = "select u from User u join Realm r on r.name = 'dbrepo' and u.username = ?1 and u.enabled = true") -}) -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(name = "FIRST_NAME") - private String firstname; - - @Column(name = "LAST_NAME") - private String lastname; - - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Field(name = "realm_id") - @Column(name = "REALM_ID", columnDefinition = "VARCHAR(36)") - private UUID realmId; - - @Column - private String email; - - @Field(name = "email_verified") - @Column(nullable = false) - private Boolean emailVerified; - - @Column(nullable = false) - private Boolean enabled; - - @Field(name = "created_timestamp") - @Column - private Long createdTimestamp; - - @ToString.Exclude - private transient String databasePassword; - - @ToString.Exclude - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user") - private List<UserAttribute> attributes; - - @ToString.Exclude - @org.springframework.data.annotation.Transient - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user") - private List<Credential> credentials; - - @ToString.Exclude - @org.springframework.data.annotation.Transient - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "owner") - private List<Database> databases; - - @ToString.Exclude - @org.springframework.data.annotation.Transient - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "creator") - private List<Identifier> identifiers; - - @ToString.Exclude - @ManyToMany(fetch = FetchType.LAZY) - @JoinTable(name = "user_role_mapping", - joinColumns = { - @JoinColumn(name = "USER_ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false), - }, - inverseJoinColumns = { - @JoinColumn(name = "ROLE_ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false), - }) - private List<Role> roles; - - @ToString.Exclude - @ManyToMany(fetch = FetchType.LAZY) - @JoinTable(name = "user_group_membership", - joinColumns = { - @JoinColumn(name = "USER_ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false), - }, - inverseJoinColumns = { - @JoinColumn(name = "GROUP_ID", nullable = false, columnDefinition = "VARCHAR(36)", updatable = false), - }) - private List<Group> groups; - - @Transient - @ToString.Exclude - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "creator") - private List<at.tuwien.entities.database.table.Table> tables; - - /** - * Compares if the user instance equals with another instance by the principal. - * - * @param principal The user principal. - * @return True if the user are equal, false otherwise. - */ - public boolean equalsPrincipal(Principal principal) { - if (principal == null) { - return false; - } - return this.username.equals(principal.getName()); - } - - /** - * Compares the user principal and checks if a certain role is present. - * - * @param principal The user principal. - * @param role The role. - * @return True if the role is present, false otherwise. - */ - public static boolean hasRole(Principal principal, String role) { - if (principal == null || role == null) { - return false; - } - final Authentication authentication = (Authentication) principal; - return authentication.getAuthorities() - .stream() - .anyMatch(a -> a.getAuthority().equals(role)); - } - -} diff --git a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/UserAttribute.java b/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/UserAttribute.java deleted file mode 100644 index 1c140010f1d6953869174b8a96afc2d9a6eaad91..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/entities/src/main/java/at/tuwien/entities/user/UserAttribute.java +++ /dev/null @@ -1,47 +0,0 @@ -package at.tuwien.entities.user; - -import lombok.*; -import org.hibernate.annotations.JdbcTypeCode; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import jakarta.persistence.*; - -import java.util.UUID; - -@Data -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EntityListeners(AuditingEntityListener.class) -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@Table(name = "user_attribute") -public class UserAttribute { - - @Id - @EqualsAndHashCode.Include - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(nullable = false, columnDefinition = "VARCHAR(36)") - private UUID id; - - @ToString.Exclude - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column(name = "user_id", nullable = false, columnDefinition = "VARCHAR(36)") - private UUID userId; - - @Column(nullable = false) - private String name; - - @Column - private String value; - - @ToString.Exclude - @org.springframework.data.annotation.Transient - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumns({ - @JoinColumn(name = "user_id", referencedColumnName = "id", insertable = false, updatable = false) - }) - private User user; - -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/exception/KeycloakRemoteException.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/exception/KeycloakRemoteException.java new file mode 100644 index 0000000000000000000000000000000000000000..594d70340303f18a3504324d75a445d1457158de --- /dev/null +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/exception/KeycloakRemoteException.java @@ -0,0 +1,21 @@ +package at.tuwien.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.LOCKED) +public class KeycloakRemoteException extends Exception { + + public KeycloakRemoteException(String msg) { + super(msg); + } + + public KeycloakRemoteException(String msg, Throwable thr) { + super(msg, thr); + } + + public KeycloakRemoteException(Throwable thr) { + super(thr); + } + +} 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 af40d0c248db8eb93cae67548843e6e6c21891ae..69a0a0b3c3bdde933ddb5d863e0d90619b4e9469 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 @@ -1,13 +1,14 @@ package at.tuwien.mapper; +import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.database.*; import at.tuwien.api.user.UserDetailsDto; +import at.tuwien.api.user.UserDto; import at.tuwien.entities.container.image.ContainerImage; 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; @@ -22,6 +23,7 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.Normalizer; import java.util.Locale; +import java.util.UUID; import java.util.regex.Pattern; @Mapper(componentModel = "spring", uses = {ContainerMapper.class, UserMapper.class, ImageMapper.class/*, IdentifierMapper.class*/}, imports = {RandomStringUtils.class}) @@ -82,10 +84,11 @@ public interface DatabaseMapper { }) Database databaseCreateDtoToDatabase(DatabaseCreateDto data); - default PreparedStatement userToRawCreateUserQuery(Connection connection, User user) throws QueryMalformedException { + default PreparedStatement userToRawCreateUserQuery(Connection connection, UserDto data) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("CREATE USER IF NOT EXISTS `") - .append(user.getUsername()) + .append(data.getUsername()) .append("`@`%` IDENTIFIED BY PASSWORD '") + .append(data.getAttributes().getMariadbPassword()) .append("';"); log.trace("statement={}", statement); try { @@ -96,9 +99,9 @@ public interface DatabaseMapper { } } - default PreparedStatement userToRawDropUserQuery(Connection connection, User user) throws QueryMalformedException { + default PreparedStatement userToRawDropUserQuery(Connection connection, String username) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("DROP USER IF EXISTS `") - .append(user.getUsername()) + .append(username) .append("`@`%`;"); log.debug("raw drop user statement [{}]", statement); try { @@ -136,9 +139,9 @@ public interface DatabaseMapper { .build(); } - default PreparedStatement rawGrantCreatorAccessQuery(Connection connection, User user) throws QueryMalformedException { + default PreparedStatement rawGrantCreatorAccessQuery(Connection connection, String username) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("GRANT ALL PRIVILEGES ON *.* TO `") - .append(user.getUsername()) + .append(username) .append("`@`%`;"); log.trace("statement={}", statement); try { @@ -149,9 +152,9 @@ public interface DatabaseMapper { } } - default PreparedStatement rawRevokeUserAccessQuery(Connection connection, User user) throws QueryMalformedException { + default PreparedStatement rawRevokeUserAccessQuery(Connection connection, String username) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("REVOKE ALL PRIVILEGES ON *.* FROM `") - .append(user.getUsername()) + .append(username) .append("`@`%`;"); log.debug("raw revoke all privileges statement [{}]", statement); try { @@ -186,10 +189,10 @@ public interface DatabaseMapper { } } - default PreparedStatement rawGrantUserProcedure(Connection connection, User user) + default PreparedStatement rawGrantUserProcedure(Connection connection, String username) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("GRANT EXECUTE ON PROCEDURE `store_query` TO `") - .append(user.getUsername()) + .append(username) .append("`@`%`;"); log.debug("raw grant execute user procedure privileges statement [{}]", statement); try { @@ -200,10 +203,10 @@ public interface DatabaseMapper { } } - default PreparedStatement rawGrantDefaultReadonlyAccessQuery(Connection connection, User user) + default PreparedStatement rawGrantDefaultReadonlyAccessQuery(Connection connection, String username) throws QueryMalformedException { final StringBuilder statement = new StringBuilder("GRANT SELECT ON *.* TO `") - .append(user.getUsername()) + .append(username) .append("`@`%`;"); log.trace("statement={}", statement); try { @@ -245,13 +248,13 @@ public interface DatabaseMapper { return principal; } - default DatabaseAccess defaultCreatorAccess(Database database, User user) { + default DatabaseAccess defaultCreatorAccess(Database database, UUID userId) { final DatabaseAccess access = DatabaseAccess.builder() .hdbid(database.getId()) - .huserid(user.getId()) + .huserid(userId) .type(AccessType.WRITE_ALL) .build(); - log.debug("give default owner access to database with id {} to user with username {}", database.getId(), user.getUsername()); + log.debug("give default owner access to database with id {} to user with id {}", database.getId(), userId); return access; } @@ -261,18 +264,18 @@ public interface DatabaseMapper { DatabaseAccessDto databaseAccessToDatabaseAccessDto(DatabaseAccess data); - default DatabaseAccess databaseGiveAccessDtoToDatabaseAccess(Database database, User user, + default DatabaseAccess databaseGiveAccessDtoToDatabaseAccess(Database database, UUID id, DatabaseGiveAccessDto data) { final DatabaseAccess access = DatabaseAccess.builder() .hdbid(database.getId()) - .huserid(user.getId()) + .huserid(id) .type(accessTypeDtoToAccessType(data.getType())) .build(); log.debug("mapped database access {} to database access {}", data, access); return access; } - default DatabaseAccess databaseModifyAccessDtoToDatabaseAccess(Database database, User user, + default DatabaseAccess databaseModifyAccessDtoToDatabaseAccess(Database database, UserDto user, DatabaseModifyAccessDto data) { final DatabaseAccess access = DatabaseAccess.builder() .hdbid(database.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 e65a3d9e01166532b5951b40f5ef04e016bde9e4..07ed149a5aee6f2e8fc673fd044c0aca2f4e52ae 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 @@ -1,7 +1,7 @@ package at.tuwien.mapper; import at.tuwien.api.database.query.ExecuteStatementDto; -import at.tuwien.entities.user.User; +import at.tuwien.api.user.UserDto; import at.tuwien.exception.QueryStoreException; import at.tuwien.exception.TableMalformedException; import at.tuwien.querystore.Query; @@ -21,7 +21,7 @@ public interface StoreMapper { DateTimeFormatter mariaDbFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]") .withZone(ZoneId.of("UTC")); - default CallableStatement queryStoreRawInsertQuery(Connection connection, User user, ExecuteStatementDto data) + default CallableStatement queryStoreRawInsertQuery(Connection connection, UserDto 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 9ed605bf973130ecf80ff5132cf283a4531d96bc..61595eb78bff321560ae44b4a92d608f629dc181 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 @@ -2,23 +2,20 @@ package at.tuwien.mapper; import at.tuwien.api.auth.SignupRequestDto; import at.tuwien.api.auth.TokenIntrospectDto; -import at.tuwien.api.user.GrantedAuthorityDto; -import at.tuwien.api.user.UserBriefDto; -import at.tuwien.api.user.UserDetailsDto; +import at.tuwien.api.keycloak.*; +import at.tuwien.api.user.*; +import at.tuwien.api.user.UserAttributesDto; import at.tuwien.api.user.UserDto; -import at.tuwien.entities.user.Group; -import at.tuwien.entities.user.GroupMembership; -import at.tuwien.entities.user.User; -import at.tuwien.entities.user.UserAttribute; +import org.apache.commons.codec.digest.DigestUtils; 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.Optional; -import java.util.UUID; +import java.util.List; import java.util.stream.Collectors; @Mapper(componentModel = "spring") @@ -37,34 +34,76 @@ public interface UserMapper { return authority; } - /* keep */ @Mappings({ - @Mapping(target = "id", expression = "java(data.getId().toString())") + @Mapping(target = "attributes", expression = "java(data)") }) - UserDetailsDto userDtoToUserDetailsDto(UserDto data); + UpdateAttributesDto userAttributesDtoToUpdateAttributesDto(at.tuwien.api.keycloak.UserAttributesDto data); + + default UpdateCredentialsDto passwordToUpdateCredentialsDto(String password) { + return UpdateCredentialsDto.builder() + .credentials(List.of(CredentialDto.builder() + .temporary(false) + .type(CredentialTypeDto.PASSWORD) + .value(password) + .build())) + .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()) + .email(data.getEmail()) + .credentials(List.of(CredentialDto.builder() + .type(CredentialTypeDto.PASSWORD) + .temporary(false) + .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 */ - @Mappings({ - @Mapping(target = "orcid", expression = "java(userToOrcid(data))") - }) - UserBriefDto userToUserBriefDto(User data); + UserBriefDto keycloakUserDtoToUserBriefDto(at.tuwien.api.keycloak.UserDto data); - UserBriefDto userDtoToUserBriefDto(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 = "orcid", expression = "java(userToOrcid(data))") + @Mapping(target = "id", expression = "java(data.getId().toString())") }) - UserDto userToUserDto(User data); + UserDetailsDto userDtoToUserDetailsDto(UserDto data); - /* keep */ - default String userToOrcid(User data) { - if (data.getAttributes() == null) { - return null; - } - final Optional<UserAttribute> orcid = data.getAttributes().stream().filter(a -> a.getName().equals("orcid")).findFirst(); - return orcid.map(UserAttribute::getValue).orElse(null); - } + UserBriefDto userDtoToUserBriefDto(UserDto data); default UserDetailsDto tokenIntrospectDtoToUserDetailsDto(TokenIntrospectDto data) { return UserDetailsDto.builder() @@ -76,22 +115,4 @@ public interface UserMapper { .build(); } - User signupRequestDtoToUser(SignupRequestDto data); - - default UserAttribute tripleToUserAttribute(UUID userId, String name, String value) { - return UserAttribute.builder() - .id(UUID.randomUUID()) - .userId(userId) - .name(name) - .value(value) - .build(); - } - - default GroupMembership userGroupToGroupMembership(User user, Group group) { - return GroupMembership.builder() - .userId(user.getId()) - .groupId(group.getId()) - .build(); - } - } diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/CredentialRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/CredentialRepository.java deleted file mode 100644 index e9e9fdb8db0d291d79e478ea6f0590ab21987b78..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/CredentialRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.Credential; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -@Repository -public interface CredentialRepository extends JpaRepository<Credential, UUID> { - -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupMembershipRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupMembershipRepository.java deleted file mode 100644 index 2c6accb9499246b52cbd6429b9eba67d26c13db8..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupMembershipRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.GroupMembership; -import at.tuwien.entities.user.GroupMembershipKey; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface GroupMembershipRepository extends JpaRepository<GroupMembership, GroupMembershipKey> { -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupRepository.java deleted file mode 100644 index 5a56e16f92ec01f402e028b16038a813c56d489a..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/GroupRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.Group; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.UUID; - -@Repository -public interface GroupRepository extends JpaRepository<Group, UUID> { - - List<Group> findDefault(); -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RealmRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RealmRepository.java deleted file mode 100644 index 56d2152fa027b32d43ad2b966db167ba8ddae253..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RealmRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.Realm; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; -import java.util.UUID; - -@Repository -public interface RealmRepository extends JpaRepository<Realm, UUID> { - - Optional<Realm> findByName(String name); - -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleMappingRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleMappingRepository.java deleted file mode 100644 index 345f96ff8afbf673b1153bd46d1b7310817aa936..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleMappingRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.RoleMapping; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -@Repository -public interface RoleMappingRepository extends JpaRepository<RoleMapping, UUID> { -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleRepository.java deleted file mode 100644 index f712472f771f020b03d09bde4dba3a79fa457f78..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/RoleRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.Role; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; -import java.util.UUID; - -@Repository -public interface RoleRepository extends JpaRepository<Role, UUID> { - - Optional<Role> findByName(String name); - - Optional<Role> findDefault(); -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserAttributeRepository.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserAttributeRepository.java deleted file mode 100644 index 6d96fc3584c79bfddae43faa467e0ab543e90780..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserAttributeRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.repository.mdb; - -import at.tuwien.entities.user.UserAttribute; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; -import java.util.UUID; - -@Repository -public interface UserAttributeRepository extends JpaRepository<UserAttribute, UUID> { - - Optional<UserAttribute> findByUserIdAndName(UUID userId, String name); - -} 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 deleted file mode 100644 index f9ca9c65ca30a0a14564770188d48a76427bf9de..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/repository/mdb/UserRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -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> { - - /** - * Finds a user by username. - * - * @param username The username. - * @return Optional user that matches this filter. - */ - Optional<User> findByUsername(String username); - - Optional<User> findByEmail(String email); - -} diff --git a/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/utils/UserUtil.java b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/utils/UserUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..433dcded1c69ee32222718bbd6c9bb860c675d1a --- /dev/null +++ b/dbrepo-metadata-service/repositories/src/main/java/at/tuwien/utils/UserUtil.java @@ -0,0 +1,30 @@ +package at.tuwien.utils; + +import at.tuwien.api.user.UserDetailsDto; +import org.springframework.security.core.Authentication; + +import java.security.Principal; +import java.util.UUID; + +public class UserUtil { + + public static boolean hasRole(Principal principal, String role) { + if (principal == null || role == null) { + return false; + } + final Authentication authentication = (Authentication) principal; + return authentication.getAuthorities() + .stream() + .anyMatch(a -> a.getAuthority().equals(role)); + } + + public static UUID getId(Principal principal) { + if (principal == null) { + return null; + } + final Authentication authentication = (Authentication) principal; + final UserDetailsDto user = (UserDetailsDto) authentication.getDetails(); + return UUID.fromString(user.getId()); + } + +} diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/AccessEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/AccessEndpoint.java index de3e7deb51f5044482c25f60caf3dea5fcfad341..8ff3422edde26b02da9f04ae9a947999a599185a 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/AccessEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/AccessEndpoint.java @@ -25,6 +25,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.security.Principal; +import java.util.UUID; @Log4j2 @RestController @@ -69,7 +70,7 @@ public class AccessEndpoint { @Valid @RequestBody DatabaseGiveAccessDto accessDto, @NotNull Principal principal) throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, - DatabaseMalformedException { + DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint give access to database, databaseId={}, accessDto={}, principal={}", databaseId, accessDto, principal); try { accessService.find(databaseId, accessDto.getUsername()); @@ -83,7 +84,7 @@ public class AccessEndpoint { .build(); } - @PutMapping("/{username}") + @PutMapping("/{userId}") @Transactional @PreAuthorize("hasAuthority('update-database-access')") @Operation(summary = "Modify access to some database", security = @SecurityRequirement(name = "bearerAuth")) @@ -108,14 +109,14 @@ public class AccessEndpoint { schema = @Schema(implementation = ApiErrorDto.class))}), }) public ResponseEntity<?> update(@NotBlank @PathVariable("id") Long databaseId, - @NotBlank @PathVariable("username") String username, + @NotBlank @PathVariable("userId") UUID userId, @Valid @RequestBody DatabaseModifyAccessDto accessDto, @NotNull Principal principal) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, NotAllowedException, - QueryMalformedException, DatabaseMalformedException { - log.debug("endpoint modify access to database, databaseId={}, username={}, accessDto={}, principal={}", databaseId, username, accessDto, principal); - accessService.find(databaseId, username); - accessService.update(databaseId, username, accessDto); + throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, + DatabaseMalformedException, AccessDeniedException, KeycloakRemoteException { + log.debug("endpoint modify access to database, databaseId={}, userId={}, accessDto={}, principal={}", databaseId, userId, accessDto, principal); + accessService.find(databaseId, userId); + accessService.update(databaseId, userId, accessDto); return ResponseEntity.accepted() .build(); } @@ -142,8 +143,7 @@ public class AccessEndpoint { schema = @Schema(implementation = ApiErrorDto.class))}), }) public ResponseEntity<DatabaseAccessDto> find(@NotBlank @PathVariable("id") Long databaseId, - @NotNull Principal principal) throws NotAllowedException, - NotAllowedException { + @NotNull Principal principal) throws NotAllowedException { log.debug("endpoint check access to database, databaseId={}, principal={}", databaseId, principal); final DatabaseAccess access = accessService.find(databaseId, principal.getName()); final DatabaseAccessDto dto = databaseMapper.databaseAccessToDatabaseAccessDto(access); @@ -151,7 +151,7 @@ public class AccessEndpoint { return ResponseEntity.ok(dto); } - @DeleteMapping("/{username}") + @DeleteMapping("/{userId}") @Transactional @PreAuthorize("hasAuthority('delete-database-access')") @Operation(summary = "Revoke access to some database", security = @SecurityRequirement(name = "bearerAuth")) @@ -181,13 +181,13 @@ public class AccessEndpoint { schema = @Schema(implementation = ApiErrorDto.class))}), }) public ResponseEntity<?> revoke(@NotBlank @PathVariable("id") Long databaseId, - @NotBlank @PathVariable("username") String username, + @NotBlank @PathVariable("userId") UUID userId, @NotNull Principal principal) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, NotAllowedException, - QueryMalformedException, DatabaseMalformedException { - log.debug("endpoint revoke access to database, databaseId={}, username={}, principal={}", databaseId, username, principal); - accessService.find(databaseId, username); - accessService.delete(databaseId, username); + throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, + DatabaseMalformedException, AccessDeniedException, KeycloakRemoteException { + log.debug("endpoint revoke access to database, databaseId={}, userId={}, principal={}", databaseId, userId, principal); + accessService.find(databaseId, userId); + accessService.delete(databaseId, userId); return ResponseEntity.accepted() .build(); } 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 fab166851caf7250c6fda00330bf916ba2cc52b5..dd2a6692b2f9f317a048b29a26c2f774ebd3b068 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 @@ -2,14 +2,14 @@ package at.tuwien.endpoints; import at.tuwien.api.database.*; 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; import at.tuwien.service.*; -import at.tuwien.service.impl.MariaDbServiceImpl; +import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -140,15 +140,15 @@ public class DatabaseEndpoint { AmqpException, ContainerConnectionException, UserNotFoundException, DatabaseNotFoundException, DatabaseNameExistsException, DatabaseConnectionException, QueryMalformedException, NotAllowedException, BrokerVirtualHostCreationException, QueryStoreException, - BrokerVirtualHostGrantException { + BrokerVirtualHostGrantException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint create database, createDto={}, principal={}", createDto, principal); - final User user = userService.findByUsername(principal.getName()); + final UserDto user = userService.findByUsername(principal.getName()); final Database database = databaseService.create(createDto, principal); - messageQueueService.createUser(user); + messageQueueService.createUser(user.getUsername()); messageQueueService.createExchange(database, principal); queryStoreService.create(database.getId(), principal); - databaseAccessRepository.save(databaseMapper.defaultCreatorAccess(database, user)); + databaseAccessRepository.save(databaseMapper.defaultCreatorAccess(database, UserUtil.getId(principal))); messageQueueService.updatePermissions(user); final DatabaseBriefDto dto = databaseMapper.databaseToDatabaseBriefDto(database); log.trace("create database resulted in database {}", dto); @@ -180,12 +180,12 @@ public class DatabaseEndpoint { }) public ResponseEntity<DatabaseDto> visibility(@NotNull @PathVariable Long id, @Valid @RequestBody DatabaseModifyVisibilityDto data, - @NotNull Principal principal) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException { + @NotNull Principal principal) throws DatabaseNotFoundException, + UserNotFoundException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint update database, id={}, data={}, principal={}", id, data, principal); final Database database = databaseService.findById(id); - final User user = userService.findByUsername(principal.getName()); - if (!database.getOwner().equals(user)) { + final UserDto 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")); } @@ -219,12 +219,12 @@ public class DatabaseEndpoint { }) public ResponseEntity<DatabaseDto> transfer(@NotNull @PathVariable Long id, @Valid @RequestBody DatabaseTransferDto transferDto, - @NotNull Principal principal) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException { + @NotNull Principal principal) throws DatabaseNotFoundException, + UserNotFoundException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint update database, id={}, transferDto={}, principal={}", id, transferDto, principal); final Database database = databaseService.findById(id); - final User user = userService.findByUsername(principal.getName()); - if (!database.getOwner().equals(user)) { + final UserDto 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")); } @@ -260,7 +260,7 @@ public class DatabaseEndpoint { log.debug("endpoint find database, id={}", id); final Database database = databaseService.findById(id); final DatabaseDto dto = databaseMapper.databaseToDatabaseDto(database); - if (principal != null && database.getOwner().equalsPrincipal(principal)) { + if (principal != null && database.getOwnedBy().equals(UserUtil.getId(principal))) { /* only owner sees the access rights */ // TODO improve this by proper mapping final List<DatabaseAccess> accesses = accessService.list(id); dto.setAccesses(accesses.stream() @@ -321,11 +321,11 @@ public class DatabaseEndpoint { public ResponseEntity<?> delete(@NotNull @PathVariable Long id, Principal principal) throws DatabaseNotFoundException, ImageNotSupportedException, DatabaseMalformedException, AmqpException, QueryMalformedException, UserNotFoundException, BrokerVirtualHostGrantException, - DatabaseConnectionException { + DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint delete database, id={}, principal={}", id, principal); final Database database = databaseService.findById(id); - final User user = userService.findByUsername(principal.getName()); + final UserDto 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/ExportEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ExportEndpoint.java index 51376dbb75b6c9689d569240cdc80aae88fb563f..c0a55f399fb627d132f14a51e82cbf3e74166db6 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ExportEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ExportEndpoint.java @@ -2,10 +2,10 @@ package at.tuwien.endpoints; import at.tuwien.ExportResource; import at.tuwien.entities.database.Database; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; +import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; @@ -45,8 +45,8 @@ public class ExportEndpoint { @RequestParam(required = false) Instant timestamp, Principal principal) throws TableNotFoundException, DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, PaginationException, ContainerNotFoundException, - FileStorageException, QueryMalformedException, UserNotFoundException, NotAllowedException { + DatabaseNotFoundException, ImageNotSupportedException, PaginationException, FileStorageException, + QueryMalformedException, UserNotFoundException, NotAllowedException { log.debug("endpoint export table, id={}, tableId={}, timestamp={}, principal={}", databaseId, tableId, timestamp, principal); final Database database = databaseService.find(databaseId); if (!database.getIsPublic()) { @@ -54,7 +54,7 @@ public class ExportEndpoint { log.error("Failed to export private table: principal is null"); throw new NotAllowedException("Failed to export private table: principal is null"); } - if (!User.hasRole(principal, "export-table-data")) { + if (!UserUtil.hasRole(principal, "export-table-data")) { log.error("Failed to export private table: role missing"); throw new NotAllowedException("Failed to export private table: role missing"); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/IdentifierEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/IdentifierEndpoint.java index 10fa31a73a3b14468a390b554492599fdb630f75..a2dcf4b69864f17940174959ee74f78911c0b99d 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/IdentifierEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/IdentifierEndpoint.java @@ -6,13 +6,13 @@ import at.tuwien.api.identifier.IdentifierSaveDto; import at.tuwien.api.identifier.IdentifierTypeDto; import at.tuwien.api.user.external.ExternalMetadataDto; import at.tuwien.entities.identifier.Identifier; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.IdentifierMapper; import at.tuwien.service.AccessService; import at.tuwien.service.IdentifierService; import at.tuwien.service.MetadataService; import at.tuwien.service.UserService; +import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -140,11 +140,10 @@ public class IdentifierEndpoint { log.error("Identifier of type view must not have a qid present"); throw new IdentifierRequestException("Identifier of type database must not have a qid present"); } - final User user = userService.findByUsername(principal.getName()); try { - accessService.find(data.getDatabaseId(), user.getId()); + accessService.find(data.getDatabaseId(), UserUtil.getId(principal)); } catch (AccessDeniedException e) { - if (!User.hasRole(principal, "create-foreign-identifier")) { + if (!UserUtil.hasRole(principal, "create-foreign-identifier")) { log.error("Failed to create identifier: insufficient access"); throw new NotAllowedException("Failed to create identifier: insufficient access"); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/OntologyEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/OntologyEndpoint.java index 6c6edbaee4afa8bd665b05b6d19aa8c8295d2f2f..d9efb708485110a03d88a7851d8b56709fbd42e1 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/OntologyEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/OntologyEndpoint.java @@ -103,7 +103,8 @@ public class OntologyEndpoint { schema = @Schema(implementation = ApiErrorDto.class))}), }) public ResponseEntity<OntologyDto> create(@NotNull @Valid @RequestBody OntologyCreateDto data, - @NotNull Principal principal) throws UserNotFoundException { + @NotNull Principal principal) throws UserNotFoundException, + KeycloakRemoteException, AccessDeniedException { log.debug("endpoint create ontology, data={}, principal={}", data, principal); final OntologyDto dto = ontologyMapper.ontologyToOntologyDto(ontologyService.create(data, principal)); log.trace("create ontology resulted in dto {}", dto); diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/PersistenceEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/PersistenceEndpoint.java index 337394c48c115b2eb857e632e73a05d5145ddf16..48fd1c4f380f08219425d06967df0b280572f1c8 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/PersistenceEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/PersistenceEndpoint.java @@ -6,12 +6,11 @@ import at.tuwien.api.identifier.IdentifierDto; import at.tuwien.api.identifier.IdentifierSaveDto; import at.tuwien.config.EndpointConfig; import at.tuwien.entities.identifier.Identifier; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.IdentifierMapper; import at.tuwien.service.AccessService; import at.tuwien.service.IdentifierService; -import at.tuwien.service.UserService; +import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; @@ -41,16 +40,14 @@ import java.util.regex.Pattern; @RequestMapping("/api/pid") public class PersistenceEndpoint { - private final UserService userService; private final AccessService accessService; private final EndpointConfig endpointConfig; private final IdentifierMapper identifierMapper; private final IdentifierService identifierService; @Autowired - public PersistenceEndpoint(UserService userService, AccessService accessService, EndpointConfig endpointConfig, + public PersistenceEndpoint(AccessService accessService, EndpointConfig endpointConfig, IdentifierMapper identifierMapper, IdentifierService identifierService) { - this.userService = userService; this.accessService = accessService; this.endpointConfig = endpointConfig; this.identifierMapper = identifierMapper; @@ -192,11 +189,10 @@ public class PersistenceEndpoint { DatabaseConnectionException, ImageNotSupportedException { log.debug("endpoint update identifier, id={}, data={}", id, data); final Identifier identifier = identifierService.find(id); - final User user = userService.findByUsername(principal.getName()); try { - accessService.find(identifier.getDatabase().getId(), user.getId()); + accessService.find(identifier.getDatabase().getId(), UserUtil.getId(principal)); } catch (AccessDeniedException e) { - if (!User.hasRole(principal, "modify-identifier-metadata")) { + if (!UserUtil.hasRole(principal, "modify-identifier-metadata")) { log.error("Failed to update identifier: insufficient access"); throw new NotAllowedException("Failed to update identifier: insufficient access"); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/QueryEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/QueryEndpoint.java index 119412473e9c642868c91afa2eeb19dfac9de726..53ccafd6f97fa567f2beeba042b582af77c1b148 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/QueryEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/QueryEndpoint.java @@ -5,13 +5,13 @@ import at.tuwien.SortType; import at.tuwien.api.database.query.ExecuteStatementDto; import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.entities.database.Database; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.querystore.Query; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; import at.tuwien.service.StoreService; +import at.tuwien.utils.UserUtil; import at.tuwien.validation.EndpointValidator; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; @@ -36,18 +36,16 @@ public class QueryEndpoint { private final QueryService queryService; private final StoreService storeService; - private final AccessService accessService; private final DatabaseService databaseService; private final EndpointValidator endpointValidator; @Autowired - public QueryEndpoint(QueryService queryService, StoreService storeService, AccessService accessService, - DatabaseService databaseService, EndpointValidator endpointValidator) { - this.accessService = accessService; - this.databaseService = databaseService; - this.endpointValidator = endpointValidator; + public QueryEndpoint(QueryService queryService, StoreService storeService, DatabaseService databaseService, + EndpointValidator endpointValidator) { this.queryService = queryService; this.storeService = storeService; + this.databaseService = databaseService; + this.endpointValidator = endpointValidator; } @PostMapping @@ -64,7 +62,7 @@ public class QueryEndpoint { @RequestParam(required = false) String sortColumn) throws DatabaseNotFoundException, ImageNotSupportedException, QueryStoreException, QueryMalformedException, ColumnParseException, UserNotFoundException, TableMalformedException, DatabaseConnectionException, - SortException, PaginationException, NotAllowedException { + SortException, PaginationException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint execute query, databaseId={}, data={}, page={}, size={}, principal={}, sortDirection={}, sortColumn={}", databaseId, data, page, size, principal, sortDirection, sortColumn); /* check */ @@ -151,7 +149,7 @@ public class QueryEndpoint { log.error("Failed to export private query: principal is null"); throw new NotAllowedException("Failed to export private query: principal is null"); } - if (!User.hasRole(principal, "export-query-data")) { + if (!UserUtil.hasRole(principal, "export-query-data")) { log.error("Failed to export private query: role missing"); throw new NotAllowedException("Failed to export private query: role missing"); } 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 f638a95f4ab8aeb5216a64a23831df7f681419fa..9f43e72caedb712835439ae17d255fded6525f27 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,8 +5,8 @@ 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.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.IdentifierMapper; import at.tuwien.mapper.QueryMapper; @@ -176,7 +176,7 @@ public class StoreEndpoint { Principal principal) throws DatabaseNotFoundException, ImageNotSupportedException, QueryStoreException, QueryNotFoundException, UserNotFoundException, NotAllowedException, - DatabaseConnectionException { + DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint find query, databaseId={}, queryId={}, principal={}", databaseId, queryId, principal); /* check */ @@ -184,8 +184,7 @@ public class StoreEndpoint { /* find */ final Query query = storeService.findOne(databaseId, queryId, principal); final QueryDto dto = queryMapper.queryToQueryDto(query); - final User creator = userService.findByUsername(query.getCreatedBy()); - dto.setCreator(userMapper.userToUserDto(creator)); + dto.setCreator(userService.findByUsername(query.getCreatedBy())); final List<Identifier> identifiers = identifierService.findByDatabaseIdAndQueryId(databaseId, queryId); if (!identifiers.isEmpty()) { dto.setIdentifier(identifierMapper.identifierToIdentifierDto(identifiers.get(0))); @@ -237,7 +236,7 @@ public class StoreEndpoint { @NotNull Principal principal) throws QueryStoreException, DatabaseNotFoundException, ImageNotSupportedException, DatabaseConnectionException, UserNotFoundException, QueryNotFoundException, - QueryAlreadyPersistedException, NotAllowedException { + QueryAlreadyPersistedException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint persist query, container, databaseId={}, queryId={}, principal={}", databaseId, queryId, principal); /* check */ @@ -252,8 +251,7 @@ public class StoreEndpoint { /* persist */ final Query query = storeService.persist(databaseId, queryId, data); final QueryDto dto = queryMapper.queryToQueryDto(query); - final User creator = userService.findByUsername(query.getCreatedBy()); - dto.setCreator(userMapper.userToUserDto(creator)); + dto.setCreator(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/TableColumnEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableColumnEndpoint.java index 45c13dd6abc73565a47a1cb041822d7daa2e109a..147dec6eb3bf33ae4ff373b0b304df86685a564b 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableColumnEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableColumnEndpoint.java @@ -4,10 +4,10 @@ import at.tuwien.api.database.table.columns.ColumnDto; import at.tuwien.api.database.table.columns.concepts.ColumnSemanticsUpdateDto; import at.tuwien.api.error.ApiErrorDto; import at.tuwien.entities.database.table.columns.TableColumn; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.TableMapper; import at.tuwien.service.TableService; +import at.tuwien.utils.UserUtil; import at.tuwien.validation.EndpointValidator; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; @@ -86,7 +86,7 @@ public class TableColumnEndpoint { ContainerNotFoundException, NotAllowedException, SemanticEntityPersistException, SemanticEntityNotFoundException, QueryMalformedException { log.debug("endpoint update table, id={}, tableId={}, principal={}", id, tableId, principal); - if (!User.hasRole(principal, "modify-foreign-table-column-semantics")) { + if (!UserUtil.hasRole(principal, "modify-foreign-table-column-semantics")) { endpointValidator.validateOnlyAccess(id, principal, true); endpointValidator.validateOnlyOwnerOrWriteAll(id, tableId, principal); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableDataEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableDataEndpoint.java index f5f816658b78da685c1f45ba0162fdc1841637a5..9552418e9a169ecf254281b11b42a2b131c682f7 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableDataEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/TableDataEndpoint.java @@ -7,10 +7,10 @@ import at.tuwien.api.database.table.TableCsvDeleteDto; import at.tuwien.api.database.table.TableCsvDto; import at.tuwien.api.database.table.TableCsvUpdateDto; import at.tuwien.entities.database.Database; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; +import at.tuwien.utils.UserUtil; import at.tuwien.validation.EndpointValidator; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; @@ -155,7 +155,7 @@ public class TableDataEndpoint { endpointValidator.validateDataParams(page, size, sortDirection, sortColumn); endpointValidator.validateOnlyAccessOrPublic(databaseId, principal); final Database database = databaseService.find(databaseId); - if (!database.getIsPublic() && !User.hasRole(principal, "view-table-data")) { + if (!database.getIsPublic() && !UserUtil.hasRole(principal, "view-table-data")) { log.error("Failed to view table data: database with id {} is private and user has no authority", databaseId); throw new NotAllowedException("Failed to view table data: database with id " + databaseId + " is private and user has no authority"); } @@ -182,7 +182,7 @@ public class TableDataEndpoint { /* check */ endpointValidator.validateOnlyAccessOrPublic(databaseId, principal); final Database database = databaseService.find(databaseId); - if (!database.getIsPublic() && !User.hasRole(principal, "view-table-data")) { + if (!database.getIsPublic() && !UserUtil.hasRole(principal, "view-table-data")) { log.error("Failed to view table data: database with id {} is private and user has no authority", databaseId); throw new NotAllowedException("Failed to view table data: database with id " + databaseId + " is private and user has no authority"); } 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 500ccd9682577ca161a24e01e6891ffbc969e950..e78686f788c3f7a37341602149cecc034d55ecb2 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,12 +3,9 @@ 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.Realm; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; -import at.tuwien.mapper.UserMapper; -import at.tuwien.service.RealmService; import at.tuwien.service.UserService; +import at.tuwien.utils.UserUtil; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -30,7 +27,6 @@ import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.List; import java.util.UUID; -import java.util.stream.Collectors; @Log4j2 @CrossOrigin(origins = "*") @@ -38,15 +34,11 @@ import java.util.stream.Collectors; @RequestMapping("/api/user") public class UserEndpoint { - private final UserMapper userMapper; private final UserService userService; - private final RealmService realmService; @Autowired - public UserEndpoint(UserMapper userMapper, UserService userService, RealmService realmService) { - this.userMapper = userMapper; + public UserEndpoint(UserService userService) { this.userService = userService; - this.realmService = realmService; } @GetMapping @@ -60,12 +52,9 @@ public class UserEndpoint { mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = UserBriefDto.class)))}), }) - public ResponseEntity<List<UserBriefDto>> findAll() { + public ResponseEntity<List<UserBriefDto>> findAll() throws KeycloakRemoteException, AccessDeniedException { log.debug("endpoint find all users"); - final List<UserBriefDto> users = userService.findAll() - .stream() - .map(userMapper::userToUserBriefDto) - .collect(Collectors.toList()); + final List<UserBriefDto> users = userService.findAll(); log.trace("find all users resulted in users {}", users); return ResponseEntity.ok(users); } @@ -97,16 +86,15 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserBriefDto> create(@NotNull @Valid @RequestBody SignupRequestDto data) - throws RealmNotFoundException, UserAlreadyExistsException, UserEmailAlreadyExistsException { + public ResponseEntity<UserDto> create(@NotNull @Valid @RequestBody SignupRequestDto data) + throws RealmNotFoundException, UserAlreadyExistsException, UserEmailAlreadyExistsException, + UserNotFoundException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint create a user, data={}", data); /* check */ - final Realm realm = realmService.find("dbrepo"); userService.validateUsernameNotExists(data.getUsername()); userService.validateEmailNotExists(data.getEmail()); /* create */ - final User user = userService.create(data, realm); - final UserBriefDto dto = userMapper.userToUserBriefDto(user); + final UserDto dto = userService.create(data); log.trace("create user resulted in dto {}", dto); return ResponseEntity.status(HttpStatus.CREATED) .body(dto); @@ -134,24 +122,23 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserDto> find(@NotNull @PathVariable("id") String id, - @NotNull Principal principal) - throws UserNotFoundException, NotAllowedException { + public ResponseEntity<UserDto> find(@NotNull @PathVariable("id") UUID id, + @NotNull Principal principal) throws UserNotFoundException, NotAllowedException, + KeycloakRemoteException, AccessDeniedException { log.debug("endpoint find a user, id={}, principal={}", id, principal); /* check */ - final User user = userService.find(UUID.fromString(id)); - final UserDto dto = userMapper.userToUserDto(user); - if (user.getUsername().equals(principal.getName())) { + final UserDto dto = userService.find(id); + if (id.equals(UserUtil.getId(principal))) { log.trace("find user resulted in dto {}", dto); return ResponseEntity.ok() .body(dto); - } else if (User.hasRole(principal, "find-user")) { + } else if (UserUtil.hasRole(principal, "find-user")) { log.trace("find user resulted in dto {}", dto); return ResponseEntity.ok() .body(dto); } log.error("Failed to find user: no authority and not the current logged-in user"); - throw new NotAllowedException("Failed to find user: no authority"); + throw new NotAllowedException("Failed to find user: no authority and not the current logged-in user"); } @PutMapping("/{id}") @@ -176,19 +163,18 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserDto> modify(@NotNull @PathVariable("id") String id, + public ResponseEntity<UserDto> modify(@NotNull @PathVariable("id") UUID id, @NotNull @Valid @RequestBody UserUpdateDto data, - @NotNull Principal principal) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + @NotNull Principal principal) throws UserNotFoundException, + ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint modify a user, id={}, data={}, principal={}", id, data, principal); /* check */ - final User user = userService.find(UUID.fromString(id)); - if (!user.equalsPrincipal(principal)) { + if (!id.equals(UserUtil.getId(principal))) { log.error("Failed to modify user: attempting to modify other user"); throw new ForeignUserException("Failed to modify user: attempting to modify other user"); } /* modify */ - final UserDto dto = userMapper.userToUserDto(userService.modify(user.getId(), data)); + final UserDto dto = userService.modify(id, data); log.trace("modify user resulted in dto {}", dto); return ResponseEntity.status(HttpStatus.ACCEPTED) .body(dto); @@ -216,19 +202,19 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserDto> theme(@NotNull @PathVariable("id") String id, + public ResponseEntity<UserDto> theme(@NotNull @PathVariable("id") UUID id, @NotNull @Valid @RequestBody UserThemeSetDto data, @NotNull Principal principal) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, + AccessDeniedException { log.debug("endpoint modify a user theme, id={}, data={}, principal={}", id, data, principal); /* check */ - final User user = userService.find(UUID.fromString(id)); - if (!user.equalsPrincipal(principal)) { + if (!id.equals(UserUtil.getId(principal))) { log.error("Failed to modify user: attempting to modify other user"); throw new ForeignUserException("Failed to modify user: attempting to modify other user"); } /* modify theme */ - final UserDto dto = userMapper.userToUserDto(userService.toggleTheme(user.getId(), data)); + final UserDto dto = userService.toggleTheme(id, data); log.trace("modify user theme resulted in dto {}", dto); return ResponseEntity.accepted() .body(dto); @@ -256,22 +242,20 @@ public class UserEndpoint { mediaType = "application/json", schema = @Schema(implementation = ApiErrorDto.class))}), }) - public ResponseEntity<UserDto> password(@NotNull @PathVariable("id") String id, + public ResponseEntity<?> password(@NotNull @PathVariable("id") UUID id, @NotNull @Valid @RequestBody UserPasswordDto data, @NotNull Principal principal) - throws UserNotFoundException, ForeignUserException { + throws UserNotFoundException, ForeignUserException, KeycloakRemoteException, AccessDeniedException { log.debug("endpoint modify a user password, id={}, data={}, principal={}", id, data, principal); /* check */ - final User user = userService.find(UUID.fromString(id)); - if (!user.equalsPrincipal(principal)) { + if (!id.equals(UserUtil.getId(principal))) { log.error("Failed to modify user: attempting to modify other user"); throw new ForeignUserException("Failed to modify user: attempting to modify other user"); } /* modify password */ - final UserDto dto = userMapper.userToUserDto(userService.updatePassword(user.getId(), data)); - log.trace("updated user password resulted in dto {}", dto); + userService.updatePassword(id, data); return ResponseEntity.accepted() - .body(dto); + .build(); } } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ViewEndpoint.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ViewEndpoint.java index c7367fe6045231018283cbc6a92178aad08fafdf..0d06774fa070a0d959b664983b960133b966cafd 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ViewEndpoint.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/endpoints/ViewEndpoint.java @@ -7,12 +7,12 @@ import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.api.error.ApiErrorDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.View; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.ViewMapper; import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; import at.tuwien.service.ViewService; +import at.tuwien.utils.UserUtil; import at.tuwien.validation.EndpointValidator; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; @@ -150,7 +150,7 @@ public class ViewEndpoint { databaseId, data, principal); /* check */ final Database database = databaseService.find(databaseId); - if (!database.getOwner().equalsPrincipal(principal)) { + if (!database.getOwnedBy().equals(UserUtil.getId(principal))) { log.error("Failed to create view: not the database owner"); throw new NotAllowedException("Failed to create view: not the database owner"); } @@ -251,7 +251,7 @@ public class ViewEndpoint { databaseId, viewId, principal); /* check */ final Database database = databaseService.find(databaseId); - if (!database.getOwner().equalsPrincipal(principal)) { + if (!database.getOwnedBy().equals(UserUtil.getId(principal))) { log.error("Failed to delete view: not the database owner"); throw new NotAllowedException("Failed to delete view: not the database owner"); } @@ -339,7 +339,7 @@ public class ViewEndpoint { log.error("Failed to view data of private view: principal is null"); throw new NotAllowedException("Failed to view data of private view: principal is null"); } - if (!User.hasRole(principal, "view-database-view-data")) { + if (!UserUtil.hasRole(principal, "view-database-view-data")) { log.error("Failed to view data of private view: role missing"); throw new NotAllowedException("Failed to view data of private view: role missing"); } diff --git a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/validation/EndpointValidator.java b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/validation/EndpointValidator.java index fd29d514de4c1601b770fba5bbf8c7240a5bb957..03dce82c02709e45b8a7af06543455bf0cdf0d61 100644 --- a/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/validation/EndpointValidator.java +++ b/dbrepo-metadata-service/rest-service/src/main/java/at/tuwien/validation/EndpointValidator.java @@ -12,12 +12,12 @@ import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.database.table.Table; import at.tuwien.entities.identifier.Identifier; import at.tuwien.entities.identifier.VisibilityType; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.repository.mdb.IdentifierRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.TableService; +import at.tuwien.utils.UserUtil; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -104,7 +104,7 @@ public class EndpointValidator { final Optional<ColumnCreateDto> optional2 = data.getColumns() .stream() .filter(c -> c.getType().equals(ColumnTypeDto.ENUM)) - .filter(c -> c.getEnums() == null || c.getEnums().size() == 0) + .filter(c -> c.getEnums() == null || c.getEnums().isEmpty()) .findFirst(); if (optional2.isPresent()) { throw new TableMalformedException("Validation failed: column " + optional2.get().getName() + " needs at least 1 allowed enum value"); @@ -113,7 +113,7 @@ public class EndpointValidator { final Optional<ColumnCreateDto> optional3 = data.getColumns() .stream() .filter(c -> c.getType().equals(ColumnTypeDto.SET)) - .filter(c -> c.getEnums() == null || c.getSets().size() == 0) + .filter(c -> c.getEnums() == null || c.getSets().isEmpty()) .findFirst(); if (optional3.isPresent()) { throw new TableMalformedException("Validation failed: column " + optional3.get().getName() + " needs at least 1 allowed set value"); @@ -130,21 +130,21 @@ public class EndpointValidator { } public void validateOnlyOwnerOrWriteAll(Long databaseId, Long tableId, Principal principal) - throws DatabaseNotFoundException, NotAllowedException, TableNotFoundException, ContainerNotFoundException { + throws DatabaseNotFoundException, NotAllowedException, TableNotFoundException { if (principal == null) { log.error("Access not allowed: no authorization provided"); throw new NotAllowedException("Access not allowed: no authorization provided"); } final Table table = tableService.findById(databaseId, tableId); log.trace("principal: {}", principal.getName()); - log.trace("table creator: {}", table.getCreator().getUsername()); + log.trace("table creator: {}", table.getCreatedBy()); final DatabaseAccess access = accessService.find(databaseId, principal.getName()); log.trace("found access {}", access); if (access.getType().equals(AccessType.READ)) { log.error("Access not allowed: insufficient access (only read-access)"); throw new NotAllowedException("Access not allowed: insufficient access (only read-access)"); } - if (table.getCreator().equalsPrincipal(principal) && (access.getType().equals(AccessType.WRITE_OWN) || access.getType().equals(AccessType.WRITE_ALL))) { + if (table.getCreatedBy().equals(UserUtil.getId(principal)) && (access.getType().equals(AccessType.WRITE_OWN) || access.getType().equals(AccessType.WRITE_ALL))) { log.trace("grant access: table creator with write access"); return; } @@ -152,7 +152,7 @@ public class EndpointValidator { log.trace("grant access: write-all access"); return; } - log.error("Access not allowed: insufficient access (neither creator {} nor write-all access)", table.getCreator().getUsername()); + log.error("Access not allowed: insufficient access (neither creator {} nor write-all access)", table.getCreatedBy()); throw new NotAllowedException("Access not allowed: insufficient access (neither creator nor write-all access)"); } @@ -169,7 +169,7 @@ public class EndpointValidator { throw new NotAllowedException("Access not allowed: no authorization provided"); } log.trace("principal: {}", principal.getName()); - if (!User.hasRole(principal, role)) { + if (!UserUtil.hasRole(principal, role)) { log.error("Access not allowed: role {} missing", role); throw new NotAllowedException("Access not allowed: role " + role + " missing"); } @@ -218,7 +218,7 @@ public class EndpointValidator { words.add(keyword); } }); - if (words.size() == 0) { + if (words.isEmpty()) { return; } log.error("Query contains forbidden keyword(s): {}", words); @@ -249,7 +249,7 @@ public class EndpointValidator { final Identifier identifier = optional.get(); log.trace("found identifier for query with id {}", queryId); if (principal != null && identifier.getVisibility().equals(VisibilityType.SELF)) { - if (identifier.getCreator().getUsername().equals(principal.getName())) { + if (identifier.getCreatedBy().equals(UserUtil.getId(principal))) { return; } log.error("Access not allowed: visibility is 'self' and user is not the creator"); @@ -279,7 +279,7 @@ public class EndpointValidator { log.debug("user {} has write-all access, skip.", principal.getName()); return; } - if (table.getOwner().getUsername().equals(principal.getName()) && access.getType().equals(AccessType.WRITE_OWN)) { + if (table.getOwnedBy().equals(UserUtil.getId(principal)) && access.getType().equals(AccessType.WRITE_OWN)) { log.debug("user {} has write-own access to their own table, skip.", principal.getName()); return; } 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 fdff72e980214bf1e16fc163ff2c91a5dd0791a9..caab719e8f3100c64fbde4c0c4d1ae7ac813de38 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 @@ -54,6 +54,9 @@ fda: jwt: issuer: http://localhost/realms/dbrepo public_key: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqqnHQ2BWWW9vDNLRCcxD++xZg/16oqMo/c1l+lcFEjjAIJjJp/HqrPYU/U9GvquGE6PbVFtTzW1KcKawOW+FJNOA3CGo8Q1TFEfz43B8rZpKsFbJKvQGVv1Z4HaKPvLUm7iMm8Hv91cLduuoWx6Q3DPe2vg13GKKEZe7UFghF+0T9u8EKzA/XqQ0OiICmsmYPbwvf9N3bCKsB/Y10EYmZRb8IhCoV9mmO5TxgWgiuNeCTtNCv2ePYqL/U0WvyGFW0reasIK8eg3KrAUj8DpyOgPOVBn3lBGf+3KFSYi+0bwZbJZWqbC/Xlk20Go1YfeJPRIt7ImxD27R/lNjgDO/MwIDAQAB + keycloak: + username: fda + password: fda consumers: 2 unsupported: \*,AVG,BIT_AND,BIT_OR,BIT_XOR,COUNT,COUNTDISTINCT,GROUP_CONCAT,JSON_ARRAYAGG,JSON_OBJECTAGG,MAX,MIN,STD,STDDEV,STDDEV_POP,STDDEV_SAMP,SUM,VARIANCE,VAR_POP,VAR_SAMP,-- website: http://localhost diff --git a/dbrepo-metadata-service/rest-service/src/main/resources/application.yml b/dbrepo-metadata-service/rest-service/src/main/resources/application.yml index c24d35dc18b7e9d862cdbef585bc36d138a3f266..f8eff0c28c3a779160e21b4c7eaeca050ed199e1 100644 --- a/dbrepo-metadata-service/rest-service/src/main/resources/application.yml +++ b/dbrepo-metadata-service/rest-service/src/main/resources/application.yml @@ -67,6 +67,9 @@ fda: jwt: issuer: "${JWT_ISSUER}" public_key: "${JWT_PUBKEY}" + keycloak: + username: "${KEYCLOAK_ADMIN}" + password: "${KEYCLOAK_ADMIN_PASSWORD}" consumers: "${BROKER_CONSUMERS}" unsupported: "${NOT_SUPPORTED_KEYWORDS}" website: "${WEBSITE}" 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 65b8004f0c81bdb5533fea8a99252a7c9133e001..4e5be3249ad93271c23784a08540e99860fca2e7 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 @@ -6,7 +6,6 @@ import at.tuwien.api.database.table.columns.ColumnTypeDto; import at.tuwien.entities.container.Container; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.Table; -import at.tuwien.entities.user.User; import at.tuwien.exception.QueryMalformedException; import at.tuwien.mapper.DatabaseMapper; import at.tuwien.querystore.Query; @@ -123,18 +122,18 @@ public class MariaDbConfig { } } - public void mockGrantUserPermissions(Container container, Database database, User user) throws SQLException, + public void mockGrantUserPermissions(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); try (Connection connection = DriverManager.getConnection(jdbc, container.getPrivilegedUsername(), container.getPrivilegedPassword())) { final DatabaseGiveAccessDto access = DatabaseGiveAccessDto.builder() - .username(user.getUsername()) + .username(username) .type(AccessTypeDto.WRITE_ALL) .build(); final PreparedStatement statement1 = databaseMapper.rawGrantUserAccessQuery(connection, access); statement1.executeUpdate(); - final PreparedStatement statement2 = databaseMapper.rawGrantUserProcedure(connection, user); + final PreparedStatement statement2 = databaseMapper.rawGrantUserProcedure(connection, username); statement2.executeUpdate(); final PreparedStatement statement3 = databaseMapper.rawFlushPrivileges(connection); statement3.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 6f26be13b3eeb5b6dd32ea92cc2a94fa35751c28..fec328ef2b8e01208ba7935a3cbc04d73d20a3e3 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 @@ -9,11 +9,9 @@ import at.tuwien.api.database.DatabaseGiveAccessDto; import at.tuwien.api.database.DatabaseModifyAccessDto; 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.AccessMapper; import at.tuwien.repository.mdb.DatabaseRepository; -import at.tuwien.repository.mdb.UserRepository; import at.tuwien.service.AccessService; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -48,9 +46,6 @@ public class AccessEndpointUnitTest extends BaseUnitTest { @MockBean private DatabaseRepository databaseRepository; - @MockBean - private UserRepository userRepository; - @Autowired private AccessEndpoint accessEndpoint; @@ -63,7 +58,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, null, USER_2_USERNAME, USER_2, null); + generic_create(DATABASE_1_ID, DATABASE_1, null, USER_2_USERNAME, null); }); } @@ -73,14 +68,14 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, null, USER_4_USERNAME, USER_4, USER_4_PRINCIPAL); + generic_create(DATABASE_1_ID, DATABASE_1, null, USER_4_USERNAME, USER_4_PRINCIPAL); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"create-database-access"}) - public void create_succeeds() throws UserNotFoundException, NotAllowedException, QueryMalformedException, - DatabaseNotFoundException, DatabaseMalformedException, NotAllowedException { + public void create_succeeds() throws UserNotFoundException, QueryMalformedException, DatabaseNotFoundException, + DatabaseMalformedException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { /* mock */ doNothing() @@ -88,7 +83,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { .create(eq(DATABASE_1_ID), any(DatabaseGiveAccessDto.class)); /* test */ - generic_create(DATABASE_1_ID, DATABASE_1, null, USER_2_USERNAME, USER_2, USER_1_PRINCIPAL); + generic_create(DATABASE_1_ID, DATABASE_1, null, USER_2_USERNAME, USER_1_PRINCIPAL); } @Test @@ -97,7 +92,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_find(DATABASE_1_ID, DATABASE_1, null, USER_1_USERNAME, null, null); + generic_find(DATABASE_1_ID, DATABASE_1, null, null, null); }); } @@ -107,29 +102,25 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - generic_find(DATABASE_1_ID, DATABASE_1, null, USER_2_USERNAME, USER_2_ID, USER_2_PRINCIPAL); + generic_find(DATABASE_1_ID, DATABASE_1, null, USER_2_ID, USER_2_PRINCIPAL); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"check-database-access"}) - public void find_hasRoleHasAccess_succeeds() throws NotAllowedException, NotAllowedException { + public void find_hasRoleHasAccess_succeeds() throws NotAllowedException, AccessDeniedException { /* test */ - generic_find(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, USER_1_USERNAME, USER_1_ID, USER_1_PRINCIPAL); + generic_find(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, USER_1_ID, USER_1_PRINCIPAL); } @Test @WithAnonymousUser public void update_anonymous_fails() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_USERNAME, null); + generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, null); }); } @@ -137,13 +128,9 @@ public class AccessEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = {"update-database-access"}) public void update_hasRoleNoAccess_fails() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(NotAllowedException.class, () -> { - generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_USERNAME, USER_1_PRINCIPAL); + generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, USER_1_PRINCIPAL); }); } @@ -151,30 +138,24 @@ public class AccessEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_4_USERNAME) public void update_noRoleNoAccess_fails() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_USERNAME, USER_4_PRINCIPAL); + generic_update(DATABASE_1_ID, DATABASE_1, null, USER_4_ID, USER_4_PRINCIPAL); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"update-database-access"}) - public void update_succeeds() throws UserNotFoundException, NotAllowedException, NotAllowedException, - QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException { + public void update_succeeds() throws UserNotFoundException, NotAllowedException, QueryMalformedException, + DatabaseNotFoundException, DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException { /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); doNothing() .when(accessService) - .update(eq(DATABASE_1_ID), eq(USER_2_USERNAME), any(DatabaseModifyAccessDto.class)); + .update(eq(DATABASE_1_ID), eq(USER_2_ID), any(DatabaseModifyAccessDto.class)); /* test */ - generic_update(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_2_WRITE_OWN_ACCESS, USER_2_USERNAME, USER_1_PRINCIPAL); + generic_update(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_2_WRITE_OWN_ACCESS, USER_2_ID, USER_1_PRINCIPAL); } @Test @@ -183,7 +164,7 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_USERNAME, USER_1_PRINCIPAL); + generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_ID, USER_1_PRINCIPAL); }); } @@ -193,32 +174,32 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_USERNAME, USER_4_PRINCIPAL); + generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_ID, USER_4_PRINCIPAL); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"delete-database-access"}) - public void revoke_succeeds() throws UserNotFoundException, NotAllowedException, - QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, NotAllowedException { + public void revoke_succeeds() throws UserNotFoundException, QueryMalformedException, DatabaseNotFoundException, + DatabaseMalformedException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { /* mock */ doNothing() .when(accessService) - .delete(DATABASE_1_ID, USER_2_USERNAME); + .delete(DATABASE_1_ID, USER_2_ID); /* test */ - generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_USERNAME, USER_1_PRINCIPAL); + generic_revoke(DATABASE_1_ID, DATABASE_1_USER_1_WRITE_ALL_ACCESS, USER_2_ID, USER_1_PRINCIPAL); } /* ################################################################################################### */ /* ## GENERIC TEST CASES ## */ /* ################################################################################################### */ - protected void generic_create(Long databaseId, Database database, DatabaseAccess access, - String username, User user, Principal principal) throws UserNotFoundException, - NotAllowedException, QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, - NotAllowedException { + protected void generic_create(Long databaseId, Database database, DatabaseAccess access, String username, + Principal principal) throws UserNotFoundException, QueryMalformedException, + DatabaseNotFoundException, DatabaseMalformedException, NotAllowedException, KeycloakRemoteException, + AccessDeniedException { final DatabaseGiveAccessDto request = DatabaseGiveAccessDto.builder() .username(username) .type(AccessTypeDto.READ) @@ -227,8 +208,6 @@ public class AccessEndpointUnitTest extends BaseUnitTest { /* mock */ when(databaseRepository.findById(databaseId)) .thenReturn(Optional.of(database)); - when(userRepository.findByUsername(username)) - .thenReturn(Optional.of(user)); if (access != null) { log.trace("mock access {} for user with username {} for database with id {}", access.getType(), username, databaseId); when(accessService.find(databaseId, username)) @@ -246,22 +225,21 @@ public class AccessEndpointUnitTest extends BaseUnitTest { assertNull(response.getBody()); } - protected void generic_find(Long databaseId, Database database, DatabaseAccess access, - String username, UUID userId, Principal principal) throws NotAllowedException, - NotAllowedException { + protected void generic_find(Long databaseId, Database database, DatabaseAccess access, UUID userId, + Principal principal) throws NotAllowedException, AccessDeniedException { /* mock */ when(databaseRepository.findById(databaseId)) .thenReturn(Optional.of(database)); if (access != null) { - log.trace("mock access {} for user with username {} for database with id {}", access.getType(), username, databaseId); - when(accessService.find(databaseId, username)) + log.trace("mock access {} for user with id {} for database with id {}", access.getType(), userId, databaseId); + when(accessService.find(databaseId, userId)) .thenReturn(access); } else { - log.trace("mock no access for user with username {} for database with id {}", username, databaseId); + log.trace("mock no access for user with id {} for database with id {}", userId, databaseId); doThrow(NotAllowedException.class) .when(accessService) - .find(databaseId, username); + .find(databaseId, userId); } /* test */ @@ -274,9 +252,10 @@ public class AccessEndpointUnitTest extends BaseUnitTest { assertEquals(accessMapper.accessType(access.getType()), dto.getType()); } - protected void generic_update(Long databaseId, Database database, DatabaseAccess access, - String username, Principal principal) throws NotAllowedException, - NotAllowedException, UserNotFoundException, QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException { + protected void generic_update(Long databaseId, Database database, DatabaseAccess access, UUID userId, + Principal principal) throws NotAllowedException, UserNotFoundException, + QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, AccessDeniedException, + KeycloakRemoteException { final DatabaseModifyAccessDto request = DatabaseModifyAccessDto.builder() .type(AccessTypeDto.READ) .build(); @@ -285,40 +264,40 @@ public class AccessEndpointUnitTest extends BaseUnitTest { when(databaseRepository.findById(databaseId)) .thenReturn(Optional.of(database)); if (access != null) { - log.trace("mock access {} for user with username {} for database with id {}", access.getType(), username, databaseId); - when(accessService.find(databaseId, username)) + log.trace("mock access {} for user with id {} for database with id {}", access.getType(), userId, databaseId); + when(accessService.find(databaseId, userId)) .thenReturn(access); } else { - log.trace("mock no access for user with username {} for database with id {}", username, databaseId); + log.trace("mock no access for user with id {} for database with id {}", userId, databaseId); doThrow(NotAllowedException.class) .when(accessService) - .find(databaseId, username); + .find(databaseId, userId); } /* test */ - final ResponseEntity<?> response = accessEndpoint.update(databaseId, username, request, principal); + final ResponseEntity<?> response = accessEndpoint.update(databaseId, userId, request, principal); assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); assertNull(response.getBody()); } - protected void generic_revoke(Long databaseId, DatabaseAccess access, String username, - Principal principal) throws NotAllowedException, NotAllowedException, - UserNotFoundException, QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException { + protected void generic_revoke(Long databaseId, DatabaseAccess access, UUID userId, Principal principal) + throws NotAllowedException, UserNotFoundException, QueryMalformedException, DatabaseNotFoundException, + DatabaseMalformedException, AccessDeniedException, KeycloakRemoteException { /* mock */ if (access != null) { - log.trace("mock access {} for user with username {} for database with id {}", access.getType(), username, databaseId); - when(accessService.find(databaseId, username)) + log.trace("mock access {} for user with id {} for database with id {}", access.getType(), userId, databaseId); + when(accessService.find(databaseId, userId)) .thenReturn(access); } else { - log.trace("mock no access for user with username {} for database with id {}", username, databaseId); + log.trace("mock no access for user with id {} for database with id {}", userId, databaseId); doThrow(NotAllowedException.class) .when(accessService) - .find(databaseId, username); + .find(databaseId, userId); } /* test */ - final ResponseEntity<?> response = accessEndpoint.revoke(databaseId, username, principal); + final ResponseEntity<?> response = accessEndpoint.revoke(databaseId, userId, principal); assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); assertNull(response.getBody()); } 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 e83440a2403afd8863df87cf009eebdcdfbea397..7cc21d255fa1fa123bb8beb14863b71b76b8fa6e 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 @@ -9,8 +9,6 @@ import at.tuwien.api.container.ContainerDto; import at.tuwien.entities.container.Container; import at.tuwien.exception.*; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.ContainerServiceImpl; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -27,7 +25,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import java.security.Principal; import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.doNothing; @@ -43,9 +40,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @MockBean private ContainerServiceImpl containerService; - @MockBean - private UserRepository userRepository; - @MockBean private ImageRepository imageRepository; @@ -64,10 +58,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = {"find-container"}) public void findById_hasRole_succeeds() throws ContainerNotFoundException { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ findById_generic(CONTAINER_1_ID, CONTAINER_1); } @@ -76,10 +66,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_4_USERNAME) public void findById_noRole_succeeds() throws ContainerNotFoundException { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ findById_generic(CONTAINER_1_ID, CONTAINER_1); } @@ -98,10 +84,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_3_USERNAME) public void delete_noRole_fails() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(AccessDeniedException.class, () -> { delete_generic(CONTAINER_1_ID, CONTAINER_1, USER_4_PRINCIPAL); @@ -113,10 +95,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { public void delete_hasRole_succeeds() throws ContainerStillRunningException, ContainerAlreadyRemovedException, ContainerNotFoundException { - /* mock */ - when(userRepository.findByUsername(USER_2_USERNAME)) - .thenReturn(Optional.of(USER_2)); - /* test */ delete_generic(CONTAINER_1_ID, CONTAINER_1, USER_2_PRINCIPAL); } @@ -133,10 +111,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = {"find-containers"}) public void findAll_hasRole_succeeds() { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ findAll_generic(USER_1_PRINCIPAL, null); } @@ -145,10 +119,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_4_USERNAME) public void findAll_noRole_succeeds() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ findAll_generic(USER_4_PRINCIPAL, null); } @@ -175,10 +145,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { .imageId(IMAGE_1_ID) .build(); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ create_generic(request, USER_1_PRINCIPAL); } @@ -191,10 +157,6 @@ public class ContainerEndpointUnitTest extends BaseUnitTest { .imageId(IMAGE_1_ID) .build(); - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(AccessDeniedException.class, () -> { create_generic(request, USER_4_PRINCIPAL); 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 9f7a0ba1334f172e105c0a065bc41cfeef2c8cd0..f77e048247fc769877ad8e76a0fc47a1100d461b 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 @@ -4,14 +4,13 @@ import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.database.*; +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.repository.mdb.DatabaseAccessRepository; import at.tuwien.repository.mdb.IdentifierRepository; -import at.tuwien.repository.mdb.UserRepository; import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.ContainerService; @@ -33,7 +32,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import java.security.Principal; import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; @@ -46,9 +44,6 @@ import static org.mockito.Mockito.*; @MockOpensearch public class DatabaseEndpointUnitTest extends BaseUnitTest { - @MockBean - private UserRepository userRepository; - @MockBean private MessageQueueService messageQueueService; @@ -100,13 +95,9 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .isPublic(DATABASE_3_PUBLIC) .build(); - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - create_generic(DATABASE_3_ID, null, request, USER_4, USER_4_PRINCIPAL); + create_generic(DATABASE_3_ID, null, request, USER_4_DTO, USER_4_PRINCIPAL); }); } @@ -115,7 +106,8 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { public void create_succeeds() throws UserNotFoundException, BrokerVirtualHostGrantException, DatabaseNameExistsException, NotAllowedException, ContainerConnectionException, DatabaseMalformedException, QueryStoreException, DatabaseConnectionException, QueryMalformedException, DatabaseNotFoundException, - ImageNotSupportedException, AmqpException, BrokerVirtualHostCreationException, ContainerNotFoundException { + ImageNotSupportedException, AmqpException, BrokerVirtualHostCreationException, ContainerNotFoundException, + KeycloakRemoteException, AccessDeniedException { final DatabaseCreateDto request = DatabaseCreateDto.builder() .cid(CONTAINER_1_ID) .name(DATABASE_1_NAME) @@ -123,21 +115,19 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); when(containerService.find(CONTAINER_1_ID)) .thenReturn(CONTAINER_1); when(databaseService.create(request, USER_1_PRINCIPAL)) .thenReturn(DATABASE_1); doNothing() .when(messageQueueService) - .createUser(USER_1); + .createUser(USER_1_USERNAME); doNothing() .when(messageQueueService) .createExchange(DATABASE_1, USER_1_PRINCIPAL); doNothing() .when(messageQueueService) - .updatePermissions(USER_1); + .updatePermissions(USER_1_DTO); doNothing() .when(queryStoreService) .create(DATABASE_1_ID, USER_1_PRINCIPAL); @@ -145,7 +135,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .thenReturn(DATABASE_1_USER_1_WRITE_ALL_ACCESS); /* test */ - create_generic(DATABASE_1_ID, null, request, USER_1, USER_1_PRINCIPAL); + create_generic(DATABASE_1_ID, null, request, USER_1_DTO, USER_1_PRINCIPAL); } @Test @@ -166,10 +156,6 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { /* pre-condition */ assertTrue(DATABASE_3_PUBLIC); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ list_generic(DATABASE_3_ID, CONTAINER_3, List.of(DATABASE_3), USER_1_PRINCIPAL); } @@ -181,10 +167,6 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { /* pre-condition */ assertTrue(DATABASE_3_PUBLIC); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ list_generic(DATABASE_3_ID, CONTAINER_3, List.of(DATABASE_3), USER_1_PRINCIPAL); } @@ -205,15 +187,11 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-database-visibility"}) public void visibility_hasRole_succeeds() throws NotAllowedException, DatabaseNotFoundException, - UserNotFoundException { + UserNotFoundException, KeycloakRemoteException, AccessDeniedException { final DatabaseModifyVisibilityDto request = DatabaseModifyVisibilityDto.builder() .isPublic(true) .build(); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, USER_1_PRINCIPAL); } @@ -238,10 +216,6 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .isPublic(true) .build(); - /* mock */ - when(userRepository.findByUsername(USER_2_USERNAME)) - .thenReturn(Optional.of(USER_2)); - /* test */ assertThrows(NotAllowedException.class, () -> { visibility_generic(DATABASE_1_ID, DATABASE_1, DATABASE_1_DTO, request, USER_2_PRINCIPAL); @@ -255,10 +229,6 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .username(USER_4_USERNAME) .build(); - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { databaseEndpoint.transfer(DATABASE_3_ID, request, USER_4_PRINCIPAL); @@ -273,8 +243,6 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { .build(); /* mock */ - when(userRepository.findByUsername(USER_2_USERNAME)) - .thenReturn(Optional.of(USER_2)); when(databaseService.findById(DATABASE_1_ID)) .thenReturn(DATABASE_1); @@ -287,16 +255,12 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-database-owner"}) public void transfer_hasRole_succeeds() throws UserNotFoundException, DatabaseNotFoundException, - NotAllowedException { + NotAllowedException, KeycloakRemoteException, AccessDeniedException { final DatabaseTransferDto request = DatabaseTransferDto.builder() .username(USER_4_USERNAME) .build(); /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); when(databaseService.findById(DATABASE_1_ID)) .thenReturn(DATABASE_1); @@ -306,14 +270,13 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-database-owner"}) - public void transfer_hasRoleUserNotExists_succeeds() throws DatabaseNotFoundException, UserNotFoundException { + public void transfer_hasRoleUserNotExists_succeeds() throws DatabaseNotFoundException, UserNotFoundException, + KeycloakRemoteException, AccessDeniedException { final DatabaseTransferDto request = DatabaseTransferDto.builder() .username("foobar") .build(); /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); when(databaseService.findById(DATABASE_1_ID)) .thenReturn(DATABASE_1); doThrow(UserNotFoundException.class) @@ -387,7 +350,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - delete_generic(DATABASE_1_ID, DATABASE_1, null, null); + delete_generic(DATABASE_1_ID, DATABASE_1, null); }); } @@ -397,7 +360,7 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(org.springframework.security.access.AccessDeniedException.class, () -> { - delete_generic(DATABASE_1_ID, DATABASE_1, USER_1_USERNAME, USER_1_PRINCIPAL); + delete_generic(DATABASE_1_ID, DATABASE_1, USER_1_PRINCIPAL); }); } @@ -406,10 +369,10 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"delete-database"}) public void delete_hasRole_succeeds() throws UserNotFoundException, BrokerVirtualHostGrantException, DatabaseConnectionException, QueryMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - AmqpException, DatabaseMalformedException { + AmqpException, DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException { /* test */ - delete_generic(DATABASE_2_ID, DATABASE_2, USER_2_USERNAME, USER_2_PRINCIPAL); + delete_generic(DATABASE_2_ID, DATABASE_2, USER_2_PRINCIPAL); } /* ################################################################################################### */ @@ -432,12 +395,12 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { assertEquals(databases.size(), body.size()); } - 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, AmqpException, BrokerVirtualHostCreationException, ContainerNotFoundException, - BrokerVirtualHostGrantException { + public void create_generic(Long databaseId, Database database, DatabaseCreateDto data, UserDto user, + Principal principal) throws UserNotFoundException, DatabaseNameExistsException, + NotAllowedException, ContainerConnectionException, DatabaseMalformedException, QueryStoreException, + DatabaseConnectionException, QueryMalformedException, DatabaseNotFoundException, ImageNotSupportedException, + AmqpException, BrokerVirtualHostCreationException, ContainerNotFoundException, + BrokerVirtualHostGrantException, KeycloakRemoteException, AccessDeniedException { /* mock */ doNothing() @@ -458,9 +421,9 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { assertNotNull(response.getBody()); } - public void visibility_generic(Long databaseId, Database database, - DatabaseDto dto, DatabaseModifyVisibilityDto data, Principal principal) - throws NotAllowedException, DatabaseNotFoundException, UserNotFoundException { + public void visibility_generic(Long databaseId, Database database, DatabaseDto dto, + DatabaseModifyVisibilityDto data, Principal principal) throws NotAllowedException, + DatabaseNotFoundException, UserNotFoundException, KeycloakRemoteException, AccessDeniedException { /* mock */ if (database != null) { @@ -503,10 +466,10 @@ public class DatabaseEndpointUnitTest extends BaseUnitTest { return body; } - public void delete_generic(Long databaseId, Database database, String username, Principal principal) + public void delete_generic(Long databaseId, Database database, Principal principal) throws DatabaseNotFoundException, UserNotFoundException, DatabaseConnectionException, QueryMalformedException, ImageNotSupportedException, AmqpException, DatabaseMalformedException, - BrokerVirtualHostGrantException { + BrokerVirtualHostGrantException, KeycloakRemoteException, AccessDeniedException { /* mock */ if (database != null) { 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 fd9bcda5ae340183d125719d9146e47a8c9389b2..91ff1841a91e8b9011beb3e227f4568c93e33e8d 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 @@ -9,14 +9,12 @@ import at.tuwien.api.identifier.IdentifierTitleDto; import at.tuwien.api.identifier.IdentifierTypeDto; import at.tuwien.exception.NotAllowedException; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.IdentifierIdxRepository; 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; 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; @@ -37,8 +35,7 @@ import static org.junit.jupiter.api.Assertions.*; @MockAmqp @MockOpensearch public class IdentifierEndpointIntegrationTest extends BaseUnitTest { - @Autowired - private ViewRepository viewRepository; + @Autowired private TableRepository tableRepository; @@ -51,15 +48,9 @@ public class IdentifierEndpointIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ContainerRepository containerRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private LicenseRepository licenseRepository; @@ -69,12 +60,7 @@ public class IdentifierEndpointIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() { imageRepository.save(IMAGE_1); - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1); - userRepository.save(USER_2); - userRepository.save(USER_3); - userRepository.save(USER_4); containerRepository.save(CONTAINER_1_SIMPLE); containerRepository.save(CONTAINER_2_SIMPLE); containerRepository.save(CONTAINER_3_SIMPLE); 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 58c044ee41b8dd1616a8da0d546f0a797c5b5d72..a87a56def38ad3d5baf54f8c0760da62d466f6d9 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 @@ -8,12 +8,10 @@ import at.tuwien.config.EndpointConfig; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.identifier.Identifier; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.repository.mdb.DatabaseAccessRepository; import at.tuwien.repository.mdb.DatabaseRepository; import at.tuwien.repository.mdb.IdentifierRepository; -import at.tuwien.repository.mdb.UserRepository; import at.tuwien.repository.sdb.IdentifierIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.IdentifierService; @@ -63,9 +61,6 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { @MockBean private AccessService accessService; - @MockBean - private UserRepository userRepository; - @MockBean private DatabaseAccessRepository accessRepository; @@ -173,7 +168,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, null, IDENTIFIER_1_DTO_REQUEST, null, null, null, null, null); + generic_create(DATABASE_1_ID, DATABASE_1, null, IDENTIFIER_1_DTO_REQUEST, null, null, null); }); } @@ -190,7 +185,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { .thenReturn(Optional.of(DATABASE_1_USER_1_READ_ACCESS)); /* test */ - generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, IDENTIFIER_1_DTO_REQUEST, IDENTIFIER_1, USER_1_PRINCIPAL, USER_1_ID, USER_1_USERNAME, USER_1); + generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, IDENTIFIER_1_DTO_REQUEST, IDENTIFIER_1, USER_1_PRINCIPAL, USER_1_ID); } @Test @@ -199,7 +194,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, null, IDENTIFIER_1_DTO_REQUEST, IDENTIFIER_1, USER_1_PRINCIPAL, USER_1_ID, USER_1_USERNAME, USER_1); + generic_create(DATABASE_1_ID, DATABASE_1, null, IDENTIFIER_1_DTO_REQUEST, IDENTIFIER_1, USER_1_PRINCIPAL, USER_1_ID); }); } @@ -209,7 +204,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - generic_create(DATABASE_2_ID, DATABASE_2, null, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, null, null, null, null); + generic_create(DATABASE_2_ID, DATABASE_2, null, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, null, null); }); } @@ -222,7 +217,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { DatabaseConnectionException, ImageNotSupportedException { /* test */ - generic_create(DATABASE_2_ID, DATABASE_2, DATABASE_2_USER_1_READ_ACCESS, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, USER_2_PRINCIPAL, USER_2_ID, USER_2_USERNAME, USER_2); + generic_create(DATABASE_2_ID, DATABASE_2, DATABASE_2_USER_1_READ_ACCESS, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, USER_2_PRINCIPAL, USER_2_ID); } @Test @@ -243,7 +238,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(IdentifierRequestException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, request, null, USER_1_PRINCIPAL, USER_1_ID, USER_1_USERNAME, USER_1); + generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, request, null, USER_1_PRINCIPAL, USER_1_ID); }); } @@ -266,7 +261,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(IdentifierRequestException.class, () -> { - generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, request, null, USER_1_PRINCIPAL, USER_1_ID, USER_1_USERNAME, USER_1); + generic_create(DATABASE_1_ID, DATABASE_1, DATABASE_1_USER_1_READ_ACCESS, request, null, USER_1_PRINCIPAL, USER_1_ID); }); } @@ -276,7 +271,7 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - generic_create(DATABASE_2_ID, DATABASE_2, null, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, USER_1_PRINCIPAL, USER_1_ID, USER_1_USERNAME, USER_1); + generic_create(DATABASE_2_ID, DATABASE_2, null, IDENTIFIER_2_DTO_REQUEST, IDENTIFIER_2, USER_1_PRINCIPAL, USER_1_ID); }); } @@ -285,23 +280,15 @@ public class IdentifierEndpointUnitTest extends BaseUnitTest { /* ################################################################################################### */ protected void generic_create(Long databaseId, Database database, DatabaseAccess access, - IdentifierSaveDto data, Identifier identifier, Principal principal, UUID userId, - String username, User user) throws QueryNotFoundException, RemoteUnavailableException, - IdentifierAlreadyExistsException, UserNotFoundException, DatabaseNotFoundException, - IdentifierPublishingNotAllowedException, IdentifierRequestException, NotAllowedException, - at.tuwien.exception.AccessDeniedException, ViewNotFoundException, QueryStoreException, - DatabaseConnectionException, ImageNotSupportedException { + IdentifierSaveDto data, Identifier identifier, Principal principal, UUID userId) + throws QueryNotFoundException, RemoteUnavailableException, IdentifierAlreadyExistsException, + UserNotFoundException, DatabaseNotFoundException, IdentifierPublishingNotAllowedException, + IdentifierRequestException, NotAllowedException, at.tuwien.exception.AccessDeniedException, + ViewNotFoundException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { /* mock */ when(databaseRepository.findById(databaseId)) .thenReturn(Optional.of(database)); - if (user == null) { - when(userRepository.findByUsername(username)) - .thenReturn(Optional.empty()); - } else { - when(userRepository.findByUsername(username)) - .thenReturn(Optional.of(user)); - } if (access != null) { when(accessService.find(databaseId, userId)) .thenReturn(access); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointIntegrationTest.java index 863cc9ae22b61fb1ef39bab5b6f0c5091aedb597..7c15a099e6f00884a315c22a9360482ae3e56b41 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/ImageEndpointIntegrationTest.java @@ -7,16 +7,11 @@ import at.tuwien.exception.ImageAlreadyExistsException; import at.tuwien.exception.ImageInvalidException; import at.tuwien.exception.ImageNotFoundException; import at.tuwien.exception.UserNotFoundException; -import at.tuwien.repository.mdb.RealmRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; 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; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -27,22 +22,9 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @MockOpensearch public class ImageEndpointIntegrationTest extends BaseUnitTest { - @MockBean - private RealmRepository realmRepository; - - @MockBean - private UserRepository userRepository; - @Autowired private ImageEndpoint imageEndpoint; - @BeforeEach - public void beforeEach() { - /* metadata database */ - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_2_SIMPLE); - } - @Test @WithMockUser(username = USER_2_USERNAME, authorities = {"create-image"}) public void create_succeeds() throws UserNotFoundException, ImageAlreadyExistsException, 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 2a9d7df55d2b4486456940333c148c7532ed96de..4ac0ea87539e9d806f2021e62ae159e59722d749 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 @@ -9,8 +9,6 @@ import at.tuwien.api.container.image.ImageCreateDto; import at.tuwien.api.container.image.ImageDto; import at.tuwien.entities.container.image.ContainerImage; import at.tuwien.exception.*; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.ImageServiceImpl; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -42,9 +40,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { @MockBean private ImageServiceImpl imageService; - @MockBean - private UserRepository userRepository; - @Autowired private ImageEndpoint imageEndpoint; @@ -60,10 +55,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = {"find-image"}) public void findAll_hasRole_succeeds() { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ findAll_generic(USER_1_PRINCIPAL); } @@ -72,10 +63,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_4_USERNAME) public void findAll_noRole_succeeds() { - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ findAll_generic(USER_4_PRINCIPAL); } @@ -108,10 +95,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { .jdbcMethod(IMAGE_1_JDBC) .build(); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ assertThrows(AccessDeniedException.class, () -> { create_generic(request, USER_1_PRINCIPAL); @@ -129,10 +112,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { .jdbcMethod(IMAGE_1_JDBC) .build(); - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(AccessDeniedException.class, () -> { create_generic(request, USER_4_PRINCIPAL); @@ -150,10 +129,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { .jdbcMethod(IMAGE_1_JDBC) .build(); - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ assertThrows(ImageInvalidException.class, () -> { create_generic(request, USER_1_PRINCIPAL); @@ -195,10 +170,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME) public void delete_noRole_fails() { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ assertThrows(AccessDeniedException.class, () -> { delete_generic(IMAGE_1_ID, IMAGE_1, USER_1_PRINCIPAL); @@ -213,8 +184,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { doNothing() .when(imageService) .delete(IMAGE_1_ID); - when(userRepository.findByUsername(USER_2_USERNAME)) - .thenReturn(Optional.of(USER_2)); /* test */ delete_generic(IMAGE_1_ID, IMAGE_1, USER_2_PRINCIPAL); @@ -246,10 +215,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { .driverClass(IMAGE_1_DRIVER) .build(); - /* mock */ - when(userRepository.findByUsername(USER_4_USERNAME)) - .thenReturn(Optional.of(USER_4)); - /* test */ assertThrows(AccessDeniedException.class, () -> { modify_generic(IMAGE_1_ID, IMAGE_1, request, USER_4_PRINCIPAL); @@ -267,10 +232,6 @@ public class ImageEndpointUnitTest extends BaseUnitTest { .driverClass(IMAGE_1_DRIVER) .build(); - /* mock */ - when(userRepository.findByUsername(USER_2_USERNAME)) - .thenReturn(Optional.of(USER_2)); - /* test */ modify_generic(IMAGE_1_ID, IMAGE_1, request, USER_2_PRINCIPAL); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MetadataEndpointComponentTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MetadataEndpointComponentTest.java index 56ea331b0cc438cd651e0f54ab666b113a7c9531..7b8323ff0febbcfac7a4f7a6ad380eb0f8c9c269 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MetadataEndpointComponentTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/MetadataEndpointComponentTest.java @@ -49,12 +49,6 @@ public class MetadataEndpointComponentTest extends BaseUnitTest { @Autowired private DatabaseRepository databaseRepository; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private IdentifierRepository identifierRepository; @@ -62,9 +56,7 @@ public class MetadataEndpointComponentTest extends BaseUnitTest { public void beforeEach() { /* metadata database */ imageRepository.save(IMAGE_1_SIMPLE); - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); identifierRepository.save(IDENTIFIER_1); 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 bce4cf5d178361ff6b6ea3a4537f1ee894c2dae8..837a1596763653fb29f4e15383b14add6dbc2dd8 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 @@ -5,11 +5,9 @@ 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.repository.sdb.ConceptIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; import at.tuwien.service.EntityService; import at.tuwien.service.OntologyService; import at.tuwien.service.UserService; @@ -117,16 +115,17 @@ public class OntologyEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - create_generic(ONTOLOGY_1_CREATE_DTO, USER_4_PRINCIPAL, USER_4_USERNAME, USER_4, ONTOLOGY_1); + create_generic(ONTOLOGY_1_CREATE_DTO, USER_4_PRINCIPAL, USER_4_USERNAME, USER_4_DTO, ONTOLOGY_1); }); } @Test @WithMockUser(username = USER_3_USERNAME, authorities = {"create-ontology"}) - public void create_hasRole_succeeds() throws UserNotFoundException { + public void create_hasRole_succeeds() throws UserNotFoundException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* test */ - create_generic(ONTOLOGY_1_CREATE_DTO, USER_3_PRINCIPAL, USER_3_USERNAME, USER_3, ONTOLOGY_1); + create_generic(ONTOLOGY_1_CREATE_DTO, USER_3_PRINCIPAL, USER_3_USERNAME, USER_3_DTO, ONTOLOGY_1); } @Test @@ -314,8 +313,9 @@ public class OntologyEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - public void create_generic(OntologyCreateDto createDto, Principal principal, String username, User user, Ontology ontology) - throws UserNotFoundException { + public void create_generic(OntologyCreateDto createDto, Principal principal, String username, UserDto user, + Ontology ontology) throws UserNotFoundException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* mock */ if (ontology != null) { 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 c392b61f64864822630f60c22254dd3ed22e0868..397419a410f0cbfcab9d6aae39de866b18f443e2 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,17 +7,13 @@ 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.repository.sdb.IdentifierIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.IdentifierService; import at.tuwien.service.UserService; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Disabled; @@ -26,8 +22,6 @@ 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.context.annotation.Bean; -import org.springframework.context.annotation.Primary; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -41,7 +35,6 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.Principal; -import java.util.TimeZone; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -574,7 +567,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, USER_4_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_4_USERNAME, USER_4_DTO, USER_4_PRINCIPAL); }); } @@ -582,10 +575,11 @@ 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 { + RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ - generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3, USER_3_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3_DTO, USER_3_PRINCIPAL); } @Test @@ -593,14 +587,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 { + DatabaseConnectionException, ImageNotSupportedException, KeycloakRemoteException { /* 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, USER_3_PRINCIPAL); + generic_update(IDENTIFIER_3_ID, IDENTIFIER_3, IDENTIFIER_3_DTO_UPDATE_REQUEST, USER_3_USERNAME, USER_3_DTO, USER_3_PRINCIPAL); } @Test @@ -639,10 +633,11 @@ public class PersistenceEndpointUnitTest extends BaseUnitTest { return IOUtils.toString(inputStream, StandardCharsets.UTF_8); } - protected void generic_update(Long id, Identifier identifier, IdentifierSaveDto data, String username, User user, + protected void generic_update(Long id, Identifier identifier, IdentifierSaveDto data, String username, UserDto user, Principal principal) throws IdentifierNotFoundException, IdentifierRequestException, UserNotFoundException, NotAllowedException, QueryNotFoundException, DatabaseNotFoundException, - RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { + RemoteUnavailableException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* 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 c01e3dbf4f7b7f7c3459e2edda6aefcbec4ee586..ab03b010effa5a844d0fb0dbff7a6a6ce01a4832 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 @@ -10,17 +10,13 @@ import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.querystore.Query; import at.tuwien.repository.mdb.ContainerRepository; import at.tuwien.repository.mdb.DatabaseAccessRepository; import at.tuwien.repository.mdb.DatabaseRepository; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.QueryService; import at.tuwien.service.StoreService; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; @@ -130,8 +126,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_4_USERNAME, authorities = {"execute-query"}) public void execute_publicNoAccess_succeeds() throws UserNotFoundException, QueryStoreException, SortException, TableMalformedException, DatabaseConnectionException, NotAllowedException, QueryMalformedException, - ColumnParseException, DatabaseNotFoundException, ImageNotSupportedException, ContainerNotFoundException, - PaginationException { + ColumnParseException, DatabaseNotFoundException, ImageNotSupportedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_3_ID, QUERY_4_STATEMENT, null, null, DATABASE_3, null); @@ -141,8 +137,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_publicRead_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_3_ID, QUERY_4_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_3, DATABASE_3_USER_2_WRITE_ALL_ACCESS); @@ -152,8 +148,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_publicWriteOwn_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_3_ID, QUERY_4_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_3, DATABASE_3_USER_2_WRITE_ALL_ACCESS); @@ -163,8 +159,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_publicWriteAll_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_3_ID, QUERY_4_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_3, DATABASE_3_USER_2_WRITE_ALL_ACCESS); @@ -174,8 +170,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_publicOwner_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_3_ID, QUERY_4_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_3, DATABASE_3_USER_2_WRITE_ALL_ACCESS); @@ -288,8 +284,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_privateRead_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_2_ID, QUERY_1_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_2, DATABASE_2_USER_1_READ_ACCESS); @@ -299,8 +295,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_privateWriteOwn_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_2_ID, QUERY_1_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_2, DATABASE_2_USER_1_WRITE_OWN_ACCESS); @@ -310,8 +306,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_privateWriteAll_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_2_ID, QUERY_1_STATEMENT, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_2, DATABASE_2_USER_1_WRITE_ALL_ACCESS); @@ -321,8 +317,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = {"execute-query"}) public void execute_privateOwner_succeeds() throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, - ImageNotSupportedException, ContainerNotFoundException, SortException, NotAllowedException, - PaginationException { + ImageNotSupportedException, SortException, NotAllowedException, PaginationException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ generic_execute(DATABASE_2_ID, QUERY_1_STATEMENT, USER_1_USERNAME, USER_1_PRINCIPAL, DATABASE_2, DATABASE_2_USER_1_WRITE_ALL_ACCESS); @@ -434,7 +430,8 @@ public class QueryEndpointUnitTest extends BaseUnitTest { Principal principal, Database database, DatabaseAccess access) throws UserNotFoundException, QueryStoreException, TableMalformedException, DatabaseConnectionException, QueryMalformedException, ColumnParseException, DatabaseNotFoundException, ImageNotSupportedException, - ContainerNotFoundException, SortException, NotAllowedException, PaginationException { + SortException, NotAllowedException, PaginationException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(statement) .build(); 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 bc2e87c693c854f6597d97a81fb43fb10dfa4d51..95e2974bb3e1d1ce0315b1248ba931b6665c406a 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 @@ -16,8 +16,6 @@ import at.tuwien.exception.DatabaseNotFoundException; import at.tuwien.exception.QueryMalformedException; import at.tuwien.exception.TableColumnNotFoundException; import at.tuwien.exception.TableNotFoundException; -import at.tuwien.repository.sdb.ConceptIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; import at.tuwien.service.EntityService; import at.tuwien.service.SemanticService; import lombok.extern.log4j.Log4j2; 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 4f9fe461b0366f23cca23a13c1bfe33f23c21ba3..e81f264bec6ffd7abca13d65d4c91d169396104b 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 @@ -8,17 +8,11 @@ import at.tuwien.api.database.query.QueryDto; import at.tuwien.api.database.query.QueryPersistDto; 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.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.querystore.Query; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.impl.StoreServiceImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -57,9 +51,6 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @MockBean private AccessService accessService; - @MockBean - private UserRepository userRepository; - @Test @WithAnonymousUser public void findAll_privateAnonymous_fails() { @@ -143,15 +134,12 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser - public void find_publicAnonymous_succeeds() throws QueryStoreException, QueryNotFoundException, DatabaseNotFoundException, - ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException { - - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); + public void find_publicAnonymous_succeeds() throws QueryStoreException, QueryNotFoundException, + DatabaseNotFoundException, ImageNotSupportedException, UserNotFoundException, NotAllowedException, + DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = find_generic(DATABASE_3_ID, DATABASE_3, QUERY_4_ID, QUERY_4, null, null, null); + final QueryDto response = find_generic(DATABASE_3_ID, DATABASE_3, QUERY_4_ID, QUERY_4, null); assertEquals(QUERY_4_ID, response.getId()); assertEquals(QUERY_4_STATEMENT, response.getQuery()); } @@ -160,23 +148,20 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @WithAnonymousUser public void find_privateAnonymous_fails() { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); - /* test */ assertThrows(NotAllowedException.class, () -> { - find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, null, null, null); + find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, null); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = "find-query") public void find_hasRole_succeeds() throws QueryStoreException, QueryNotFoundException, DatabaseNotFoundException, - ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException { + ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException, + KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL); + final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_PRINCIPAL); assertEquals(QUERY_1_ID, response.getId()); assertEquals(QUERY_1_STATEMENT, response.getQuery()); } @@ -184,10 +169,11 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME) public void find_noRole_succeeds() throws QueryStoreException, QueryNotFoundException, DatabaseNotFoundException, - ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException { + ImageNotSupportedException, UserNotFoundException, NotAllowedException, DatabaseConnectionException, + KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL); + final QueryDto response = find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_PRINCIPAL); assertEquals(QUERY_1_ID, response.getId()); assertEquals(QUERY_1_STATEMENT, response.getQuery()); } @@ -198,7 +184,7 @@ public class StoreEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(QueryNotFoundException.class, () -> { - find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, null, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL); + find_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, null, USER_1_PRINCIPAL); }); } @@ -208,7 +194,7 @@ public class StoreEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(DatabaseNotFoundException.class, () -> { - find_generic(DATABASE_1_ID, null, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL); + find_generic(DATABASE_1_ID, null, QUERY_1_ID, QUERY_1, USER_1_PRINCIPAL); }); } @@ -216,10 +202,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = "persist-query") public void persist_ownRead_succeeds() throws UserNotFoundException, QueryStoreException, NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, - DatabaseNotFoundException, ImageNotSupportedException { + DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL, DATABASE_1_USER_1_READ_ACCESS); + final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1_PRINCIPAL, DATABASE_1_USER_1_READ_ACCESS); assertEquals(QUERY_1_ID, response.getId()); assertEquals(QUERY_1_STATEMENT, response.getQuery()); } @@ -228,10 +214,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = "persist-query") public void persist_ownWriteOwn_succeeds() throws UserNotFoundException, QueryStoreException, NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, - DatabaseNotFoundException, ImageNotSupportedException { + DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_OWN_ACCESS); + final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_OWN_ACCESS); assertEquals(QUERY_1_ID, response.getId()); assertEquals(QUERY_1_STATEMENT, response.getQuery()); } @@ -240,10 +226,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_1_USERNAME, authorities = "persist-query") public void persist_ownWriteAll_succeeds() throws UserNotFoundException, QueryStoreException, NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, - DatabaseNotFoundException, ImageNotSupportedException { + DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { /* test */ - final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_ALL_ACCESS); + final QueryDto response = persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_1_USERNAME, USER_1_PRINCIPAL, DATABASE_1_USER_1_WRITE_ALL_ACCESS); assertEquals(QUERY_1_ID, response.getId()); assertEquals(QUERY_1_STATEMENT, response.getQuery()); } @@ -252,14 +238,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { @WithMockUser(username = USER_2_USERNAME, authorities = "persist-query") public void persist_foreignWriteAll_succeeds() throws UserNotFoundException, QueryStoreException, NotAllowedException, DatabaseConnectionException, QueryAlreadyPersistedException, QueryNotFoundException, - DatabaseNotFoundException, ImageNotSupportedException { - - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); + DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { /* test */ - persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_2_USERNAME, USER_2, USER_2_PRINCIPAL, DATABASE_1_USER_2_WRITE_ALL_ACCESS); + persist_generic(DATABASE_1_ID, DATABASE_1, QUERY_1_ID, QUERY_1, USER_2_USERNAME, USER_2_PRINCIPAL, DATABASE_1_USER_2_WRITE_ALL_ACCESS); } @@ -268,10 +250,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { /* ################################################################################################### */ protected QueryDto persist_generic(Long databaseId, Database database, Long queryId, Query query, - String username, User user, Principal principal, DatabaseAccess access) + String username, Principal principal, DatabaseAccess access) throws DatabaseNotFoundException, UserNotFoundException, QueryStoreException, QueryNotFoundException, ImageNotSupportedException, NotAllowedException, DatabaseConnectionException, - QueryAlreadyPersistedException { + QueryAlreadyPersistedException, KeycloakRemoteException, AccessDeniedException { final QueryPersistDto request = QueryPersistDto.builder() .persist(true) .build(); @@ -292,8 +274,6 @@ public class StoreEndpointUnitTest extends BaseUnitTest { when(accessService.find(databaseId, username)) .thenThrow(NotAllowedException.class); } - when(userRepository.findByUsername(username)) - .thenReturn(Optional.of(user)); /* test */ final ResponseEntity<QueryDto> response = storeEndpoint.persist(databaseId, queryId, request, principal); @@ -322,10 +302,10 @@ public class StoreEndpointUnitTest extends BaseUnitTest { assertEquals(QUERY_1_STATEMENT, query.getQuery()); } - protected QueryDto find_generic(Long databaseId, Database database, Long queryId, Query query, - String username, User user, Principal principal) throws QueryStoreException, - QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, UserNotFoundException, - NotAllowedException, DatabaseConnectionException { + protected QueryDto find_generic(Long databaseId, Database database, Long queryId, Query query, Principal principal) + throws QueryStoreException, QueryNotFoundException, DatabaseNotFoundException, ImageNotSupportedException, + UserNotFoundException, NotAllowedException, DatabaseConnectionException, KeycloakRemoteException, + AccessDeniedException { /* mock */ if (query != null) { @@ -342,13 +322,6 @@ public class StoreEndpointUnitTest extends BaseUnitTest { when(databaseService.find(databaseId)) .thenThrow(DatabaseNotFoundException.class); } - if (user != null) { - when(userRepository.findByUsername(username)) - .thenReturn(Optional.of(user)); - } else { - when(userRepository.findByUsername(username)) - .thenReturn(Optional.empty()); - } /* test */ final ResponseEntity<QueryDto> response = storeEndpoint.find(databaseId, queryId, principal); 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 9d559676a5acabf77e4e8875e044940c5f3beb74..0083761dc09e8f2bb08002d2b418c98b487ca1c8 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 @@ -11,14 +11,10 @@ import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.database.table.Table; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.TableService; import at.tuwien.service.impl.QueryServiceImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointIntegrationTest.java index da60844123a313fb2025680da3d604a38268f896..e52f787ea9dc496b3ceb2f3e87fc5547335d7067 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableEndpointIntegrationTest.java @@ -6,11 +6,6 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.config.MariaDbConfig; import at.tuwien.exception.*; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ConceptIdxRepository; -import at.tuwien.repository.sdb.TableColumnIdxRepository; -import at.tuwien.repository.sdb.TableIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,7 +14,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.MariaDBContainer; @@ -46,12 +40,6 @@ public class TableEndpointIntegrationTest extends BaseUnitTest { @Autowired private DatabaseRepository databaseRepository; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private DatabaseAccessRepository accessRepository; @@ -66,8 +54,6 @@ public class TableEndpointIntegrationTest extends BaseUnitTest { public void beforeEach() throws SQLException { /* metadata database */ imageRepository.save(IMAGE_1); - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); MariaDbConfig.dropAllDatabases(CONTAINER_1); 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 f4b9eaf1293bb73c85225b4dc1d5889f3289070e..789b3c968f98ae5e3902f9126dc254c8d317c7e8 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 @@ -10,14 +10,9 @@ import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.database.table.Table; import at.tuwien.exception.*; -import at.tuwien.repository.sdb.ConceptIdxRepository; -import at.tuwien.repository.sdb.TableColumnIdxRepository; -import at.tuwien.repository.sdb.TableIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.TableService; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableHistoryEndpointUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableHistoryEndpointUnitTest.java index 43be785375f93122985a2a3189638cdb381cf4d6..562fab5aa4a64e48fb2f6dfa141300a98f992b10 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableHistoryEndpointUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/endpoints/TableHistoryEndpointUnitTest.java @@ -8,14 +8,9 @@ import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.entities.database.table.Table; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.DatabaseAccessRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.DatabaseService; -import at.tuwien.service.QueryService; import at.tuwien.service.TableService; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; 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 267da029d8249ff159e47185b3c580f9af7872c3..d467a7936075c7531b1d36cea049a62fe8c8567c 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,13 +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.Realm; -import at.tuwien.entities.user.Role; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; -import at.tuwien.repository.sdb.UserIdxRepository; -import at.tuwien.service.RealmService; -import at.tuwien.service.RoleService; import at.tuwien.service.UserService; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; @@ -33,8 +27,7 @@ import java.util.List; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @Log4j2 @EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) @@ -47,18 +40,12 @@ public class UserEndpointUnitTest extends BaseUnitTest { @MockBean private UserService userService; - @MockBean - private RealmService realmService; - - @MockBean - private RoleService roleService; - @Autowired private UserEndpoint userEndpoint; @Test @WithAnonymousUser - public void findAll_anonymous_succeeds() { + public void findAll_anonymous_succeeds() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ findAll_generic(); @@ -66,7 +53,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { @Test @WithMockUser(username = USER_1_USERNAME) - public void findAll_noRole_succeeds() { + public void findAll_noRole_succeeds() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* test */ findAll_generic(); @@ -75,20 +62,8 @@ public class UserEndpointUnitTest extends BaseUnitTest { @Test @WithAnonymousUser public void create_anonymous_succeeds() throws UserNotFoundException, UserEmailAlreadyExistsException, - RealmNotFoundException, RoleNotFoundException, RemoteUnavailableException, UserAlreadyExistsException { - final SignupRequestDto request = SignupRequestDto.builder() - .email(USER_1_EMAIL) - .username(USER_1_USERNAME) - .password(USER_1_PASSWORD) - .build(); - - /* test */ - create_generic(USER_1, REALM_DBREPO, ROLE_DEFAULT_RESEARCHER_ROLES, request); - } - - @Test - @WithAnonymousUser - public void create_realmNotFound_fails() { + RealmNotFoundException, UserAlreadyExistsException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { final SignupRequestDto request = SignupRequestDto.builder() .email(USER_1_EMAIL) .username(USER_1_USERNAME) @@ -96,9 +71,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - assertThrows(RealmNotFoundException.class, () -> { - create_generic(USER_1, null, ROLE_DEFAULT_RESEARCHER_ROLES, request); - }); + create_generic(request); } @Test @@ -112,7 +85,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - create_generic(USER_2, REALM_DBREPO, ROLE_DEFAULT_RESEARCHER_ROLES, request); + create_generic(request); }); } @@ -122,16 +95,17 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - find_generic(USER_1_ID.toString(), USER_1, null); + find_generic(USER_1_ID, USER_1_DTO, null); }); } @Test @WithMockUser(username = USER_1_USERNAME) - public void find_self_succeeds() throws UserNotFoundException, NotAllowedException { + public void find_self_succeeds() throws UserNotFoundException, NotAllowedException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* test */ - find_generic(USER_1_ID.toString(), USER_1, USER_1_PRINCIPAL); + find_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL); } @Test @@ -140,7 +114,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - find_generic(USER_2_ID.toString(), USER_2, USER_1_PRINCIPAL); + find_generic(USER_2_ID, USER_2_DTO, USER_1_PRINCIPAL); }); } @@ -150,7 +124,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(NotAllowedException.class, () -> { - find_generic(USER_2_ID.toString(), USER_2, USER_3_PRINCIPAL); + find_generic(USER_2_ID, USER_2_DTO, USER_3_PRINCIPAL); }); } @@ -166,7 +140,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - modify_generic(USER_1_ID.toString(), USER_1, null, request); + modify_generic(USER_1_ID, USER_1_DTO, null, request); }); } @@ -182,7 +156,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - modify_generic(USER_1_ID.toString(), USER_1, USER_4_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1_DTO, USER_4_PRINCIPAL, request); }); } @@ -198,13 +172,14 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - modify_generic(USER_1_ID.toString(), USER_1, USER_2_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1_DTO, USER_2_PRINCIPAL, request); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-user-information"}) - public void modify_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + public void modify_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { final UserUpdateDto request = UserUpdateDto.builder() .firstname(USER_1_FIRSTNAME) .lastname(USER_1_LASTNAME) @@ -213,7 +188,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { .build(); /* test */ - modify_generic(USER_1_ID.toString(), USER_1, USER_1_PRINCIPAL, request); + modify_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); } @Test @@ -225,7 +200,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - theme_generic(USER_1_ID.toString(), USER_1, null, request); + theme_generic(USER_1_ID, USER_1_DTO, null, request); }); } @@ -238,7 +213,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - theme_generic(USER_4_ID.toString(), USER_4, USER_4_PRINCIPAL, request); + theme_generic(USER_4_ID, USER_4_DTO, USER_4_PRINCIPAL, request); }); } @@ -251,19 +226,20 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - theme_generic(USER_1_ID.toString(), USER_1, USER_2_PRINCIPAL, request); + theme_generic(USER_1_ID, USER_1_DTO, USER_2_PRINCIPAL, request); }); } @Test @WithMockUser(username = USER_1_USERNAME, authorities = {"modify-user-theme"}) - public void theme_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + public void theme_succeeds() throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, + KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { final UserThemeSetDto request = UserThemeSetDto.builder() .themeDark(USER_1_THEME_DARK) .build(); /* test */ - theme_generic(USER_1_ID.toString(), USER_1, USER_1_PRINCIPAL, request); + theme_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); } @Test @@ -275,7 +251,7 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(AccessDeniedException.class, () -> { - password_generic(USER_1_ID.toString(), USER_1, null, request); + password_generic(USER_1_ID, USER_1_DTO, null, request); }); } @@ -288,30 +264,31 @@ public class UserEndpointUnitTest extends BaseUnitTest { /* test */ assertThrows(ForeignUserException.class, () -> { - password_generic(USER_1_ID.toString(), USER_1, USER_4_PRINCIPAL, request); + password_generic(USER_1_ID, USER_1_DTO, USER_4_PRINCIPAL, request); }); } @Test @WithMockUser(username = USER_1_USERNAME) - public void password_succeeds() throws UserNotFoundException, ForeignUserException { + public void password_succeeds() throws UserNotFoundException, ForeignUserException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { final UserPasswordDto request = UserPasswordDto.builder() .password(USER_1_PASSWORD) .build(); /* test */ - password_generic(USER_1_ID.toString(), USER_1, USER_1_PRINCIPAL, request); + password_generic(USER_1_ID, USER_1_DTO, USER_1_PRINCIPAL, request); } /* ################################################################################################### */ /* ## GENERIC TEST CASES ## */ /* ################################################################################################### */ - protected void findAll_generic() { + protected void findAll_generic() throws KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* mock */ when(userService.findAll()) - .thenReturn(List.of(USER_1, USER_2)); + .thenReturn(List.of(USER_1_BRIEF_DTO, USER_2_BRIEF_DTO)); /* test */ final ResponseEntity<List<UserBriefDto>> response = userEndpoint.findAll(); @@ -321,54 +298,28 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertEquals(2, body.size()); } - protected void create_generic(User user, Realm realm, Role role, SignupRequestDto data) - throws UserEmailAlreadyExistsException, RealmNotFoundException, RoleNotFoundException, - UserAlreadyExistsException { - - /* mock */ - if (realm != null) { - when(realmService.find(REALM_DBREPO_NAME)) - .thenReturn(realm); - } else { - doThrow(RealmNotFoundException.class) - .when(realmService) - .find(REALM_DBREPO_NAME); - } - if (role != null) { - when(roleService.find(ROLE_DEFAULT_RESEARCHER_ROLES_NAME)) - .thenReturn(role); - } else { - doThrow(RoleNotFoundException.class) - .when(roleService) - .find(ROLE_DEFAULT_REALM_DBREPO_ROLES_NAME); - } - if (user != null) { - when(userService.create(data, realm)) - .thenReturn(user); - } else { - doThrow(UserNotFoundException.class) - .when(userService) - .create(data, realm); - } + protected void create_generic(SignupRequestDto data) throws UserEmailAlreadyExistsException, RealmNotFoundException, + UserAlreadyExistsException, UserNotFoundException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* test */ - final ResponseEntity<UserBriefDto> response = userEndpoint.create(data); + final ResponseEntity<UserDto> response = userEndpoint.create(data); assertEquals(HttpStatus.CREATED, response.getStatusCode()); - final UserBriefDto body = response.getBody(); + final UserDto body = response.getBody(); assertNotNull(body); } - protected void find_generic(String id, User user, Principal principal) throws UserNotFoundException, - NotAllowedException { + protected void find_generic(UUID id, UserDto user, Principal principal) throws UserNotFoundException, + NotAllowedException, KeycloakRemoteException, at.tuwien.exception.AccessDeniedException { /* mock */ if (user != null) { - when(userService.find(UUID.fromString(id))) + when(userService.find(id)) .thenReturn(user); } else { doThrow(UserNotFoundException.class) .when(userService) - .find(UUID.fromString(id)); + .find(id); } /* test */ @@ -378,19 +329,20 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void modify_generic(String id, User user, Principal principal, UserUpdateDto data) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + protected void modify_generic(UUID id, UserDto user, Principal principal, UserUpdateDto data) + throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* mock */ if (user != null) { - when(userService.find(UUID.fromString(id))) + when(userService.find(id)) .thenReturn(user); } else { doThrow(UserNotFoundException.class) .when(userService) - .find(UUID.fromString(id)); + .find(id); } - when(userService.modify(UUID.fromString(id), data)) + when(userService.modify(id, data)) .thenReturn(user); /* test */ @@ -400,19 +352,20 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void theme_generic(String id, User user, Principal principal, UserThemeSetDto data) - throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException { + protected void theme_generic(UUID id, UserDto user, Principal principal, UserThemeSetDto data) + throws UserNotFoundException, ForeignUserException, UserAttributeNotFoundException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* mock */ if (user != null) { - when(userService.find(UUID.fromString(id))) + when(userService.find(id)) .thenReturn(user); } else { doThrow(UserNotFoundException.class) .when(userService) - .find(UUID.fromString(id)); + .find(id); } - when(userService.toggleTheme(UUID.fromString(id), data)) + when(userService.toggleTheme(id, data)) .thenReturn(user); /* test */ @@ -422,25 +375,25 @@ public class UserEndpointUnitTest extends BaseUnitTest { assertNotNull(body); } - protected void password_generic(String id, User user, Principal principal, UserPasswordDto data) - throws UserNotFoundException, ForeignUserException { + protected void password_generic(UUID id, UserDto user, Principal principal, UserPasswordDto data) + throws UserNotFoundException, ForeignUserException, KeycloakRemoteException, + at.tuwien.exception.AccessDeniedException { /* mock */ if (user != null) { - when(userService.find(UUID.fromString(id))) + when(userService.find(id)) .thenReturn(user); } else { doThrow(UserNotFoundException.class) .when(userService) - .find(UUID.fromString(id)); + .find(id); } - when(userService.updatePassword(UUID.fromString(id), data)) - .thenReturn(user); + doNothing() + .when(userService) + .updatePassword(id, data); /* test */ - final ResponseEntity<UserDto> response = userEndpoint.password(id, data, principal); + final ResponseEntity<?> response = userEndpoint.password(id, data, principal); assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); - final UserDto body = response.getBody(); - assertNotNull(body); } } 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 45ea13be12879a040ac15731717719294bbc21d1..ac325fbe5053dfab95c2cc0200e442ace0f6f401 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 @@ -10,14 +10,10 @@ import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; import at.tuwien.service.ViewService; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/gateway/BrokerServiceGatewayTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/gateway/BrokerServiceGatewayTest.java index 92846d8e0bb7a9a3c21c7ddcf704797f2471c396..ef9682a26d73a567883962dcc285cbb32fb88de3 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/gateway/BrokerServiceGatewayTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/gateway/BrokerServiceGatewayTest.java @@ -5,8 +5,6 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.exception.BrokerVirtualHostCreationException; import at.tuwien.exception.BrokerVirtualHostGrantException; -import at.tuwien.repository.sdb.DatabaseIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,8 +19,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import java.net.URI; - import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/listener/RabbitMqListenerIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/listener/RabbitMqListenerIntegrationTest.java index b5e70850ca7b65ded5d5a2716f4a865ec6294711..64ef5d0c348d13362d3003b027f6dfaf7e63fa33 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/listener/RabbitMqListenerIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/listener/RabbitMqListenerIntegrationTest.java @@ -1,13 +1,11 @@ package at.tuwien.listener; import at.tuwien.BaseUnitTest; -import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.amqp.ConsumerDto; import at.tuwien.config.AmqpConfig; import at.tuwien.config.RabbitMqConfig; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; @@ -19,7 +17,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.rules.Timeout; 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.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; @@ -35,7 +32,6 @@ import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; - @Log4j2 @ActiveProfiles(profiles = "junit") @Testcontainers @@ -54,12 +50,6 @@ public class RabbitMqListenerIntegrationTest extends BaseUnitTest { @Autowired private ContainerRepository containerRepository; - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @Autowired private DatabaseRepository databaseRepository; @@ -92,8 +82,6 @@ public class RabbitMqListenerIntegrationTest extends BaseUnitTest { public void beforeEach() { /* metadata database */ imageRepository.save(IMAGE_1_SIMPLE); - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); tableRepository.save(TABLE_1_SIMPLE); 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 df991d55863fdbfef622d9cc715858d2411a89ed..73e17f82b88365ed4b6275a6bde94d19651f8bc2 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 @@ -5,14 +5,11 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.database.DatabaseDto; import at.tuwien.api.user.UserBriefDto; -import at.tuwien.repository.sdb.DatabaseIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; 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 static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/QueryMapperTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/QueryMapperTest.java index f4304d570226edd34dcfcd59a7c6e4a3e217f807..eb6a70c6dd0f5fee845d8f5a9df3e3ab26ae64dc 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/QueryMapperTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/QueryMapperTest.java @@ -6,15 +6,11 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.entities.container.image.ContainerImageDate; import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.entities.database.table.columns.TableColumnType; -import at.tuwien.listener.impl.RabbitMqListenerImpl; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; 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.time.Instant; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/StoreMapperTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/StoreMapperTest.java index 8e2533709c89caa3ff89b7f15f303bc7bea938b7..f842f65db6feaed05c62ed8a234579aab7222d27 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/StoreMapperTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/StoreMapperTest.java @@ -3,14 +3,8 @@ package at.tuwien.mapper; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; -import at.tuwien.listener.impl.RabbitMqListenerImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -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.time.Instant; import java.time.LocalDateTime; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/TableMapperUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/TableMapperUnitTest.java index 3a736c8feac82b7e4ba0a763fa0f3a4eb240e126..b1d1a841cc93add28f9fe5e52d7aec6963c0ee39 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/TableMapperUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/TableMapperUnitTest.java @@ -3,11 +3,6 @@ package at.tuwien.mapper; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; -import at.tuwien.repository.sdb.ConceptIdxRepository; -import at.tuwien.repository.sdb.TableColumnIdxRepository; -import at.tuwien.repository.sdb.TableIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -17,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.test.context.junit.jupiter.SpringExtension; import java.util.stream.Stream; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/UserMapperTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/UserMapperTest.java index 73f9a670b45a38e3c5b79d937d0e6531aaf2005f..87b5665cc7eee2fd02a24259d99506b56b99f92e 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/UserMapperTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/mapper/UserMapperTest.java @@ -3,12 +3,10 @@ package at.tuwien.mapper; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.user.User; -import at.tuwien.repository.sdb.UserIdxRepository; +import at.tuwien.api.user.UserDto; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -23,24 +21,24 @@ public class UserMapperTest extends BaseUnitTest { public void equals_fails() { /* test */ - assertNotEquals(USER_1, USER_2); + assertNotEquals(USER_1_DTO, USER_2_DTO); } @Test public void equals_identity_succeeds() { /* test */ - assertEquals(USER_1, USER_1); + assertEquals(USER_1_DTO, USER_1_DTO); } @Test public void equals_similar_succeeds() { - final User tmp = User.builder() + final UserDto tmp = UserDto.builder() .id(USER_1_ID) .build(); /* test */ - assertEquals(USER_1, tmp); + assertEquals(USER_1_DTO, tmp); } } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/DatabaseRepositoryUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/DatabaseRepositoryUnitTest.java index 6143fe1974e67b9308cab97a70398a2d7f23ad79..66f1695ae6a256b2a5c5ef6dac60e9a59158711e 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/DatabaseRepositoryUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/DatabaseRepositoryUnitTest.java @@ -5,18 +5,14 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.entities.database.Database; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.DatabaseIdxRepository; -import com.rabbitmq.client.Channel; 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; 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.junit.jupiter.Testcontainers; import java.util.List; @@ -30,12 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @MockOpensearch public class DatabaseRepositoryUnitTest extends BaseUnitTest { - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @@ -50,13 +40,6 @@ public class DatabaseRepositoryUnitTest extends BaseUnitTest { @BeforeEach public void beforeEach() { - if (realmRepository.findAll().size() != 0) { - log.warn("data already initialized, skip."); - return; - } - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); imageRepository.save(IMAGE_1_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); containerRepository.save(CONTAINER_2_SIMPLE); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewIdxRepositoryIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewIdxRepositoryIntegrationTest.java index 350c95264644710fad7bc6274b44266670e80f05..fa1329dbd8a117fe100548851b4c372259ad4cf2 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewIdxRepositoryIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/repository/ViewIdxRepositoryIntegrationTest.java @@ -2,17 +2,13 @@ package at.tuwien.repository; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; -import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.database.ViewCreateDto; import at.tuwien.api.database.ViewDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.*; import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.ViewService; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.Rule; import org.junit.jupiter.api.BeforeEach; @@ -22,7 +18,6 @@ import org.junit.rules.Timeout; import org.opensearch.testcontainers.OpensearchContainer; 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.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -39,7 +34,6 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - @Log4j2 @Testcontainers @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @@ -48,15 +42,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @MockAmqp public class ViewIdxRepositoryIntegrationTest extends BaseUnitTest { - @Autowired - private UserRepository userRepository; - @Autowired private DatabaseRepository databaseRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @@ -101,9 +89,7 @@ public class ViewIdxRepositoryIntegrationTest extends BaseUnitTest { TABLE_1.setColumns(TABLE_1_COLUMNS); TABLE_2.setColumns(TABLE_2_COLUMNS); /* metadata database */ - realmRepository.save(REALM_DBREPO); imageRepository.save(IMAGE_1); - userRepository.save(USER_1); containerRepository.save(CONTAINER_1); databaseRepository.save(DATABASE_1_SIMPLE); tableRepository.saveAll(List.of(TABLE_1_SIMPLE, TABLE_2_SIMPLE)); 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 2b796e0be39f373f868fc732e5834889da676fbd..a3c11ad09bb70a2d1e34a7d91b01a7ce6a31d175 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 @@ -4,11 +4,7 @@ import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.entities.database.View; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.Rule; import org.junit.jupiter.api.BeforeEach; @@ -17,7 +13,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.rules.Timeout; 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; @@ -36,12 +31,6 @@ public class ViewRepositoryIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private ContainerRepository containerRepository; @@ -62,8 +51,6 @@ public class ViewRepositoryIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() { - realmRepository.save(REALM_DBREPO); - userRepository.saveAll(List.of(USER_1, USER_2)); imageRepository.save(IMAGE_1); containerRepository.saveAll(List.of(CONTAINER_1_SIMPLE, CONTAINER_2_SIMPLE)); databaseRepository.saveAll(List.of(DATABASE_1_SIMPLE, DATABASE_2_SIMPLE)); 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 244253a8ce1bc70c7c86e20b5a610a4a725b0a86..f4f32b3647629540ddd3bfe65f8fa00693aeae87 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 @@ -57,12 +57,6 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @Autowired private AccessService accessService; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Container @Autowired private MariaDBContainer<?> mariaDBContainer; @@ -70,11 +64,7 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() throws SQLException { /* metadata database */ - realmRepository.save(REALM_DBREPO); imageRepository.save(IMAGE_1); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); - userRepository.save(USER_3_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); MariaDbConfig.dropAllDatabases(CONTAINER_1); @@ -151,9 +141,9 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @ParameterizedTest @MethodSource("create_succeeds_parameters") protected <T extends Throwable> void create_succeeds(String test, AccessTypeDto accessTypeDto, AccessType access, - String username, UUID userId) - throws UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseNotFoundException, - DatabaseMalformedException { + String username, UUID userId) throws UserNotFoundException, + NotAllowedException, QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, + KeycloakRemoteException, AccessDeniedException { final DatabaseGiveAccessDto request = DatabaseGiveAccessDto.builder() .type(accessTypeDto) .username(username) @@ -171,8 +161,9 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { @ParameterizedTest @MethodSource("update_succeeds_parameters") protected void update_succeeds(String test, Long databaseId, AccessTypeDto accessTypeDto, AccessType access, - String username) throws UserNotFoundException, NotAllowedException, - QueryMalformedException, DatabaseNotFoundException, DatabaseMalformedException, NotAllowedException { + UUID userId) throws UserNotFoundException, QueryMalformedException, + DatabaseNotFoundException, DatabaseMalformedException, NotAllowedException, KeycloakRemoteException, + AccessDeniedException { final DatabaseModifyAccessDto request = DatabaseModifyAccessDto.builder() .type(accessTypeDto) .build(); @@ -181,7 +172,7 @@ public class AccessServiceIntegrationTest extends BaseUnitTest { databaseAccessRepository.save(DATABASE_1_USER_2_READ_ACCESS); /* test */ - accessService.update(databaseId, username, request); + accessService.update(databaseId, userId, request); final List<DatabaseAccess> response = databaseAccessRepository.findAll(); assertEquals(1, response.size()); assertEquals(access, response.get(0).getType()); @@ -191,36 +182,35 @@ 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, - String username) { + Long databaseId, AccessTypeDto accessTypeDto, UUID userId) { final DatabaseModifyAccessDto request = DatabaseModifyAccessDto.builder() .type(accessTypeDto) .build(); /* test */ assertThrows(expectedException, () -> { - accessService.update(databaseId, username, request); + accessService.update(databaseId, userId, request); }); } @ParameterizedTest @MethodSource("delete_fails_parameters") - protected <T extends Throwable> void delete_fails(String name, Class<T> expectedException, String username) { + protected <T extends Throwable> void delete_fails(String name, Class<T> expectedException, UUID userId) { /* test */ assertThrows(expectedException, () -> { - accessService.delete(DATABASE_1_ID, username); + accessService.delete(DATABASE_1_ID, userId); }); } @ParameterizedTest @MethodSource("delete_succeeds_parameters") - protected <T extends Throwable> void delete_succeeds(String name, String username) - throws UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseNotFoundException, - DatabaseMalformedException { + 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, username); + 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 87b8d4215c6da3f223e6f2a602888c6364731372..11eaf02da7944a12ec29e8023f2b06db52fa4156 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 @@ -10,7 +10,6 @@ import at.tuwien.entities.database.DatabaseAccess; import at.tuwien.exception.NotAllowedException; import at.tuwien.repository.mdb.DatabaseAccessRepository; import at.tuwien.repository.mdb.DatabaseRepository; -import at.tuwien.repository.mdb.UserRepository; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -36,9 +35,6 @@ public class AccessServiceUnitTest extends BaseUnitTest { @MockBean private DatabaseRepository databaseRepository; - @MockBean - private UserRepository userRepository; - @MockBean private DatabaseAccessRepository databaseAccessRepository; @@ -103,12 +99,10 @@ public class AccessServiceUnitTest extends BaseUnitTest { /* mock */ when(databaseRepository.findById(DATABASE_1_ID)) .thenReturn(Optional.of(DATABASE_1)); - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); /* test */ assertThrows(NotAllowedException.class, () -> { - accessService.update(DATABASE_1_ID, USER_1_USERNAME, request); + accessService.update(DATABASE_1_ID, USER_1_ID, request); }); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ContainerServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ContainerServiceIntegrationTest.java index 33da5f4952a0b25f4de7a24f9a98acae0d9d397f..9efb25050e5538a366d027d44742700a03fdd287 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ContainerServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ContainerServiceIntegrationTest.java @@ -8,8 +8,6 @@ import at.tuwien.entities.container.Container; import at.tuwien.exception.*; import at.tuwien.repository.mdb.ContainerRepository; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.mdb.RealmRepository; -import at.tuwien.repository.mdb.UserRepository; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -38,21 +36,12 @@ public class ContainerServiceIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ContainerService containerService; - @Autowired - private RealmRepository realmRepository; - @BeforeEach public void beforeEach() { /* mock data */ - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); imageRepository.save(IMAGE_1_SIMPLE); } @@ -163,7 +152,7 @@ public class ContainerServiceIntegrationTest extends BaseUnitTest { } @Test - public void remove_succeeds() throws ContainerStillRunningException, ContainerNotFoundException, ContainerAlreadyRemovedException { + public void remove_succeeds() throws ContainerNotFoundException { /* mock */ containerRepository.save(CONTAINER_1); 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 7d16fef0f8c4940716c44d4cf1ec79124caf0046..ac337d5d52ce749edd6572278fa1eb07ebbd58fd 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 @@ -11,8 +11,6 @@ import at.tuwien.config.EndpointConfig; import at.tuwien.entities.identifier.Identifier; import at.tuwien.exception.*; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.IdentifierIdxRepository; -import at.tuwien.service.impl.IdentifierServiceImpl; import org.apache.http.auth.BasicUserPrincipal; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,12 +65,6 @@ public class DataCiteIdentifierServiceIntegrationTest extends BaseUnitTest { @Autowired private IdentifierRepository identifierRepository; - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @MockBean @Qualifier("restTemplate") private RestTemplate restTemplate; @@ -80,17 +72,12 @@ public class DataCiteIdentifierServiceIntegrationTest extends BaseUnitTest { @MockBean(answer = Answers.RETURNS_SELF) private RestTemplateBuilder restTemplateBuilder; - @Autowired - private IdentifierServiceImpl identifierService; - @Autowired private IdentifierService dataCiteIdentifierService; @BeforeEach public void beforeEach() { - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1); imageRepository.save(IMAGE_1); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceUnitTest.java index 10e0306693a2a05638317aa5db15ec310d5214c2..169ad4d76f35a8d084c8010e38cdccce413895c2 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DataCiteIdentifierServiceUnitTest.java @@ -12,7 +12,6 @@ import at.tuwien.config.EndpointConfig; import at.tuwien.entities.identifier.Identifier; import at.tuwien.exception.*; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.IdentifierIdxRepository; import at.tuwien.service.impl.IdentifierServiceImpl; import org.apache.http.auth.BasicUserPrincipal; import org.junit.jupiter.api.BeforeEach; @@ -69,12 +68,6 @@ public class DataCiteIdentifierServiceUnitTest extends BaseUnitTest { @Autowired private IdentifierRepository identifierRepository; - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @MockBean @Qualifier("restTemplate") private RestTemplate restTemplate; @@ -90,9 +83,7 @@ public class DataCiteIdentifierServiceUnitTest extends BaseUnitTest { @BeforeEach public void beforeEach() { - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1); imageRepository.save(IMAGE_1); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); @@ -105,7 +96,6 @@ public class DataCiteIdentifierServiceUnitTest extends BaseUnitTest { IdentifierRequestException, ViewNotFoundException, QueryStoreException, DatabaseConnectionException, ImageNotSupportedException { final Principal principal = new BasicUserPrincipal(USER_1_USERNAME); - final String bearer = "Bearer abcxyz"; final DataCiteBody<DataCiteDoi> response = new DataCiteBody<>(new DataCiteData<>(null, "dois", new DataCiteDoi(IDENTIFIER_1_DOI_NOT_NULL))); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceComponentTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceComponentTest.java index 74a6d4e2d83d8af1928e43731038971a89157e69..dd6cf5370826ead3fe585033e413a9e60f2eb592 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceComponentTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/DatabaseServiceComponentTest.java @@ -9,10 +9,8 @@ import at.tuwien.config.MariaDbConfig; import at.tuwien.entities.database.Database; import at.tuwien.repository.mdb.ContainerRepository; import at.tuwien.repository.mdb.DatabaseRepository; -import at.tuwien.repository.mdb.UserRepository; import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.MariaDbServiceImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,9 +39,6 @@ import static org.mockito.Mockito.when; @MockOpensearch public class DatabaseServiceComponentTest extends BaseUnitTest { - @MockBean - private UserRepository userRepository; - @MockBean private ContainerRepository containerRepository; @@ -84,8 +79,6 @@ public class DatabaseServiceComponentTest extends BaseUnitTest { throws Exception { /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); when(containerRepository.findById(CONTAINER_1_ID)) .thenReturn(Optional.of(CONTAINER_1)); when(databaseRepository.save(any(Database.class))) 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 9fe07441057320555f7cf4ee8b7231e10cad4a08..afa64ac6ad6280cde939998173d3d7eb135a759b 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 @@ -13,7 +13,6 @@ import at.tuwien.exception.*; import at.tuwien.repository.mdb.*; import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.MariaDbServiceImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -54,12 +53,6 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @Autowired private MariaDbServiceImpl databaseService; @@ -74,10 +67,6 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { public void beforeEach() throws SQLException { /* metadata database */ imageRepository.save(IMAGE_1); - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1); - userRepository.save(USER_2); - userRepository.save(USER_3); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_3_SIMPLE); MariaDbConfig.dropAllDatabases(CONTAINER_1); @@ -235,7 +224,8 @@ public class DatabaseServiceIntegrationTest extends BaseUnitTest { } @Test - public void transfer_succeeds() throws DatabaseNotFoundException, UserNotFoundException, SQLException { + public void transfer_succeeds() throws DatabaseNotFoundException, UserNotFoundException, SQLException, + KeycloakRemoteException, AccessDeniedException { final DatabaseTransferDto request = DatabaseTransferDto.builder() .username(USER_2_USERNAME) .build(); @@ -256,7 +246,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); + mariaDbConfig.mockGrantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); /* test */ final Long response = MariaDbConfig.mockSystemQueryInsert(DATABASE_3, query); @@ -276,7 +266,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); + mariaDbConfig.mockGrantUserPermissions(CONTAINER_1, DATABASE_3, USER_1_USERNAME); /* test */ final Long queryId = MariaDbConfig.mockSystemQueryInsert(DATABASE_3, QUERY_4_STATEMENT, username, password); @@ -286,7 +276,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); + mariaDbConfig.mockGrantUserPermissions(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 f9c76ae4c5cf0f20c0851236c851e9f0a542892e..c63a62509f0a289171ce4ead01963b3ee2aed996 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 @@ -7,16 +7,10 @@ import at.tuwien.api.database.DatabaseCreateDto; import at.tuwien.entities.container.Container; import at.tuwien.entities.container.image.ContainerImage; import at.tuwien.entities.database.Database; -import at.tuwien.exception.ContainerNotFoundException; -import at.tuwien.exception.DatabaseNotFoundException; -import at.tuwien.exception.ImageNotSupportedException; -import at.tuwien.exception.UserNotFoundException; +import at.tuwien.exception.*; import at.tuwien.repository.mdb.ContainerRepository; import at.tuwien.repository.mdb.DatabaseRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.MariaDbServiceImpl; -import at.tuwien.service.impl.RabbitMqServiceImpl; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -106,7 +100,7 @@ public class DatabaseServiceUnitTest extends BaseUnitTest { } @Test - public void create_notFound_fails() throws UserNotFoundException { + public void create_notFound_fails() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { final DatabaseCreateDto request = DatabaseCreateDto.builder() .cid(CONTAINER_1_ID) .name(DATABASE_1_NAME) @@ -114,7 +108,7 @@ public class DatabaseServiceUnitTest extends BaseUnitTest { /* mock */ when(userService.findByUsername(USER_1_USERNAME)) - .thenReturn(USER_1); + .thenReturn(USER_1_DTO); when(containerRepository.findById(CONTAINER_1_ID)) .thenReturn(Optional.empty()); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceIntegrationTest.java index 5279541a4030fdc20f294d718894b2e24706a03a..74802cc49d36ca0ae57d1d604a4cf011fd86a340 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/IdentifierServiceIntegrationTest.java @@ -3,7 +3,6 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.api.database.query.QueryDto; -import at.tuwien.api.identifier.IdentifierSaveDto; import at.tuwien.entities.identifier.Identifier; import at.tuwien.entities.identifier.IdentifierDescription; import at.tuwien.entities.identifier.IdentifierTitle; @@ -73,18 +72,12 @@ public class IdentifierServiceIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ViewRepository viewRepository; @Autowired private TableRepository tableRepository; - @Autowired - private RealmRepository realmRepository; - @Container private static final OpensearchContainer opensearchContainer = new OpensearchContainer(DockerImageName.parse("opensearchproject/opensearch:2.8.0")); @@ -100,12 +93,7 @@ public class IdentifierServiceIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() { imageRepository.save(IMAGE_1_SIMPLE); - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); - userRepository.save(USER_3_SIMPLE); - userRepository.save(USER_4_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); containerRepository.save(CONTAINER_2_SIMPLE); @@ -429,7 +417,6 @@ public class IdentifierServiceIntegrationTest extends BaseUnitTest { /* test */ identifierService.delete(IDENTIFIER_1_ID); - assertTrue(userRepository.findById(IDENTIFIER_1_CREATED_BY).isPresent()) /* no cascade of delete */; /* open search database */ assertFalse(identifierIdxRepository.existsById(IDENTIFIER_1_ID)); } 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 3ced0a81a46e1d82d5a6424566c3e715e024bd3a..ed996b9ca1eeb383d80f0e86451c2e013c34e38b 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 { + ImageNotSupportedException, KeycloakRemoteException, AccessDeniedException { /* 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); + .thenReturn(USER_1_DTO); 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/ImageServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceIntegrationTest.java index cee2f67be96ed19d0dd2c8035e631acc628474d2..d80f6787e49e6a97ea5e95f1a7e7e8cc058e3c88 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceIntegrationTest.java @@ -8,8 +8,6 @@ import at.tuwien.exception.ImageAlreadyExistsException; import at.tuwien.exception.ImageNotFoundException; import at.tuwien.repository.mdb.ContainerRepository; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.ImageServiceImpl; import lombok.extern.log4j.Log4j2; import org.apache.http.auth.BasicUserPrincipal; @@ -18,7 +16,6 @@ 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.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -40,15 +37,11 @@ public class ImageServiceIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ContainerRepository containerRepository; @BeforeEach public void beforeEach() { - userRepository.save(USER_1_SIMPLE); imageRepository.save(IMAGE_1_SIMPLE); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceUnitTest.java index cc80c82790acfa52de2c251d3e85e0708df7bb4a..2e632909a0f065cbc351ce44f1ca578673ac9bdc 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ImageServiceUnitTest.java @@ -9,7 +9,6 @@ import at.tuwien.entities.container.image.ContainerImage; import at.tuwien.exception.ImageAlreadyExistsException; import at.tuwien.exception.ImageNotFoundException; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.ImageServiceImpl; import jakarta.persistence.EntityNotFoundException; import jakarta.validation.ConstraintViolationException; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/LicenseServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/LicenseServiceIntegrationTest.java index 3d70823bf9da4ec5ea016f6fa689c70a7ff2bc0f..98b90e73f4d998a9bd6b5714d0ee3ba5bdf7a634 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/LicenseServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/LicenseServiceIntegrationTest.java @@ -6,15 +6,12 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.entities.database.License; import at.tuwien.exception.LicenseNotFoundException; import at.tuwien.repository.mdb.LicenseRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; -import com.rabbitmq.client.Channel; 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; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.MariaDBContainer; import org.testcontainers.junit.jupiter.Container; 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 f834287b8a36020dc30975d68eeb292c22164e75..86767db28dc5dc51484371beab39f0d5c1af2f83 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 @@ -1,4 +1,3 @@ - package at.tuwien.service; import at.tuwien.BaseUnitTest; @@ -87,7 +86,7 @@ public class MessageQueueServiceIntegrationTest extends BaseUnitTest { public void createUser_succeeds() throws BrokerVirtualHostCreationException { /* test */ - messageQueueService.createUser(USER_1); + messageQueueService.createUser(USER_1_USERNAME); } @Test @@ -169,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); + messageQueueService.updatePermissions(USER_1_DTO); return amqpUtils.getPermissions(USER_1_USERNAME); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceUnitTest.java index abff6e0cc3b792ad3140edbda5dbadb59a77cea3..8f533059f5a7d7b43e8c502ae2cb2a7fe1df53fa 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MessageQueueServiceUnitTest.java @@ -6,7 +6,6 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.exception.AmqpException; import at.tuwien.gateway.BrokerServiceGateway; import at.tuwien.repository.mdb.DatabaseRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.RabbitMqServiceImpl; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceIntegrationTest.java index a2781c575136933c0228e7ae2412a4bd7ef26314..3116d2ff9bed8887b760ae91bf8000f29d56f96e 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceIntegrationTest.java @@ -3,26 +3,21 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.identifier.Identifier; import at.tuwien.oaipmh.OaiErrorType; import at.tuwien.oaipmh.OaiListIdentifiersParameters; import at.tuwien.oaipmh.OaiRecordParameters; import at.tuwien.exception.IdentifierNotFoundException; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.IdentifierIdxRepository; 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; 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.springframework.transaction.annotation.Transactional; -import java.util.List; - import static org.junit.jupiter.api.Assertions.*; @Log4j2 @@ -45,12 +40,6 @@ public class MetadataServiceIntegrationTest extends BaseUnitTest { @Autowired private LicenseRepository licenseRepository; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private IdentifierRepository identifierRepository; @@ -61,9 +50,7 @@ public class MetadataServiceIntegrationTest extends BaseUnitTest { public void beforeEach() { /* metadata database */ imageRepository.save(IMAGE_1_SIMPLE); - realmRepository.save(REALM_DBREPO); licenseRepository.save(LICENSE_1); - userRepository.save(USER_1_SIMPLE); containerRepository.save(CONTAINER_1); databaseRepository.save(DATABASE_1_SIMPLE); identifierRepository.save(IDENTIFIER_1); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceUnitTest.java index 7d999d17714dc597eee50b9ef84b17b9ee482211..1f06ad3c38e7490001c2e9ec52ba0a1a699565cb 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/MetadataServiceUnitTest.java @@ -16,7 +16,6 @@ import at.tuwien.gateway.CrossrefGateway; import at.tuwien.gateway.OrcidGateway; import at.tuwien.gateway.RorGateway; import at.tuwien.repository.mdb.IdentifierRepository; -import at.tuwien.repository.sdb.IdentifierIdxRepository; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/PersistenceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/PersistenceIntegrationTest.java index ee290b755870979c58bac856453f5c6c5e8c8f28..74a2ee5ca9c47ac2ec3eb1d91c076033addc59c4 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/PersistenceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/PersistenceIntegrationTest.java @@ -5,8 +5,6 @@ import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.exception.ImageNotFoundException; import at.tuwien.repository.mdb.ImageRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.ImageServiceImpl; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; @@ -14,7 +12,6 @@ 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.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -34,12 +31,8 @@ public class PersistenceIntegrationTest extends BaseUnitTest { @Autowired private ImageRepository imageRepository; - @Autowired - private UserRepository userRepository; - @BeforeEach public void beforeEach() { - userRepository.save(USER_1_SIMPLE); imageRepository.save(IMAGE_1_SIMPLE); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryServiceIntegrationTest.java index 70806bde80d0b6fc543a06abbd1085ce59beaf5b..c08785afeddff8e3768e06c7e7c03981da29ef52 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryServiceIntegrationTest.java @@ -9,12 +9,8 @@ import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.api.database.table.TableCsvDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.querystore.Query; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.MariaDBContainer; @@ -46,7 +41,6 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.*; - @Log4j2 @Testcontainers @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @@ -60,18 +54,12 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Autowired private DatabaseRepository databaseRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @Autowired private ContainerRepository containerRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ViewRepository viewRepository; @@ -94,8 +82,6 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { MariaDbConfig.createInitDatabase(CONTAINER_1, DATABASE_2); MariaDbConfig.createInitDatabase(CONTAINER_1, DATABASE_1); /* metadata database */ - realmRepository.save(REALM_DBREPO); - userRepository.saveAll(List.of(USER_1, USER_2)); imageRepository.save(IMAGE_1); containerRepository.saveAll(List.of(CONTAINER_1_SIMPLE, CONTAINER_2_SIMPLE)); databaseRepository.saveAll(List.of(DATABASE_1_SIMPLE, DATABASE_2_SIMPLE)); @@ -303,7 +289,8 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_succeeds() throws DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, - QueryStoreException, ColumnParseException, InterruptedException { + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT n.`firstname`, n.`lastname`, n.`birth`, n.`reminder`, z.`animal_name`, z.`legs` FROM `likes` l JOIN `names` n ON l.`name_id` = n.`id` JOIN `mock_view` z ON z.`id` = l.`zoo_id`") .build(); @@ -338,8 +325,9 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_withoutNullField_succeeds() throws DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, - UserNotFoundException, QueryStoreException, ColumnParseException, InterruptedException { + DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT `location`, `lng` FROM `weather_location` WHERE `lat` IS NULL") .build(); @@ -358,8 +346,8 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_withoutNullField2_succeeds() throws DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, - UserNotFoundException, QueryStoreException, ColumnParseException, InterruptedException { + DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT `location` FROM `weather_location` WHERE `lat` IS NULL") .build(); @@ -378,8 +366,9 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_withNullField_succeeds() throws DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, - UserNotFoundException, QueryStoreException, ColumnParseException, InterruptedException { + DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT `lat`, `lng` FROM `weather_location` WHERE `lat` IS NULL") .build(); @@ -394,8 +383,8 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_aliases_succeeds() throws DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, - UserNotFoundException, QueryStoreException, ColumnParseException, InterruptedException { + DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT aus.location as a, loc.location from weather_aus aus, weather_location loc") .build(); @@ -428,8 +417,9 @@ public class QueryServiceIntegrationTest extends BaseUnitTest { @Test public void execute_aliasesWithDatabaseName_succeeds() throws DatabaseConnectionException, TableMalformedException, - DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, - UserNotFoundException, QueryStoreException, ColumnParseException, InterruptedException { + DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, UserNotFoundException, + QueryStoreException, ColumnParseException, InterruptedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT aus.location as a, loc.location from weather.weather_aus aus, weather.weather_location loc") .build(); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryStoreServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryStoreServiceIntegrationTest.java index 14ae56a9670e004c595e2d8bfc66f0edc3dbf9d6..bb1da63e372a57b853cd633687286c047c406f6f 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryStoreServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueryStoreServiceIntegrationTest.java @@ -6,18 +6,15 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.config.MariaDbConfig; import at.tuwien.exception.*; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.DatabaseIdxRepository; import at.tuwien.service.impl.HibernateConnector; import at.tuwien.service.impl.QueryStoreServiceImpl; import com.mchange.v2.c3p0.ComboPooledDataSource; -import com.rabbitmq.client.Channel; 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; 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; @@ -36,12 +33,6 @@ import java.sql.SQLException; @MockOpensearch public class QueryStoreServiceIntegrationTest extends BaseUnitTest { - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @Autowired private ContainerRepository containerRepository; @@ -61,8 +52,6 @@ public class QueryStoreServiceIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() throws SQLException { /* metadata database */ - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1); imageRepository.save(IMAGE_1); containerRepository.save(CONTAINER_1_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueueServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueueServiceIntegrationTest.java index 2e074dec070bb164884b8c25678b1021ec3b70b7..de4146b122d441561d20c67c48efba9cdf4780be 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueueServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/QueueServiceIntegrationTest.java @@ -2,7 +2,6 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.amqp.RabbitMqConsumer; -import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.amqp.ConsumerDto; import at.tuwien.api.database.table.TableCsvDto; @@ -15,7 +14,6 @@ import at.tuwien.gateway.BrokerServiceGateway; import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.DatabaseRepository; import at.tuwien.repository.mdb.TableRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.client.*; import lombok.extern.log4j.Log4j2; diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RealmServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RealmServiceIntegrationTest.java deleted file mode 100644 index 0337b4b0640db6c189909bc33df425edec0e7fa7..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RealmServiceIntegrationTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.BaseUnitTest; -import at.tuwien.annotations.MockAmqp; -import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.user.Realm; -import at.tuwien.exception.RealmNotFoundException; -import at.tuwien.repository.mdb.RealmRepository; -import at.tuwien.repository.sdb.UserIdxRepository; -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; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -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.test.annotation.DirtiesContext; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.*; - -@Log4j2 -@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) -@SpringBootTest -@ExtendWith(SpringExtension.class) -@MockAmqp -@MockOpensearch -public class RealmServiceIntegrationTest extends BaseUnitTest { - - @Autowired - private RealmRepository realmRepository; - - @Autowired - private RealmService realmService; - - @BeforeEach - public void beforeEach() { - realmRepository.save(REALM_DBREPO); - } - - @Test - public void find_succeeds() throws RealmNotFoundException { - - /* test */ - final Realm response = realmService.find(REALM_DBREPO_NAME); - assertNotNull(response); - assertEquals(REALM_DBREPO_ID, response.getId()); - assertEquals(REALM_DBREPO_NAME, response.getName()); - assertEquals(REALM_DBREPO_ENABLED, response.getEnabled()); - } - - @Test - public void find_fails() { - - /* test */ - assertThrows(RealmNotFoundException.class, () -> { - realmService.find("shadow"); - }); - } -} diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RoleServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RoleServiceIntegrationTest.java deleted file mode 100644 index 024e1eef9aad8b02fd287e640fd8f4c97f11433d..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/RoleServiceIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.BaseUnitTest; -import at.tuwien.annotations.MockAmqp; -import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.user.Role; -import at.tuwien.exception.RoleNotFoundException; -import at.tuwien.repository.mdb.RoleRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.UserIdxRepository; -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; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -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.test.annotation.DirtiesContext; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.*; - -@Log4j2 -@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) -@SpringBootTest -@ExtendWith(SpringExtension.class) -@MockAmqp -@MockOpensearch -public class RoleServiceIntegrationTest extends BaseUnitTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private RoleRepository roleRepository; - - @Autowired - private RoleService roleService; - - @BeforeEach - public void beforeEach() { - userRepository.save(USER_1_SIMPLE); - roleRepository.save(ROLE_DEFAULT_RESEARCHER_ROLES); - } - - @Test - public void find_succeeds() throws RoleNotFoundException { - - /* test */ - final Role response = roleService.find(ROLE_DEFAULT_RESEARCHER_ROLES_NAME); - assertNotNull(response); - assertEquals(ROLE_DEFAULT_RESEARCHER_ROLES_ID, response.getId()); - assertEquals(ROLE_DEFAULT_RESEARCHER_ROLES_NAME, response.getName()); - } - - @Test - public void find_fails() { - - /* test */ - assertThrows(RoleNotFoundException.class, () -> { - roleService.find("1role2rulethemall"); - }); - } -} diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationModifyTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationModifyTest.java index 5b3cc99f42a64d3804943f3854fb5c2bf61c4a6e..4597bb22e9c34e3d09954ba37e302aa62fb10ea5 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationModifyTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationModifyTest.java @@ -8,12 +8,8 @@ import at.tuwien.api.database.query.QueryPersistDto; import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.querystore.Query; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,7 +18,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.MariaDBContainer; @@ -50,15 +45,9 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Autowired private TableRepository tableRepository; - @Autowired - private UserRepository userRepository; - @Autowired private DatabaseRepository databaseRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @@ -85,9 +74,7 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { TABLE_1.setColumns(TABLE_1_COLUMNS); TABLE_2.setColumns(TABLE_2_COLUMNS); /* metadata database */ - realmRepository.save(REALM_DBREPO); imageRepository.save(IMAGE_1); - userRepository.saveAll(List.of(USER_1, USER_2, USER_3, USER_4, USER_5)); containerRepository.save(CONTAINER_1); databaseRepository.save(DATABASE_1_SIMPLE); tableRepository.saveAll(List.of(TABLE_1_SIMPLE, TABLE_2_SIMPLE)); @@ -97,7 +84,8 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void insert_same_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, - DatabaseNotFoundException, ImageNotSupportedException, SQLException { + DatabaseNotFoundException, ImageNotSupportedException, SQLException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_2_STATEMENT) .build(); @@ -115,7 +103,7 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_different_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException { + QueryMalformedException, ColumnParseException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto mock = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .build(); @@ -134,7 +122,7 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_same_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException { + QueryMalformedException, ColumnParseException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .build(); @@ -151,7 +139,8 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_notPersisted_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException, SQLException { + QueryMalformedException, ColumnParseException, SQLException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .build(); @@ -166,7 +155,7 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_emptyResult_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException { + QueryMalformedException, ColumnParseException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT `id`, `date`, `location`, `mintemp`, `rainfall` FROM `weather_aus` WHERE `location` = 'Vienna'") .build(); @@ -179,7 +168,7 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_emptyResultTwice_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException { + QueryMalformedException, ColumnParseException, KeycloakRemoteException, AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement("SELECT `id`, `date`, `location`, `mintemp`, `rainfall` FROM `weather_aus` WHERE `location` = 'Vienna'") .build(); @@ -195,7 +184,8 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void execute_dataChangeSameQuery_succeeds() throws UserNotFoundException, QueryStoreException, DatabaseConnectionException, TableMalformedException, DatabaseNotFoundException, ImageNotSupportedException, - QueryMalformedException, ColumnParseException, SQLException { + QueryMalformedException, ColumnParseException, SQLException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .build(); @@ -271,7 +261,8 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void insert_timestamp_succeeds() throws UserNotFoundException, QueryStoreException, - DatabaseConnectionException, DatabaseNotFoundException, ImageNotSupportedException { + DatabaseConnectionException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .timestamp(Instant.now().plus(1, ChronoUnit.SECONDS)) @@ -283,7 +274,8 @@ public class StoreServiceIntegrationModifyTest extends BaseUnitTest { @Test public void insert_anonymous_succeeds() throws UserNotFoundException, QueryStoreException, - DatabaseConnectionException, DatabaseNotFoundException, ImageNotSupportedException { + DatabaseConnectionException, DatabaseNotFoundException, ImageNotSupportedException, KeycloakRemoteException, + AccessDeniedException { final ExecuteStatementDto request = ExecuteStatementDto.builder() .statement(QUERY_1_STATEMENT) .build(); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationReadTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationReadTest.java index 6a87569d7e050ba889ca764abc37b42080f4daec..2e4a3251b45c3350cb34e1f886a0155a0aaef63c 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationReadTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/StoreServiceIntegrationReadTest.java @@ -6,13 +6,9 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.config.MariaDbConfig; import at.tuwien.config.MariaDbContainerConfig; import at.tuwien.exception.*; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.querystore.Query; import at.tuwien.repository.mdb.DatabaseRepository; import at.tuwien.repository.mdb.TableRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.apache.http.auth.BasicUserPrincipal; import org.junit.jupiter.api.BeforeAll; @@ -50,9 +46,6 @@ public class StoreServiceIntegrationReadTest extends BaseUnitTest { @MockBean private TableRepository tableRepository; - @MockBean - private UserRepository userRepository; - @MockBean private DatabaseRepository databaseRepository; @@ -73,7 +66,6 @@ public class StoreServiceIntegrationReadTest extends BaseUnitTest { @BeforeEach public void beforeEach() { /* metadata database */ - userRepository.save(USER_5); DATABASE_1.setTables(List.of(TABLE_1, TABLE_2, TABLE_3, TABLE_7)); DATABASE_1.setViews(List.of(VIEW_3)); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationReadTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationReadTest.java index 950044d5b2950a43d230b7345189be51fde1c696..31798e89caa3daca7d160a0c76be4cca63436fd6 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationReadTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationReadTest.java @@ -7,21 +7,13 @@ import at.tuwien.api.database.table.TableHistoryDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.entities.database.table.Table; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.*; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; -import org.junit.jupiter.api.BeforeAll; 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; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -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.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.annotation.DirtiesContext; @@ -32,11 +24,9 @@ import org.testcontainers.junit.jupiter.Testcontainers; import java.sql.SQLException; import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; @Log4j2 @Testcontainers @@ -56,12 +46,6 @@ public class TableServiceIntegrationReadTest extends BaseUnitTest { @Autowired private ContainerRepository containerRepository; - @Autowired - private RealmRepository realmRepository; - - @Autowired - private UserRepository userRepository; - @Autowired private DatabaseRepository databaseRepository; @@ -75,9 +59,6 @@ public class TableServiceIntegrationReadTest extends BaseUnitTest { @BeforeEach public void beforeEach() throws SQLException { imageRepository.save(IMAGE_1); - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); containerRepository.save(CONTAINER_2_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationWriteTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationWriteTest.java index 7887379dae80c6b3bf8f99c183594e6f330ecc9d..fbab8d9570e130bb906b350899ecc6d68d493b0f 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationWriteTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceIntegrationWriteTest.java @@ -1,4 +1,3 @@ - package at.tuwien.service; import at.tuwien.BaseUnitTest; @@ -15,11 +14,8 @@ import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.exception.*; import at.tuwien.mapper.TableMapper; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ConceptIdxRepository; import at.tuwien.repository.sdb.TableColumnIdxRepository; import at.tuwien.repository.sdb.TableIdxRepository; -import at.tuwien.repository.sdb.UnitIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -78,12 +74,6 @@ public class TableServiceIntegrationWriteTest extends BaseUnitTest { @Autowired private TableService tableService; - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - @Autowired private TableMapper tableMapper; @@ -97,9 +87,6 @@ public class TableServiceIntegrationWriteTest extends BaseUnitTest { MariaDbConfig.createInitDatabase(CONTAINER_1, DATABASE_1); /* metadata database */ imageRepository.save(IMAGE_1); - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1_SIMPLE); - userRepository.save(USER_2_SIMPLE); containerRepository.save(CONTAINER_1_SIMPLE); containerRepository.save(CONTAINER_2_SIMPLE); databaseRepository.save(DATABASE_1_SIMPLE); @@ -470,7 +457,6 @@ public class TableServiceIntegrationWriteTest extends BaseUnitTest { /* test */ tableService.deleteTable(DATABASE_1_ID, TABLE_1_ID); - assertTrue(userRepository.findById(TABLE_1_CREATED_BY).isPresent()); assertTrue(databaseRepository.findById(TABLE_1_DATABASE_ID).isPresent()); } diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceUnitTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceUnitTest.java index 50950cfbc506de2d83ea9e8a5d9cbbd61ee1fae2..a051dd2dbfab922f306b5c0c9b0b401e21ee79a8 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceUnitTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/TableServiceUnitTest.java @@ -6,11 +6,7 @@ import at.tuwien.annotations.MockOpensearch; import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.exception.DatabaseNotFoundException; import at.tuwien.exception.TableNotFoundException; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.TableRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,7 +25,6 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; - @Log4j2 @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserAttributeServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserAttributeServiceIntegrationTest.java deleted file mode 100644 index 4efd9fc8e946a344838e7bc7c5a7c7ee39265f68..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/UserAttributeServiceIntegrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.BaseUnitTest; -import at.tuwien.annotations.MockAmqp; -import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.user.UserAttribute; -import at.tuwien.exception.UserAttributeNotFoundException; -import at.tuwien.repository.mdb.UserAttributeRepository; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.UserIdxRepository; -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; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -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.test.annotation.DirtiesContext; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; - -@Log4j2 -@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) -@SpringBootTest -@ExtendWith(SpringExtension.class) -@MockAmqp -@MockOpensearch -public class UserAttributeServiceIntegrationTest extends BaseUnitTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserAttributeRepository userAttributeRepository; - - @Autowired - private UserAttributeService userAttributeService; - - @BeforeEach - public void beforeEach() { - userRepository.save(USER_1_SIMPLE); - userAttributeRepository.saveAll(USER_1_ATTRIBUTES); - userRepository.save(USER_2_SIMPLE); - } - - @Test - public void find_succeeds() throws UserAttributeNotFoundException { - - /* test */ - final UserAttribute response = userAttributeService.find(USER_1_ID, "theme_dark"); - assertNotNull(response); - } - - @Test - public void find_fails() { - - /* test */ - assertThrows(UserAttributeNotFoundException.class, () -> { - userAttributeService.find(USER_2_ID, "theme_dark"); - }); - } - - @Test - public void create_succeeds() { - final UserAttribute request = UserAttribute.builder() - .id(UUID.randomUUID()) - .userId(USER_2_ID) - .name("debug") - .value("yes") - .build(); - - /* test */ - final UserAttribute response = userAttributeService.create(request); - assertNotNull(response); - assertEquals("debug", response.getName()); - assertEquals("yes", response.getValue()); - } - - @Test - public void update_succeeds() throws UserAttributeNotFoundException { - - /* test */ - final UserAttribute response = userAttributeService.update(USER_1_ID, "affiliation", "NASA"); - assertNotNull(response); - assertEquals("affiliation", response.getName()); - assertEquals("NASA", response.getValue()); - } - - @Test - public void update_fails() { - - /* test */ - assertThrows(UserAttributeNotFoundException.class, () -> { - userAttributeService.update(USER_2_ID, "affiliation", "NASA"); - }); - } -} 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 5f86ca2204a5989eb26cd00bafd84a83e02ea6b0..a45007cafb1bd004ce11d248639b5ed235fe1b30 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 @@ -4,20 +4,9 @@ import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.auth.SignupRequestDto; -import at.tuwien.api.user.UserPasswordDto; -import at.tuwien.api.user.UserThemeSetDto; -import at.tuwien.api.user.UserUpdateDto; -import at.tuwien.entities.user.User; -import at.tuwien.entities.user.UserAttribute; -import at.tuwien.exception.UserAlreadyExistsException; -import at.tuwien.exception.UserAttributeNotFoundException; -import at.tuwien.exception.UserEmailAlreadyExistsException; -import at.tuwien.exception.UserNotFoundException; -import at.tuwien.repository.mdb.RealmRepository; -import at.tuwien.repository.mdb.RoleRepository; -import at.tuwien.repository.mdb.UserRepository; +import at.tuwien.api.user.*; +import at.tuwien.exception.*; 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; @@ -30,7 +19,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @@ -43,30 +31,14 @@ import static org.junit.jupiter.api.Assertions.*; @MockOpensearch public class UserServiceIntegrationTest extends BaseUnitTest { - @Autowired - private UserRepository userRepository; - - @Autowired - private RealmRepository realmRepository; - - @Autowired - private RoleRepository roleRepository; - @Autowired private UserService userService; - @BeforeEach - public void beforeEach() { - realmRepository.save(REALM_DBREPO); - userRepository.save(USER_1); - roleRepository.save(ROLE_DEFAULT_RESEARCHER_ROLES); - } - @Test - public void findByUsername_succeeds() throws UserNotFoundException { + public void findByUsername_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { /* test */ - final User response = userService.findByUsername(USER_1_USERNAME); + final UserDto response = userService.findByUsername(USER_1_USERNAME); assertEquals(USER_1_ID, response.getId()); assertEquals(USER_1_USERNAME, response.getUsername()); } @@ -81,15 +53,16 @@ public class UserServiceIntegrationTest extends BaseUnitTest { } @Test - public void findAll_succeeds() { + public void findAll_succeeds() throws KeycloakRemoteException, AccessDeniedException { /* test */ - final List<User> response = userService.findAll(); + final List<UserBriefDto> response = userService.findAll(); assertEquals(1, response.size()); } @Test - public void create_succeeds() throws UserAlreadyExistsException { + public void create_succeeds() throws UserAlreadyExistsException, UserNotFoundException, KeycloakRemoteException, + AccessDeniedException { final SignupRequestDto request = SignupRequestDto.builder() .username(USER_2_USERNAME) .password(USER_2_PASSWORD) @@ -97,8 +70,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { .build(); /* test */ - final User response = userService.create(request, REALM_DBREPO); - assertEquals(0, response.getRoles().size()); + final UserDto response = userService.create(request); } @Test @@ -111,7 +83,7 @@ public class UserServiceIntegrationTest extends BaseUnitTest { /* test */ assertThrows(DataIntegrityViolationException.class, () -> { - userService.create(request, REALM_DBREPO); + userService.create(request); }); } @@ -125,13 +97,14 @@ public class UserServiceIntegrationTest extends BaseUnitTest { /* test */ assertThrows(DataIntegrityViolationException.class, () -> { - userService.create(request, REALM_DBREPO); + userService.create(request); }); } @Test @Transactional - public void modify_succeeds() throws UserNotFoundException, UserAttributeNotFoundException { + public void modify_succeeds() throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, + AccessDeniedException { final UserUpdateDto request = UserUpdateDto.builder() .firstname(USER_1_FIRSTNAME) .lastname(USER_1_LASTNAME) @@ -140,17 +113,12 @@ public class UserServiceIntegrationTest extends BaseUnitTest { .build(); /* test */ - final User response = userService.modify(USER_1_ID, request); + final UserDto 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(3, response.getAttributes().size()); - final Optional<UserAttribute> affiliation = response.getAttributes().stream().filter(a -> a.getName().equals("affiliation")).findFirst(); - assertTrue(affiliation.isPresent()); - assertEquals("NASA", affiliation.get().getValue()); - final Optional<UserAttribute> orcid = response.getAttributes().stream().filter(a -> a.getName().equals("orcid")).findFirst(); - assertTrue(orcid.isPresent()); - assertNull(orcid.get().getValue()); + assertEquals("NASA", response.getAttributes().getAffiliation()); + assertNull(response.getAttributes().getOrcid()); } @Test @@ -169,14 +137,13 @@ public class UserServiceIntegrationTest extends BaseUnitTest { } @Test - public void updatePassword_succeeds() throws UserNotFoundException { + public void updatePassword_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { final UserPasswordDto request = UserPasswordDto.builder() .password(USER_1_PASSWORD) .build(); /* test */ - final User response = userService.updatePassword(USER_1_ID, request); - assertEquals(1, response.getCredentials().size()); + userService.updatePassword(USER_1_ID, request); } @Test @@ -193,15 +160,15 @@ public class UserServiceIntegrationTest extends BaseUnitTest { @Test @Transactional - public void toggleTheme_succeeds() throws UserNotFoundException, UserAttributeNotFoundException { + public void toggleTheme_succeeds() throws UserNotFoundException, UserAttributeNotFoundException, + KeycloakRemoteException, AccessDeniedException { final UserThemeSetDto request = UserThemeSetDto.builder() .themeDark(true) .build(); /* test */ - final User response = userService.toggleTheme(USER_1_ID, request); + final UserDto response = userService.toggleTheme(USER_1_ID, request); assertNotNull(response.getAttributes()); - assertEquals(3, response.getAttributes().size()); } @Test @@ -217,10 +184,10 @@ public class UserServiceIntegrationTest extends BaseUnitTest { } @Test - public void find_succeeds() throws UserNotFoundException { + public void find_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { /* test */ - final User user = userService.find(USER_1_ID); + final UserDto user = userService.find(USER_1_ID); assertEquals(USER_1_ID, user.getId()); } 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 13ad878a8fb0a9f1126266c4801eae7e09da7f29..c6cb1398ed2e7e80b2b448a2e3572e0a0d71df35 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,22 +3,18 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; import at.tuwien.annotations.MockOpensearch; -import at.tuwien.entities.user.User; +import at.tuwien.api.user.UserDto; +import at.tuwien.exception.AccessDeniedException; +import at.tuwien.exception.KeycloakRemoteException; import at.tuwien.exception.UserNotFoundException; -import at.tuwien.repository.mdb.UserRepository; -import at.tuwien.repository.sdb.IdentifierIdxRepository; 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.Optional; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) @SpringBootTest @@ -26,21 +22,14 @@ import static org.mockito.Mockito.when; @MockOpensearch public class UserServiceUnitTest extends BaseUnitTest { - @MockBean - private UserRepository userRepository; - @Autowired private UserService userService; @Test - public void findByUsername_succeeds() throws UserNotFoundException { - - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.of(USER_1)); + public void findByUsername_succeeds() throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { /* test */ - final User response = userService.findByUsername(USER_1_USERNAME); + final UserDto response = userService.findByUsername(USER_1_USERNAME); assertEquals(USER_1_ID, response.getId()); assertEquals(USER_1_USERNAME, response.getUsername()); } @@ -48,10 +37,6 @@ public class UserServiceUnitTest extends BaseUnitTest { @Test public void findByUsername_fails() { - /* mock */ - when(userRepository.findByUsername(USER_1_USERNAME)) - .thenReturn(Optional.empty()); - /* test */ assertThrows(UserNotFoundException.class, () -> { userService.findByUsername(USER_1_USERNAME); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServiceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServiceIntegrationTest.java index 803bdc44c0c922dc5670a956cb53492f4bd75c9b..d52fe08cead7e79dc30fe3ed7c60bd82ca7a7f46 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServiceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServiceIntegrationTest.java @@ -2,17 +2,12 @@ package at.tuwien.service; import at.tuwien.BaseUnitTest; import at.tuwien.annotations.MockAmqp; -import at.tuwien.annotations.MockOpensearch; import at.tuwien.api.database.ViewCreateDto; import at.tuwien.config.MariaDbConfig; import at.tuwien.config.MariaDbContainerConfig; import at.tuwien.entities.database.View; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.Rule; import org.junit.jupiter.api.BeforeAll; @@ -25,7 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -42,7 +36,6 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; - @Log4j2 @Testcontainers @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @@ -55,18 +48,12 @@ public class ViewServiceIntegrationTest extends BaseUnitTest { @Autowired private DatabaseRepository databaseRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @Autowired private ContainerRepository containerRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ViewRepository viewRepository; @@ -106,8 +93,6 @@ public class ViewServiceIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() { /* metadata database */ - realmRepository.save(REALM_DBREPO); - userRepository.saveAll(List.of(USER_1, USER_2)); imageRepository.save(IMAGE_1); containerRepository.saveAll(List.of(CONTAINER_1_SIMPLE, CONTAINER_2_SIMPLE)); databaseRepository.saveAll(List.of(DATABASE_1_SIMPLE, DATABASE_2_SIMPLE)); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServicePersistenceIntegrationTest.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServicePersistenceIntegrationTest.java index 44d023d87b8ddc6595883c1047a6d04d81c497b4..f581f6e98abd03a292de8f9d294620134a61fb26 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServicePersistenceIntegrationTest.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/service/ViewServicePersistenceIntegrationTest.java @@ -8,11 +8,7 @@ import at.tuwien.config.MariaDbConfig; import at.tuwien.config.MariaDbContainerConfig; import at.tuwien.entities.database.View; import at.tuwien.exception.*; -import at.tuwien.gateway.BrokerServiceGateway; -import at.tuwien.listener.impl.RabbitMqListenerImpl; import at.tuwien.repository.mdb.*; -import at.tuwien.repository.sdb.ViewIdxRepository; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -22,7 +18,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; @@ -35,7 +30,6 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; - @Log4j2 @Testcontainers @EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class) @@ -49,18 +43,12 @@ public class ViewServicePersistenceIntegrationTest extends BaseUnitTest { @Autowired private DatabaseRepository databaseRepository; - @Autowired - private RealmRepository realmRepository; - @Autowired private ImageRepository imageRepository; @Autowired private ContainerRepository containerRepository; - @Autowired - private UserRepository userRepository; - @Autowired private ViewRepository viewRepository; @@ -85,8 +73,6 @@ public class ViewServicePersistenceIntegrationTest extends BaseUnitTest { @BeforeEach public void beforeEach() { /* metadata database */ - realmRepository.save(REALM_DBREPO); - userRepository.saveAll(List.of(USER_1, USER_2)); imageRepository.save(IMAGE_1); containerRepository.saveAll(List.of(CONTAINER_1_SIMPLE, CONTAINER_2_SIMPLE)); databaseRepository.saveAll(List.of(DATABASE_1_SIMPLE, DATABASE_2_SIMPLE)); diff --git a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/utils/AmqpUtils.java b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/utils/AmqpUtils.java index 22ee9436920a2317dbac578ce32cdad02290c3b8..719ed8229779eff53e260225a009c6a62c1a8409 100644 --- a/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/utils/AmqpUtils.java +++ b/dbrepo-metadata-service/rest-service/src/test/java/at/tuwien/utils/AmqpUtils.java @@ -5,7 +5,6 @@ import lombok.extern.log4j.Log4j2; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; 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 6ea244795211c2b568b6a0e09e36b8ece87bf118..d9bdc7aff4fd86dd3e2d85a9b4f9f4fcbdda60e9 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 @@ -9,12 +9,10 @@ import at.tuwien.entities.identifier.Identifier; import at.tuwien.entities.identifier.VisibilityType; import at.tuwien.exception.*; import at.tuwien.repository.mdb.IdentifierRepository; -import at.tuwien.repository.sdb.ViewIdxRepository; import at.tuwien.service.AccessService; import at.tuwien.service.DatabaseService; import at.tuwien.service.TableService; import at.tuwien.validation.EndpointValidator; -import com.rabbitmq.client.Channel; import lombok.extern.log4j.Log4j2; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -235,7 +233,7 @@ public class EndpointValidatorUnitTest extends BaseUnitTest { public void validateOnlyAccessOrPublic2_privateAnonymousHasSelfIdentifier_fails() throws DatabaseNotFoundException { final Identifier identifier = Identifier.builder() .visibility(VisibilityType.SELF) - .creator(USER_1) + .createdBy(USER_1_ID) .build(); /* mock */ @@ -255,7 +253,7 @@ public class EndpointValidatorUnitTest extends BaseUnitTest { NotAllowedException { final Identifier identifier = Identifier.builder() .visibility(VisibilityType.SELF) - .creator(USER_1) + .createdBy(USER_1_ID) .build(); /* mock */ @@ -311,7 +309,7 @@ public class EndpointValidatorUnitTest extends BaseUnitTest { public void validateOnlyWriteOwnOrWriteAllAccess_privateHasWriteAllAccess_succeeds() throws NotAllowedException, TableNotFoundException, DatabaseNotFoundException { final Table table = Table.builder() - .owner(USER_2) + .ownedBy(USER_2_ID) .build(); /* mock */ diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/auth/AuthTokenFilter.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/auth/AuthTokenFilter.java index 92b60f4f8a5ed8a566e2504d71b63478b1593f68..647f23867be68d0f5f953934d460185c3fff0afd 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/auth/AuthTokenFilter.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/auth/AuthTokenFilter.java @@ -79,6 +79,7 @@ public class AuthTokenFilter extends OncePerRequestFilter { final DecodedJWT jwt = verifier.verify(token); final RealmAccessDto realmAccess = jwt.getClaim("realm_access").as(RealmAccessDto.class); return UserDetailsDto.builder() + .id(jwt.getSubject()) .username(jwt.getClaim("client_id").asString()) .authorities(Arrays.stream(realmAccess.getRoles()).map(SimpleGrantedAuthority::new).collect(Collectors.toList())) .build(); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/config/KeycloakConfig.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/config/KeycloakConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..1c6f82290583d3618af9143696540a8f30d44a67 --- /dev/null +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/config/KeycloakConfig.java @@ -0,0 +1,17 @@ +package at.tuwien.config; + +import lombok.Getter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Getter +@Configuration +public class KeycloakConfig { + + @Value("${fda.keycloak.username}") + private String username; + + @Value("${fda.keycloak.password}") + private String password; +} 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 new file mode 100644 index 0000000000000000000000000000000000000000..b1e4a00a360db65ef346c1f6fcec0783ec0d4800 --- /dev/null +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/KeycloakGateway.java @@ -0,0 +1,32 @@ +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; +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 new file mode 100644 index 0000000000000000000000000000000000000000..f5542abffecacda9b9b2f6735632a9407a17933c --- /dev/null +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/gateway/impl/KeycloakGatewayImpl.java @@ -0,0 +1,206 @@ +package at.tuwien.gateway.impl; + +import at.tuwien.api.keycloak.*; +import at.tuwien.api.user.UserPasswordDto; +import at.tuwien.config.KeycloakConfig; +import at.tuwien.exception.AccessDeniedException; +import at.tuwien.exception.KeycloakRemoteException; +import at.tuwien.exception.UserNotFoundException; +import at.tuwien.gateway.KeycloakGateway; +import at.tuwien.mapper.UserMapper; +import lombok.extern.log4j.Log4j2; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +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 +@Service +public class KeycloakGatewayImpl implements KeycloakGateway { + + private final UserMapper userMapper; + private final RestTemplate restTemplate; + private final KeycloakConfig keycloakConfig; + + public KeycloakGatewayImpl(UserMapper userMapper, KeycloakConfig keycloakConfig) { + this.userMapper = userMapper; + this.restTemplate = new RestTemplate(); + this.keycloakConfig = keycloakConfig; + } + + public TokenDto obtainToken() throws AccessDeniedException { + final HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + final MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(); + payload.add("username", keycloakConfig.getUsername()); + payload.add("password", keycloakConfig.getPassword()); + payload.add("grant_type", "password"); + payload.add("client_id", "admin-cli"); + final ResponseEntity<TokenDto> response; + try { + response = restTemplate.exchange("/api/auth/realms/master/protocol/openid-connect/token", + HttpMethod.POST, new HttpEntity<>(payload, headers), TokenDto.class); + } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { + log.error("Failed to obtain admin token: {}", e.getMessage()); + throw new AccessDeniedException("Failed to obtain admin token: " + e.getMessage()); + } + return response.getBody(); + } + + @Override + public void createUser(UserCreateDto data) throws AccessDeniedException, KeycloakRemoteException { + /* obtain admin token */ + final HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); + final ResponseEntity<Void> response; + try { + response = restTemplate.exchange("/api/auth/admin/realms/dbrepo/users", HttpMethod.POST, + new HttpEntity<>(data, headers), Void.class); + } catch (ResourceAccessException | HttpServerErrorException.ServiceUnavailable e) { + log.error("Failed to create user: {}", e.getMessage()); + throw new KeycloakRemoteException("Failed to create user: " + e.getMessage()); + } + if (!response.getStatusCode().equals(HttpStatus.CREATED)) { + log.error("Failed to create user: status {} was not expected", response.getStatusCode().value()); + throw new KeycloakRemoteException("Failed to create user: status " + response.getStatusCode().value() + "was not expected"); + } + } + + @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 { + /* obtain admin token */ + final HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + headers.set("Authorization", "Bearer " + obtainToken().getAccessToken()); + final UpdateCredentialsDto payload = userMapper.passwordToUpdateCredentialsDto(data.getPassword()); + 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 credentials: {}", e.getMessage()); + throw new KeycloakRemoteException("Failed to update user credentials: " + e.getMessage()); + } + if (!response.getStatusCode().equals(HttpStatus.ACCEPTED)) { + log.error("Failed to update user credentials: status {} was not expected", response.getStatusCode().value()); + throw new KeycloakRemoteException("Failed to update user credentials: status " + response.getStatusCode().value() + "was not expected"); + } + } + + @Override + public UserDto findByUsername(String username) 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/?username=" + username, + 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 username {}: response is not exactly 1 but is {}", username, body.length); + throw new UserNotFoundException("Failed to find user with username " + username); + } + 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/AccessService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/AccessService.java index 95077d2b20fe4f45ff70f509bd19f67423175564..707b5b75cae1050513897da712a1ed04f5a6cad2 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/AccessService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/AccessService.java @@ -45,44 +45,41 @@ public interface AccessService { /** * Give somebody access to a database of container. * - * @param databaseId The database id. - * @param accessDto The access. + * @param databaseId The database id. + * @param accessDto The access. * @throws DatabaseNotFoundException The database was not found in the metadata database. * @throws UserNotFoundException The authenticated user was not found in the metadata database. * @throws NotAllowedException The access is not allowed. * @throws QueryMalformedException The mapped access query is malformed. * @throws DatabaseMalformedException The database has an invalid state. */ - void create(Long databaseId, DatabaseGiveAccessDto accessDto) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException; + void create(Long databaseId, DatabaseGiveAccessDto accessDto) throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException; /** * Update access to a database. * - * @param databaseId The database id. - * @param username The username. - * @param accessDto The updated access. + * @param databaseId The database id. + * @param userId The user id. + * @param accessDto The updated access. * @throws DatabaseNotFoundException The database was not found in the metadata database. * @throws UserNotFoundException The authenticated user was not found in the metadata database. * @throws NotAllowedException The access is not allowed. * @throws QueryMalformedException The mapped access query is malformed. * @throws DatabaseMalformedException The database has an invalid state. */ - void update(Long databaseId, String username, DatabaseModifyAccessDto accessDto) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException, - NotAllowedException; + void update(Long databaseId, UUID userId, DatabaseModifyAccessDto accessDto) throws DatabaseNotFoundException, UserNotFoundException, QueryMalformedException, DatabaseMalformedException, + NotAllowedException, KeycloakRemoteException, AccessDeniedException; /** * Revokes access to a database of container. * - * @param databaseId The database id. - * @param username The user name. + * @param databaseId The database id. + * @param userId The user id. * @throws DatabaseNotFoundException The database was not found in the metadata database. * @throws UserNotFoundException The authenticated user was not found in the metadata database. * @throws NotAllowedException The access is not allowed. * @throws QueryMalformedException The mapped access query is malformed. * @throws DatabaseMalformedException The database has an invalid state. */ - void delete(Long databaseId, String username) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException; + void delete(Long databaseId, UUID userId) throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException; } 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 913afb59bdd6c3218679addedaa9211fa1abb367..573941b00a110ef5a60ed2a703627d848a51b08a 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 @@ -86,7 +86,7 @@ public interface DatabaseService { Database create(DatabaseCreateDto createDto, Principal principal) throws ImageNotSupportedException, ContainerNotFoundException, DatabaseMalformedException, AmqpException, ContainerConnectionException, UserNotFoundException, - DatabaseNameExistsException, DatabaseConnectionException, QueryMalformedException; + DatabaseNameExistsException, DatabaseConnectionException, QueryMalformedException, KeycloakRemoteException, AccessDeniedException; /** * Updates the visibility of the database. @@ -107,5 +107,5 @@ public interface DatabaseService { * @throws DatabaseNotFoundException The database was not found in the metadata database. * @throws UserNotFoundException The new user was not found in the metadata database. */ - Database transfer(Long databaseId, DatabaseTransferDto transferDto) throws DatabaseNotFoundException, UserNotFoundException; + Database transfer(Long databaseId, DatabaseTransferDto transferDto) throws DatabaseNotFoundException, UserNotFoundException, KeycloakRemoteException, AccessDeniedException; } 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 2aa11a7a503cdd49e2b45297bac29ffd43ee256c..2cfa8eef79db2d3940d95ae989f99e00678e094f 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 @@ -1,8 +1,8 @@ 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; @@ -42,10 +42,10 @@ public interface MessageQueueService { /** * Create user on the broker service * - * @param user The new user. + * @param username The username. * @throws BrokerVirtualHostCreationException The user could not be created. */ - void createUser(User user) throws BrokerVirtualHostCreationException; + void createUser(String username) throws BrokerVirtualHostCreationException; /** @@ -54,7 +54,7 @@ public interface MessageQueueService { * @param user The user. * @throws BrokerVirtualHostGrantException The Broker Service refused to grant the permissions. */ - void updatePermissions(User user) throws BrokerVirtualHostGrantException; + void updatePermissions(UserDto user) throws BrokerVirtualHostGrantException; /** * Deletes an exchange for a database. @@ -67,9 +67,9 @@ public interface MessageQueueService { /** * Creates a consumer on the provided queue with name and container id and database id for table id. * - * @param queueName The queue name. - * @param databaseId The database id. - * @param tableId The table id. + * @param queueName The queue name. + * @param databaseId The database id. + * @param tableId The table id. * @throws AmqpException The consumer could not be created. */ void createConsumer(String queueName, Long databaseId, Long tableId) throws AmqpException; diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/OntologyService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/OntologyService.java index 4a55f52491007c5ecae69bc6c59698541284a528..7782aaf2d940e65db3ab16879c21e768a18619e3 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/OntologyService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/OntologyService.java @@ -3,6 +3,8 @@ package at.tuwien.service; import at.tuwien.api.semantics.OntologyCreateDto; import at.tuwien.api.semantics.OntologyModifyDto; import at.tuwien.entities.semantics.Ontology; +import at.tuwien.exception.AccessDeniedException; +import at.tuwien.exception.KeycloakRemoteException; import at.tuwien.exception.OntologyNotFoundException; import at.tuwien.exception.UserNotFoundException; @@ -14,7 +16,7 @@ public interface OntologyService { Ontology find(Long id) throws OntologyNotFoundException; - Ontology create(OntologyCreateDto data, Principal principal) throws UserNotFoundException; + Ontology create(OntologyCreateDto data, Principal principal) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; Ontology update(Long id, OntologyModifyDto data) throws OntologyNotFoundException; diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/QueryService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/QueryService.java index bd3bc0ba8f3f347dab55183c907715fc475b7937..e974f6eac844814716a6f8c791e4f806aeadf893 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/QueryService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/QueryService.java @@ -44,7 +44,7 @@ public interface QueryService { QueryResultDto execute(Long databaseId, ExecuteStatementDto statement, Principal principal, Long page, Long size, SortType sortDirection, String sortColumn) throws DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, QueryStoreException, ColumnParseException, - UserNotFoundException, TableMalformedException, DatabaseConnectionException; + UserNotFoundException, TableMalformedException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException; /** * Re-Executes an arbitrary query on the database. We allow the user to only view the data, therefore the diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RealmService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RealmService.java deleted file mode 100644 index 6c93de60862f459c1ca80db0f7493babf36a8531..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RealmService.java +++ /dev/null @@ -1,16 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.entities.user.Realm; -import at.tuwien.exception.RealmNotFoundException; - -public interface RealmService { - - /** - * Finds a realm by name. - * - * @param name The realm name. - * @return The realm, if successful. - * @throws RealmNotFoundException The realm could not be found. - */ - Realm find(String name) throws RealmNotFoundException; -} diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RoleService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RoleService.java deleted file mode 100644 index 08c3a0cc3f693ce325eca257f4e972466f99bd6d..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/RoleService.java +++ /dev/null @@ -1,8 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.entities.user.Role; -import at.tuwien.exception.RoleNotFoundException; - -public interface RoleService { - Role find(String name) throws RoleNotFoundException; -} diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/StoreService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/StoreService.java index 287761b79c162c582c266efa42985ba06b6cf598..f737a79c85c700d901c3b6477c2200c774943ab8 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/StoreService.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/StoreService.java @@ -56,7 +56,7 @@ public interface StoreService { * @throws DatabaseConnectionException The database connection to the remote container failed. */ Query insert(Long databaseId, ExecuteStatementDto metadata, Principal principal) throws QueryStoreException, - DatabaseNotFoundException, ImageNotSupportedException, UserNotFoundException, DatabaseConnectionException; + DatabaseNotFoundException, ImageNotSupportedException, UserNotFoundException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException; /** * Persists a query to be displayed in the frontend. diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserAttributeService.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserAttributeService.java deleted file mode 100644 index d8af9940ad232d4f7160362b0efa703146dffd0e..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/UserAttributeService.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.tuwien.service; - -import at.tuwien.entities.user.UserAttribute; -import at.tuwien.exception.UserAttributeNotFoundException; - -import java.util.UUID; - -public interface UserAttributeService { - - UserAttribute find(UUID userId, String name) throws UserAttributeNotFoundException; - - UserAttribute update(UUID userId, String name, String value) throws UserAttributeNotFoundException; - - UserAttribute create(UserAttribute userAttribute); -} 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 dcf127ac67ffe0e623373654823da88543ef4fbf..0cbf5ef091e93c1ce67e947b11a7624f7ea639c4 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 @@ -1,15 +1,8 @@ package at.tuwien.service; import at.tuwien.api.auth.SignupRequestDto; -import at.tuwien.api.user.UserPasswordDto; -import at.tuwien.api.user.UserThemeSetDto; -import at.tuwien.api.user.UserUpdateDto; -import at.tuwien.entities.user.Realm; -import at.tuwien.entities.user.User; -import at.tuwien.exception.UserAlreadyExistsException; -import at.tuwien.exception.UserAttributeNotFoundException; -import at.tuwien.exception.UserEmailAlreadyExistsException; -import at.tuwien.exception.UserNotFoundException; +import at.tuwien.api.user.*; +import at.tuwien.exception.*; import java.util.List; import java.util.UUID; @@ -21,7 +14,7 @@ public interface UserService { * * @return The list of users. */ - List<User> findAll(); + List<UserBriefDto> findAll() throws KeycloakRemoteException, AccessDeniedException; /** * Finds a user by username. @@ -30,7 +23,7 @@ public interface UserService { * @return The user, if successfully. * @throws UserNotFoundException The user with this username was not found in the metadata database. */ - User findByUsername(String username) throws UserNotFoundException; + UserDto findByUsername(String username) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; /** * Finds a specific user in the metadata database by given id. @@ -39,17 +32,17 @@ public interface UserService { * @return The user if successful. False otherwise. * @throws UserNotFoundException The user was not found. */ - User find(UUID id) throws UserNotFoundException; + UserDto find(UUID id) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; /** * Creates a user in the metadata database managed by Keycloak in the given realm. * * @param data The user data. - * @param realm The realm this user should be created. * @return The user, if successful. False otherwise. * @throws UserAlreadyExistsException The user already exists in the metadata database. */ - User create(SignupRequestDto data, Realm realm) throws UserAlreadyExistsException; + UserDto create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, + KeycloakRemoteException, UserNotFoundException; /** * Updates the user information for a user with given id in the metadata database. @@ -60,17 +53,16 @@ public interface UserService { * @throws UserNotFoundException The user was not found. * @throws UserAttributeNotFoundException One or more user attributes for the user information were not found. */ - User modify(UUID id, UserUpdateDto data) throws UserNotFoundException, UserAttributeNotFoundException; + UserDto modify(UUID id, UserUpdateDto data) throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException; /** * Updates the user password for a user with given id. * * @param id The user id. * @param data The new password. - * @return The user if successful. False otherwise. * @throws UserNotFoundException The user was not found. */ - User updatePassword(UUID id, UserPasswordDto data) throws UserNotFoundException; + void updatePassword(UUID id, UserPasswordDto data) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException; /** * Updates the user theme for a user with given id. @@ -81,7 +73,7 @@ public interface UserService { * @throws UserNotFoundException The user was not found. * @throws UserAttributeNotFoundException One or more user attributes for the user information were not found. */ - User toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, UserAttributeNotFoundException; + UserDto toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, UserAttributeNotFoundException, KeycloakRemoteException, AccessDeniedException; /** * 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 8f5b94e49981ac06b545541756bbf42ff404226b..9f6c10be734f2cf695493bb47bac8e14b6e544cc 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,12 +2,14 @@ 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; @@ -29,17 +31,21 @@ 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(UserService userService, DatabaseMapper databaseMapper, DatabaseService databaseService, - DatabaseAccessRepository databaseAccessRepository) { + public AccessServiceImpl(UserMapper userMapper, UserService userService, DatabaseMapper databaseMapper, DatabaseService databaseService, + KeycloakGateway keycloakGateway, DatabaseAccessRepository databaseAccessRepository) { + this.userMapper = userMapper; this.userService = userService; this.databaseMapper = databaseMapper; this.databaseService = databaseService; + this.keycloakGateway = keycloakGateway; this.databaseAccessRepository = databaseAccessRepository; } @@ -83,14 +89,13 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi @Override @Transactional - public void create(Long databaseId, DatabaseGiveAccessDto accessDto) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, - DatabaseMalformedException { + public void create(Long databaseId, DatabaseGiveAccessDto accessDto) throws DatabaseNotFoundException, + UserNotFoundException, NotAllowedException, QueryMalformedException, DatabaseMalformedException, + KeycloakRemoteException, AccessDeniedException { /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); - final User user = userService.findByUsername(accessDto.getUsername()); - log.trace("give access to user with username {}", user.getUsername()); + final UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findByUsername(accessDto.getUsername())); if (databaseAccessRepository.findByDatabaseIdAndUsername(databaseId, accessDto.getUsername()).isPresent()) { log.error("Failed to give access to user with username {}, has already permission", accessDto.getUsername()); throw new NotAllowedException("Failed to give access"); @@ -104,7 +109,7 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi /* grant access */ final PreparedStatement preparedStatement2 = databaseMapper.rawGrantUserAccessQuery(connection, accessDto); preparedStatement2.executeUpdate(); - final PreparedStatement preparedStatement3 = databaseMapper.rawGrantUserProcedure(connection, user); + final PreparedStatement preparedStatement3 = databaseMapper.rawGrantUserProcedure(connection, user.getUsername()); preparedStatement3.executeUpdate(); final PreparedStatement preparedStatement4 = databaseMapper.rawFlushPrivileges(connection); preparedStatement4.executeUpdate(); @@ -115,27 +120,26 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi dataSource.close(); } /* update access */ - final DatabaseAccess entity = databaseMapper.databaseGiveAccessDtoToDatabaseAccess(database, user, accessDto); + final DatabaseAccess entity = databaseMapper.databaseGiveAccessDtoToDatabaseAccess(database, user.getId(), accessDto); databaseAccessRepository.save(entity); - log.info("Gave access to database with id {} for user with username {}", databaseId, user.getUsername()); + log.info("Handed access to database with id {} for user with username {}", databaseId, user.getUsername()); } @Override @Transactional - public void update(Long databaseId, String username, DatabaseModifyAccessDto accessDto) - throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, - DatabaseMalformedException, NotAllowedException { + public void update(Long databaseId, UUID userId, DatabaseModifyAccessDto accessDto) + throws DatabaseNotFoundException, UserNotFoundException, QueryMalformedException, + DatabaseMalformedException, NotAllowedException, KeycloakRemoteException, AccessDeniedException { /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); - final User user = userService.findByUsername(username); - if (database.getOwner().getUsername().equals(username)) { - log.error("Failed to modify access of user with username {}, because it is the owner", username); - throw new NotAllowedException("Failed modify access"); + 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"); } - find(databaseId, username); + 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(username, accessDto); + final DatabaseGiveAccessDto giveAccess = databaseMapper.databaseModifyAccessToDatabaseGiveAccessDto(user.getUsername(), accessDto); try { final Connection connection = dataSource.getConnection(); /* create user if not exists */ @@ -144,7 +148,7 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi /* grant access */ final PreparedStatement preparedStatement2 = databaseMapper.rawGrantUserAccessQuery(connection, giveAccess); preparedStatement2.executeUpdate(); - final PreparedStatement preparedStatement3 = databaseMapper.rawGrantUserProcedure(connection, user); + final PreparedStatement preparedStatement3 = databaseMapper.rawGrantUserProcedure(connection, user.getUsername()); preparedStatement3.executeUpdate(); final PreparedStatement preparedStatement4 = databaseMapper.rawFlushPrivileges(connection); preparedStatement4.executeUpdate(); @@ -156,29 +160,29 @@ public class AccessServiceImpl extends HibernateConnector implements AccessServi } /* update access */ databaseAccessRepository.save(databaseMapper.databaseModifyAccessDtoToDatabaseAccess(database, user, accessDto)); - log.info("Modified access to database with id {} for user with username {}", databaseId, username); + log.info("Modified access to database with id {} for user with username {}", databaseId, user.getUsername()); } @Override @Transactional - public void delete(Long databaseId, String username) + public void delete(Long databaseId, UUID userId) throws DatabaseNotFoundException, UserNotFoundException, NotAllowedException, QueryMalformedException, - DatabaseMalformedException { + DatabaseMalformedException, KeycloakRemoteException, AccessDeniedException { /* check */ final Database database = databaseService.findById(databaseId); final Container container = database.getContainer(); - final User user = userService.findByUsername(username); - if (database.getOwner().getUsername().equals(username)) { - log.error("Failed to revoke access of user with username {}, because it is the owner", username); - throw new NotAllowedException("Failed revoke access"); + 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(); /* create user */ - final PreparedStatement preparedStatement1 = databaseMapper.rawRevokeUserAccessQuery(connection, user); + final PreparedStatement preparedStatement1 = databaseMapper.rawRevokeUserAccessQuery(connection, user.getUsername()); preparedStatement1.executeUpdate(); - final PreparedStatement preparedStatement2 = databaseMapper.userToRawDropUserQuery(connection, user); + final PreparedStatement preparedStatement2 = databaseMapper.userToRawDropUserQuery(connection, user.getUsername()); preparedStatement2.executeUpdate(); } catch (SQLException e) { log.error("Failed to revoke database access, reason {}", e.getMessage()); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/HibernateConnector.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/HibernateConnector.java index 9bb5c149f7bfb197ff37b8eaaf4dcc95cf5d37d5..3b56451717725710c3d7b9dfd909be40727db613 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/HibernateConnector.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/HibernateConnector.java @@ -1,9 +1,9 @@ package at.tuwien.service.impl; +import at.tuwien.api.user.UserDto; import at.tuwien.entities.container.Container; import at.tuwien.entities.container.image.ContainerImage; import at.tuwien.entities.database.Database; -import at.tuwien.entities.user.User; import com.mchange.v2.c3p0.ComboPooledDataSource; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; @@ -12,8 +12,8 @@ import org.springframework.stereotype.Service; @Service public abstract class HibernateConnector { - public static ComboPooledDataSource getDataSource(ContainerImage image, Container container, User user) { - return getDataSource(image, container, null, user.getUsername(), user.getDatabasePassword()); + public static ComboPooledDataSource getDataSource(ContainerImage image, Container container, UserDto user) { + return getDataSource(image, container, null, user.getUsername(), user.getAttributes().getMariadbPassword()); } public static ComboPooledDataSource getPrivilegedDataSource(ContainerImage image, Container container) { diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/IdentifierServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/IdentifierServiceImpl.java index 92e5ffc340f600ae6130973930acd6783bb6788e..b138faed37bccf048a3eb57d90348dc14dc5359f 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/IdentifierServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/IdentifierServiceImpl.java @@ -9,13 +9,13 @@ import at.tuwien.entities.database.View; import at.tuwien.entities.identifier.Identifier; import at.tuwien.entities.identifier.IdentifierTitle; import at.tuwien.entities.identifier.IdentifierType; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.IdentifierMapper; import at.tuwien.querystore.Query; import at.tuwien.repository.mdb.IdentifierRepository; import at.tuwien.repository.sdb.IdentifierIdxRepository; import at.tuwien.service.*; +import at.tuwien.utils.UserUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.core.io.InputStreamResource; @@ -25,12 +25,12 @@ import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.exceptions.TemplateInputException; -import java.io.ByteArrayInputStream; import java.nio.charset.Charset; import java.security.Principal; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.stream.Stream; @Slf4j @@ -148,8 +148,7 @@ public class IdentifierServiceImpl implements IdentifierService { } /* create identifier */ final Identifier identifier = identifierMapper.identifierCreateDtoToIdentifier(data); - final User creator = userService.findByUsername(principal.getName()); - identifier.setCreator(creator); + identifier.setCreatedBy(UserUtil.getId(principal)); identifier.setDatabaseId(data.getDatabaseId()); final Database database = databaseService.find(data.getDatabaseId()); identifier.setDatabase(database); @@ -228,7 +227,6 @@ public class IdentifierServiceImpl implements IdentifierService { context.setVariable("identifierType", "url"); context.setVariable("identifier", endpointConfig.getWebsiteUrl() + "/pid/" + identifier.getId()); } - context.setVariable("creator", identifier.getCreator()); context.setVariable("creators", identifier.getCreators()); context.setVariable("title", preferTitle(identifier.getTitles())); context.setVariable("publisher", identifier.getPublisher()); @@ -277,8 +275,7 @@ public class IdentifierServiceImpl implements IdentifierService { final Identifier identifier = identifierMapper.identifierUpdateDtoToIdentifier(data); identifier.setId(identifierId); identifier.setDoi(oldIdentifier.getDoi()); - final User creator = userService.findByUsername(principal.getName()); - identifier.setCreator(creator); + identifier.setCreatedBy(UserUtil.getId(principal)); final Database database = databaseService.find(data.getDatabaseId()); identifier.setDatabase(database); if (data.getType().equals(IdentifierTypeDto.SUBSET)) { 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 488f082711602a8e08a6140d5f03846153865918..9d8b95e4fd6d8d957b8cf96e8b04fc631a962bcd 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 @@ -3,9 +3,9 @@ package at.tuwien.service.impl; import at.tuwien.api.database.DatabaseCreateDto; import at.tuwien.api.database.DatabaseModifyVisibilityDto; import at.tuwien.api.database.DatabaseTransferDto; +import at.tuwien.api.user.UserDto; 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; @@ -102,7 +102,7 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe log.error("Currently only MariaDB is supported"); throw new ImageNotSupportedException("Currently only MariaDB is supported"); } - if (!database.getOwner().getId().equals(userId)) { + if (!database.getOwnedBy().equals(userId)) { log.error("Failed to delete database: user is not owner"); throw new DatabaseMalformedException("Failed to delete database: user is not owner"); } @@ -129,14 +129,14 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe @Override @Transactional public Database create(DatabaseCreateDto createDto, Principal principal) - throws ImageNotSupportedException, ContainerNotFoundException, - DatabaseMalformedException, AmqpException, ContainerConnectionException, UserNotFoundException, - DatabaseNameExistsException, DatabaseConnectionException, QueryMalformedException { - final User user = userService.findByUsername(principal.getName()); + throws ImageNotSupportedException, ContainerNotFoundException, DatabaseMalformedException, AmqpException, + ContainerConnectionException, UserNotFoundException, DatabaseNameExistsException, + DatabaseConnectionException, QueryMalformedException, KeycloakRemoteException, AccessDeniedException { + final UserDto user = userService.findByUsername(principal.getName()); /* start the object */ final Database database = databaseMapper.databaseCreateDtoToDatabase(createDto); final Container container = containerService.find(database.getCid()); - final User owner = userService.findByUsername(principal.getName()); + final UserDto owner = userService.findByUsername(principal.getName()); database.setContainer(container); database.setOwnedBy(owner.getId()); database.setCreatedBy(owner.getId()); @@ -186,10 +186,10 @@ public class MariaDbServiceImpl extends HibernateConnector implements DatabaseSe @Override @Transactional public Database transfer(Long databaseId, DatabaseTransferDto transferDto) throws DatabaseNotFoundException, - UserNotFoundException { + UserNotFoundException, KeycloakRemoteException, AccessDeniedException { /* check */ final Database database = findById(databaseId); - final User user = userService.findByUsername(transferDto.getUsername()); + final UserDto 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 411ea767ecdfce7de3f8613ad690f618f96df431..b52c92527d0c0952deece042be05edd4a8949729 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 @@ -2,8 +2,10 @@ package at.tuwien.service.impl; 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; import at.tuwien.exception.UserNotFoundException; import at.tuwien.mapper.OntologyMapper; @@ -50,8 +52,9 @@ public class OntologyServiceImpl implements OntologyService { } @Override - public Ontology create(OntologyCreateDto data, Principal principal) throws UserNotFoundException { - final User user = userService.findByUsername(principal.getName()); + public Ontology create(OntologyCreateDto data, Principal principal) throws UserNotFoundException, + KeycloakRemoteException, AccessDeniedException { + final UserDto 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/QueryServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/QueryServiceImpl.java index aba3e4ac81a4e402f8af96030f5c1187d34b0609..cc58dc9f55d8e31ec38626dc50c8776b363c7d3d 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/QueryServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/QueryServiceImpl.java @@ -74,8 +74,8 @@ public class QueryServiceImpl extends HibernateConnector implements QueryService public QueryResultDto execute(Long databaseId, ExecuteStatementDto statement, Principal principal, Long page, Long size, SortType sortDirection, String sortColumn) throws DatabaseNotFoundException, ImageNotSupportedException, QueryMalformedException, QueryStoreException, - ColumnParseException, UserNotFoundException, DatabaseConnectionException, - TableMalformedException { + ColumnParseException, UserNotFoundException, DatabaseConnectionException, TableMalformedException, + KeycloakRemoteException, AccessDeniedException { if (statement.getStatement().contains(";")) { log.error("Failed to execute query since it contains ';'"); throw new QueryMalformedException("Failed to execute query since it contains ';'"); 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 9780d4d8caffda4bf49dbf7a3a64383b6a07a9c9..5cfec6e09ba7ce320e03849a258df72fb3842d03 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; @@ -23,7 +23,6 @@ import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import lombok.extern.log4j.Log4j2; import org.apache.http.auth.BasicUserPrincipal; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; @@ -40,25 +39,23 @@ public class RabbitMqServiceImpl implements MessageQueueService { private Channel channel; private final AmqpConfig amqpConfig; private final AmqpMapper amqpMapper; - private final DatabaseRepository databaseRepository; - private final TableRepository tableRepository; private final ObjectMapper objectMapper; private final QueryService queryService; private final TableService tableService; + private final TableRepository tableRepository; + private final DatabaseRepository databaseRepository; private final BrokerServiceGateway brokerServiceGateway; - @Autowired - public RabbitMqServiceImpl(Channel channel, AmqpConfig amqpConfig, AmqpMapper amqpMapper, - DatabaseRepository databaseRepository, TableRepository tableRepository, ObjectMapper objectMapper, - QueryService queryService, TableService tableService, BrokerServiceGateway brokerServiceGateway) { - this.channel = channel; + public RabbitMqServiceImpl(AmqpConfig amqpConfig, AmqpMapper amqpMapper, ObjectMapper objectMapper, + QueryService queryService, TableService tableService, TableRepository tableRepository, + DatabaseRepository databaseRepository, BrokerServiceGateway brokerServiceGateway) { this.amqpConfig = amqpConfig; this.amqpMapper = amqpMapper; - this.databaseRepository = databaseRepository; - this.tableRepository = tableRepository; this.objectMapper = objectMapper; this.queryService = queryService; this.tableService = tableService; + this.tableRepository = tableRepository; + this.databaseRepository = databaseRepository; this.brokerServiceGateway = brokerServiceGateway; } @@ -102,12 +99,12 @@ public class RabbitMqServiceImpl implements MessageQueueService { } @Override - public void createUser(User user) throws BrokerVirtualHostCreationException { - brokerServiceGateway.createUser(user.getUsername()); + public void createUser(String username) throws BrokerVirtualHostCreationException { + brokerServiceGateway.createUser(username); } @Override - public void updatePermissions(User user) throws BrokerVirtualHostGrantException { + public void updatePermissions(UserDto 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/RealmServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RealmServiceImpl.java deleted file mode 100644 index 4ff1da34d84784ad626d3be3926d21949f593d39..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RealmServiceImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package at.tuwien.service.impl; - -import at.tuwien.entities.user.Realm; -import at.tuwien.exception.RealmNotFoundException; -import at.tuwien.repository.mdb.RealmRepository; -import at.tuwien.service.RealmService; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Optional; - -@Log4j2 -@Service -public class RealmServiceImpl implements RealmService { - - private final RealmRepository realmRepository; - - @Autowired - public RealmServiceImpl(RealmRepository realmRepository) { - this.realmRepository = realmRepository; - } - - @Override - public Realm find(String name) throws RealmNotFoundException { - final Optional<Realm> optional = realmRepository.findByName(name); - if (optional.isEmpty()) { - log.error("Failed to find realm with name '{}'", name); - throw new RealmNotFoundException("Failed to find realm"); - } - final Realm realm = optional.get(); - log.trace("found realm {}", realm); - return realm; - } -} diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RoleServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RoleServiceImpl.java deleted file mode 100644 index 3f65f7d920344b79d199f67b21da26891b8f690d..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/RoleServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package at.tuwien.service.impl; - -import at.tuwien.entities.user.Role; -import at.tuwien.exception.RoleNotFoundException; -import at.tuwien.repository.mdb.RoleRepository; -import at.tuwien.service.RoleService; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Optional; - -@Log4j2 -@Service -public class RoleServiceImpl implements RoleService { - - private final RoleRepository roleRepository; - - @Autowired - public RoleServiceImpl(RoleRepository roleRepository) { - this.roleRepository = roleRepository; - } - - @Override - public Role find(String name) throws RoleNotFoundException { - final Optional<Role> optional = roleRepository.findByName(name); - if (optional.isEmpty()) { - log.error("Failed to find role with name {}", name); - throw new RoleNotFoundException("Failed to find role with name " + name); - } - final Role role = optional.get(); - log.trace("found role {}", role); - return role; - } - -} 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 11aebdf429250708b88bc20bde9c422d3e14552d..ecd46179292135d4de4c00444a980c0502a04678 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,14 +2,15 @@ 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; @@ -25,15 +26,18 @@ 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(StoreMapper storeMapper, UserService userService, DatabaseService databaseService) { + public StoreServiceImpl(UserMapper userMapper, StoreMapper storeMapper, DatabaseService databaseService, + KeycloakGateway keycloakGateway) { + this.userMapper = userMapper; this.storeMapper = storeMapper; - this.userService = userService; this.databaseService = databaseService; + this.keycloakGateway = keycloakGateway; } @Override @@ -98,7 +102,7 @@ public class StoreServiceImpl extends HibernateConnector implements StoreService @Transactional(readOnly = true) public Query insert(Long databaseId, ExecuteStatementDto metadata, Principal principal) throws QueryStoreException, DatabaseNotFoundException, ImageNotSupportedException, - UserNotFoundException, DatabaseConnectionException { + UserNotFoundException, DatabaseConnectionException, KeycloakRemoteException, AccessDeniedException { /* find */ final Database database = databaseService.find(databaseId); if (!database.getContainer().getImage().getName().equals("mariadb")) { @@ -107,12 +111,8 @@ public class StoreServiceImpl extends HibernateConnector implements StoreService } log.trace("insert into database id {}, metadata {}", databaseId, metadata); /* user */ - final User creator; - if (principal != null) { - creator = userService.findByUsername(principal.getName()); - } else { - creator = userService.findByUsername("system"); - } + final UserDto creator = userMapper.keycloakUserDtoToUserDto( + keycloakGateway.findByUsername(principal.getName())); /* save */ final ComboPooledDataSource dataSource = getPrivilegedDataSource(database.getContainer().getImage(), database.getContainer(), database); diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/TableServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/TableServiceImpl.java index 48d1d4925ff1dde041899401cc93afac03ee6f07..33b1c507fe00df066d95a13fc5b8bdc1415d0abb 100644 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/TableServiceImpl.java +++ b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/TableServiceImpl.java @@ -8,7 +8,6 @@ import at.tuwien.api.database.table.columns.concepts.ColumnSemanticsUpdateDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.table.Table; import at.tuwien.entities.database.table.columns.TableColumn; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.QueryMapper; import at.tuwien.mapper.TableMapper; @@ -20,6 +19,7 @@ import at.tuwien.service.DatabaseService; import at.tuwien.service.SemanticService; import at.tuwien.service.TableService; import at.tuwien.service.UserService; +import at.tuwien.utils.UserUtil; import com.mchange.v2.c3p0.ComboPooledDataSource; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; @@ -215,9 +215,8 @@ public class TableServiceImpl extends HibernateConnector implements TableService entity.setTdbid(databaseId); entity.setDatabase(database); entity.setConstraints(null); - final User creator = userService.findByUsername(principal.getName()); - entity.setCreator(creator); - entity.setOwner(creator); + entity.setCreatedBy(UserUtil.getId(principal)); + entity.setOwnedBy(UserUtil.getId(principal)); /* map columns */ entity.setColumns(createDto.getColumns() .stream() diff --git a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserAttributeServiceImpl.java b/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserAttributeServiceImpl.java deleted file mode 100644 index b8ef166f7ed067021c9157b11baa0c5e7fa86d08..0000000000000000000000000000000000000000 --- a/dbrepo-metadata-service/services/src/main/java/at/tuwien/service/impl/UserAttributeServiceImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -package at.tuwien.service.impl; - -import at.tuwien.entities.user.UserAttribute; -import at.tuwien.exception.UserAttributeNotFoundException; -import at.tuwien.repository.mdb.UserAttributeRepository; -import at.tuwien.service.UserAttributeService; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Optional; -import java.util.UUID; - -@Log4j2 -@Service -public class UserAttributeServiceImpl implements UserAttributeService { - - private final UserAttributeRepository userAttributeRepository; - - @Autowired - public UserAttributeServiceImpl(UserAttributeRepository userAttributeRepository) { - this.userAttributeRepository = userAttributeRepository; - } - - @Override - public UserAttribute find(UUID userId, String name) throws UserAttributeNotFoundException { - final Optional<UserAttribute> optional = userAttributeRepository.findByUserIdAndName(userId, name); - if (optional.isEmpty()) { - log.error("Failed to find user attribute with name {}", name); - throw new UserAttributeNotFoundException("Failed to find user attribute with name " + name); - } - return optional.get(); - } - - @Override - public UserAttribute update(UUID userId, String name, String value) throws UserAttributeNotFoundException { - final UserAttribute entity = find(userId, name); - entity.setValue(value); - return userAttributeRepository.save(entity); - } - - @Override - public UserAttribute create(UserAttribute userAttribute) { - return userAttributeRepository.save(userAttribute); - } -} 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 a461c20e0d635bcca24bd1b91206c1857a03a1f8..d0223155279fe7ac24031f253f92248bcc2d9b5b 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 @@ -1,255 +1,117 @@ package at.tuwien.service.impl; import at.tuwien.api.auth.SignupRequestDto; -import at.tuwien.api.user.UserPasswordDto; -import at.tuwien.api.user.UserThemeSetDto; -import at.tuwien.api.user.UserUpdateDto; -import at.tuwien.entities.user.*; -import at.tuwien.exception.UserAlreadyExistsException; -import at.tuwien.exception.UserAttributeNotFoundException; -import at.tuwien.exception.UserEmailAlreadyExistsException; -import at.tuwien.exception.UserNotFoundException; +import at.tuwien.api.user.*; +import at.tuwien.exception.*; +import at.tuwien.gateway.KeycloakGateway; import at.tuwien.mapper.UserMapper; -import at.tuwien.repository.mdb.CredentialRepository; -import at.tuwien.repository.mdb.GroupRepository; -import at.tuwien.repository.mdb.RoleRepository; -import at.tuwien.repository.mdb.UserRepository; import at.tuwien.repository.sdb.UserIdxRepository; -import at.tuwien.service.UserAttributeService; import at.tuwien.service.UserService; import lombok.extern.log4j.Log4j2; -import org.keycloak.common.util.Base64; -import org.keycloak.common.util.PaddingUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.time.Instant; import java.util.List; -import java.util.Optional; import java.util.UUID; @Log4j2 @Service public class UserServiceImpl implements UserService { - - private static final String ID = "pbkdf2-sha256"; - private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA256"; - private static final int DEFAULT_ITERATIONS = 27500; - private static final Integer DERIVED_KEY_SIZE = 256; - private static final Integer MAX_PADDING_LENGTH = 14; - private final UserMapper userMapper; - private final RoleRepository roleRepository; - private final UserRepository userRepository; - private final GroupRepository groupRepository; + private final KeycloakGateway keycloakGateway; private final UserIdxRepository userIdxRepository; - private final UserAttributeService userAttributeService; - private final CredentialRepository credentialRepository; @Autowired - public UserServiceImpl(UserMapper userMapper, RoleRepository roleRepository, UserRepository userRepository, - GroupRepository groupRepository, UserIdxRepository userIdxRepository, - UserAttributeService userAttributeService, CredentialRepository credentialRepository) { + public UserServiceImpl(UserMapper userMapper, KeycloakGateway keycloakGateway, + UserIdxRepository userIdxRepository) { this.userMapper = userMapper; - this.roleRepository = roleRepository; - this.userRepository = userRepository; - this.groupRepository = groupRepository; + this.keycloakGateway = keycloakGateway; this.userIdxRepository = userIdxRepository; - this.userAttributeService = userAttributeService; - this.credentialRepository = credentialRepository; } @Override - @Transactional(readOnly = true) - public List<User> findAll() { - return userRepository.findAll(); + public List<UserBriefDto> findAll() throws KeycloakRemoteException, AccessDeniedException { + return keycloakGateway.findAllUsers() + .stream() + .map(userMapper::keycloakUserDtoToUserBriefDto) + .toList(); } @Override - public User findByUsername(String username) throws UserNotFoundException { - final Optional<User> optional = userRepository.findByUsername(username); - if (optional.isEmpty()) { - log.error("Failed to retrieve user with username {}", username); - throw new UserNotFoundException("Failed to retrieve user"); - } - return optional.get(); + public UserDto findByUsername(String username) throws UserNotFoundException, KeycloakRemoteException, + AccessDeniedException { + return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findByUsername(username)); } @Override - @Transactional(readOnly = true) - public User find(UUID id) throws UserNotFoundException { - final Optional<User> optional = userRepository.findById(id); - if (optional.isEmpty()) { - log.error("Failed to retrieve user with id {}", id); - throw new UserNotFoundException("Failed to retrieve user"); - } - return optional.get(); + public UserDto find(UUID id) throws UserNotFoundException, KeycloakRemoteException, AccessDeniedException { + return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); } @Override - @Transactional(rollbackFor = RuntimeException.class) - public User create(SignupRequestDto data, Realm realm) throws UserAlreadyExistsException { - /* create secret */ - final byte[] salt = getSalt(); - final StringBuilder secretData = new StringBuilder("{\"value\":\"") - .append(encodedCredential(data.getPassword(), DEFAULT_ITERATIONS, salt, DERIVED_KEY_SIZE)) - .append("\",\"salt\":\"") - .append(Base64.encodeBytes(salt)) - .append("\",\"additionalParameters\":{}}"); - Credential credential = Credential.builder() - .id(UUID.randomUUID()) - .createdDate(Instant.now().toEpochMilli()) - .secretData(secretData.toString()) - .type("password") - .priority(10) - .credentialData("{\"hashIterations\":" + DEFAULT_ITERATIONS + ",\"algorithm\":\"" + ID + "\",\"additionalParameters\":{}}") - .build(); - /* save user attributes */ - User user = userMapper.signupRequestDtoToUser(data); - user.setId(UUID.randomUUID()); - user.setEmailVerified(false); - user.setEnabled(true); - user.setRealmId(realm.getId()); - user.setCreatedTimestamp(Instant.now().toEpochMilli()); - user = userRepository.save(user); - final UserAttribute userAttribute1 = userAttributeService.create(userMapper.tripleToUserAttribute(user.getId(), - "theme_dark", "false")); - final UserAttribute userAttribute2 = userAttributeService.create(userMapper.tripleToUserAttribute(user.getId(), - "orcid", "")); - final UserAttribute userAttribute3 = userAttributeService.create(userMapper.tripleToUserAttribute(user.getId(), - "affiliation", "")); - credential.setUserId(user.getId()); - /* find default roles and groups */ - final List<Group> groups = groupRepository.findDefault(); - final Optional<Role> optionalRole = roleRepository.findDefault(); - if (optionalRole.isPresent()) { - final Role defaultRole = optionalRole.get(); - log.debug("set default role: {}", defaultRole.getName()); - user.setRoles(List.of(defaultRole)); - } else { - user.setRoles(List.of()); - } - /* save in metadata database */ - credential = credentialRepository.save(credential); - user.setCredentials(List.of(credential)); - user.setAttributes(List.of(userAttribute1, userAttribute2, userAttribute3)); - user.setGroups(groups); - log.info("Created user with id {} in metadata database", user.getId()); + public UserDto create(SignupRequestDto data) throws UserAlreadyExistsException, AccessDeniedException, + KeycloakRemoteException, UserNotFoundException { + /* create */ + keycloakGateway.createUser(userMapper.signupRequestDtoToUserCreateDto(data)); + final at.tuwien.api.keycloak.UserDto keycloakUser = keycloakGateway.findByUsername(data.getUsername()); + final UserDto userDto = userMapper.keycloakUserDtoToUserDto(keycloakUser); /* save in open search database */ - userIdxRepository.save(userMapper.userToUserDto(user)); - log.info("Created user with id {} in open search database", user.getId()); - return user; + userIdxRepository.save(userMapper.keycloakUserDtoToUserDto(keycloakUser)); + log.info("Created user with id {} in open search database", userDto.getId()); + return userDto; } @Override - @Transactional - public User modify(UUID id, UserUpdateDto data) throws UserNotFoundException, UserAttributeNotFoundException { - /* check */ - final User entity = find(id); - entity.setFirstname(data.getFirstname()); - entity.setLastname(data.getLastname()); - /* save in metadata database */ - final User user = userRepository.save(entity); - log.info("Modified user with id {}", user.getId()); - /* modify attributes */ - userAttributeService.update(user.getId(), "orcid", data.getOrcid()); - userAttributeService.update(user.getId(), "affiliation", data.getAffiliation()); + 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 */ - userIdxRepository.save(userMapper.userToUserDto(user)); + final UserDto user = userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); + userIdxRepository.save(user); return user; } @Override - @Transactional(rollbackFor = RuntimeException.class) - public User updatePassword(UUID id, UserPasswordDto data) throws UserNotFoundException { - final User user = find(id); - /* create secret */ - final byte[] salt = getSalt(); - final StringBuilder secretData = new StringBuilder("{\"value\":\"") - .append(encodedCredential(data.getPassword(), DEFAULT_ITERATIONS, salt, DERIVED_KEY_SIZE)) - .append("\",\"salt\":\"") - .append(Base64.encodeBytes(salt)) - .append("\",\"additionalParameters\":{}}"); - final Credential entity = Credential.builder() - .id(UUID.randomUUID()) - .userId(user.getId()) - .createdDate(Instant.now().toEpochMilli()) - .secretData(secretData.toString()) - .type("password") - .priority(10) - .credentialData("{\"hashIterations\":" + DEFAULT_ITERATIONS + ",\"algorithm\":\"" + ID + "\",\"additionalParameters\":{}}") - .build(); + public void updatePassword(UUID id, UserPasswordDto data) throws KeycloakRemoteException, AccessDeniedException, + UserNotFoundException { /* save */ - final Credential credential = credentialRepository.save(entity); - user.setCredentials(List.of(credential)); - log.info("Updated user password with id {}", user.getId()); - return user; + keycloakGateway.updateUserCredentials(id, data); + log.info("Updated user password with id {}", id); } @Override - @Transactional - public User toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, - UserAttributeNotFoundException { - /* check */ - final User user = find(id); - final UserAttribute entity = userAttributeService.update(user.getId(), "theme_dark", data.getThemeDark().toString()); - log.info("Updated theme by updating attribute with id {}", entity.getId()); - return user; + public UserDto toggleTheme(UUID id, UserThemeSetDto data) throws UserNotFoundException, KeycloakRemoteException, + AccessDeniedException { + /* save */ + keycloakGateway.updateUserAttributes(id, userMapper.userThemeSetDtoToUserAttributesDto(data)); + log.info("Updated theme by updating attribute with id {}", id); + return userMapper.keycloakUserDtoToUserDto(keycloakGateway.findById(id)); } @Override - @Transactional(readOnly = true) public void validateUsernameNotExists(String username) throws UserAlreadyExistsException { - final Optional<User> optional = userRepository.findByUsername(username); - if (optional.isPresent()) { + 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 */ } } @Override - @Transactional(readOnly = true) public void validateEmailNotExists(String email) throws UserEmailAlreadyExistsException { - final Optional<User> optional = userRepository.findByEmail(email); - if (optional.isPresent()) { - log.error("User with email {} already exists", email); - throw new UserEmailAlreadyExistsException("User with email already exists"); - } - } - - private String encodedCredential(String rawPassword, int iterations, byte[] salt, int derivedKeySize) { - final String rawPasswordWithPadding = PaddingUtils.padding(rawPassword, MAX_PADDING_LENGTH); - final KeySpec spec = new PBEKeySpec(rawPasswordWithPadding.toCharArray(), salt, iterations, derivedKeySize); try { - byte[] key = getSecretKeyFactory().generateSecret(spec).getEncoded(); - return Base64.encodeBytes(key); - } catch (InvalidKeySpecException e) { - throw new RuntimeException("Credential could not be encoded", e); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private byte[] getSalt() { - byte[] buffer = new byte[16]; - final SecureRandom secureRandom = new SecureRandom(); - secureRandom.nextBytes(buffer); - return buffer; - } - - private SecretKeyFactory getSecretKeyFactory() { - try { - return SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(PBKDF2_ALGORITHM + " algorithm not found", e); + 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 */ } } } 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 ad27bf692b0d3c0095e0b963b2aa0a716a10e707..2cc7bb651ce2ed80ffbfd83adbaea9bea69e0364 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 @@ -4,7 +4,6 @@ import at.tuwien.api.database.ViewCreateDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.View; import at.tuwien.entities.database.table.columns.TableColumn; -import at.tuwien.entities.user.User; import at.tuwien.exception.*; import at.tuwien.mapper.ViewMapper; import at.tuwien.repository.mdb.ViewRepository; @@ -13,6 +12,7 @@ import at.tuwien.service.DatabaseService; import at.tuwien.service.QueryService; import at.tuwien.service.UserService; import at.tuwien.service.ViewService; +import at.tuwien.utils.UserUtil; import com.google.common.hash.Hashing; import com.mchange.v2.c3p0.ComboPooledDataSource; import lombok.extern.log4j.Log4j2; @@ -124,7 +124,6 @@ public class ViewServiceImpl extends HibernateConnector implements ViewService { ViewMalformedException, UserNotFoundException { /* find */ final Database database = databaseService.find(databaseId); - final User user = userService.findByUsername(principal.getName()); /* create view */ final ComboPooledDataSource dataSource = getPrivilegedDataSource(database.getContainer().getImage(), database.getContainer(), database); @@ -151,7 +150,7 @@ public class ViewServiceImpl extends HibernateConnector implements ViewService { .database(database) .name(data.getName()) .internalName(viewMapper.nameToInternalName(data.getName())) - .createdBy(user.getId()) + .createdBy(UserUtil.getId(principal)) .query(data.getQuery()) .queryHash(Hashing.sha256() .hashString(data.getQuery(), StandardCharsets.UTF_8) 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 d92383be87c0dd0e5bdc3fb64dbf2b101a060374..54f56a8ff25863b2e6018c4c28a4ee0fa9e9cff9 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 @@ -49,10 +49,6 @@ 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.Realm; -import at.tuwien.entities.user.Role; -import at.tuwien.entities.user.User; -import at.tuwien.entities.user.UserAttribute; import at.tuwien.querystore.Query; import at.tuwien.test.utils.ArrayUtil; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -217,36 +213,13 @@ public abstract class BaseTest { public final static String ROLE_DEFAULT_REALM_DBREPO_ROLES_NAME = "default-dbrepo-roles"; public final static UUID ROLE_DEFAULT_REALM_DBREPO_ROLES_REALM_ID = REALM_DBREPO_ID; - public final static Role ROLE_DEFAULT_REALM_DBREPO_ROLES = Role.builder() - .id(ROLE_DEFAULT_REALM_DBREPO_ROLES_ID) - .name(ROLE_DEFAULT_REALM_DBREPO_ROLES_NAME) - .realmId(ROLE_DEFAULT_REALM_DBREPO_ROLES_REALM_ID) - .build(); - - public final static Realm REALM_DBREPO = Realm.builder() - .id(REALM_DBREPO_ID) - .name(REALM_DBREPO_NAME) - .enabled(REALM_DBREPO_ENABLED) - .defaultRole(ROLE_DEFAULT_REALM_DBREPO_ROLES_ID) - .build(); - public final static UUID ROLE_DEFAULT_RESEARCHER_ROLES_ID = UUID.fromString("c74cbbe7-3ab1-4472-9211-cc9045672682"); public final static String ROLE_DEFAULT_RESEARCHER_ROLES_NAME = "default-researcher-roles"; public final static UUID ROLE_DEFAULT_RESEARCHER_ROLES_REALM_ID = REALM_DBREPO_ID; - public final static Role ROLE_DEFAULT_RESEARCHER_ROLES = Role.builder() - .id(ROLE_DEFAULT_RESEARCHER_ROLES_ID) - .name(ROLE_DEFAULT_RESEARCHER_ROLES_NAME) - .realmId(ROLE_DEFAULT_RESEARCHER_ROLES_REALM_ID) - .build(); - public final static String USER_BROKER_USERNAME = "guest"; public final static String USER_BROKER_PASSWORD = "guest"; - public final static User USER_BROKER = User.builder() - .username(USER_BROKER_USERNAME) - .build(); - public final static UUID USER_1_ID = UUID.fromString("cd5bab0d-7799-4069-85fb-c5d738572a0b"); public final static String USER_1_EMAIL = "john.doe@example.com"; public final static String USER_1_USERNAME = "junit1"; @@ -279,68 +252,10 @@ public abstract class BaseTest { .write("") .build(); - public final static List<UserAttribute> USER_1_ATTRIBUTES = List.of(UserAttribute.builder() - .id(UUID.fromString("c466a105-5bbd-4afc-87ae-751d5037d9ab")) - .userId(USER_1_ID) - .name("theme_dark") - .value("false") - .build(), - UserAttribute.builder() - .id(UUID.fromString("0870498b-d6ac-4543-bef1-830142de96d7")) - .userId(USER_1_ID) - .name("orcid") - .value(USER_1_ORCID_UNCOMPRESSED) - .build(), - UserAttribute.builder() - .id(UUID.fromString("42b06e7f-9df2-4b1c-bdfb-904401d6ad36")) - .userId(USER_1_ID) - .name("affiliation") - .value(USER_1_AFFILIATION) - .build()); - - public final static List<UserAttributeDto> USER_1_ATTRIBUTES_DTO = List.of(UserAttributeDto.builder() - .id(UUID.fromString("c466a105-5bbd-4afc-87ae-751d5037d9ab")) - .userId(USER_1_ID) - .name("theme_dark") - .value("false") - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("0870498b-d6ac-4543-bef1-830142de96d7")) - .userId(USER_1_ID) - .name("orcid") - .value(USER_1_ORCID_UNCOMPRESSED) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("42b06e7f-9df2-4b1c-bdfb-904401d6ad36")) - .userId(USER_1_ID) - .name("affiliation") - .value(USER_1_AFFILIATION) - .build()); - - public final static User USER_1 = User.builder() - .id(USER_1_ID) - .username(USER_1_USERNAME) - .email(USER_1_EMAIL) - .databasePassword(USER_1_DATABASE_PASSWORD) - .firstname(USER_1_FIRSTNAME) - .lastname(USER_1_LASTNAME) - .emailVerified(USER_1_VERIFIED) - .enabled(USER_1_ENABLED) - .realmId(USER_1_REALM_ID) - .attributes(USER_1_ATTRIBUTES) - .build(); - - public final static User USER_1_SIMPLE = User.builder() - .id(USER_1_ID) - .username(USER_1_USERNAME) - .email(USER_1_EMAIL) - .databasePassword(USER_1_DATABASE_PASSWORD) - .firstname(USER_1_FIRSTNAME) - .lastname(USER_1_LASTNAME) - .emailVerified(USER_1_VERIFIED) - .enabled(USER_1_ENABLED) - .realmId(USER_1_REALM_ID) - .attributes(List.of() /* for jpa */) + public final static UserAttributesDto USER_1_ATTRIBUTES_DTO = UserAttributesDto.builder() + .themeDark(USER_1_THEME_DARK) + .orcid(USER_1_ORCID_UNCOMPRESSED) + .affiliation(USER_1_AFFILIATION) .build(); public final static UserDto USER_1_DTO = UserDto.builder() @@ -405,70 +320,10 @@ public abstract class BaseTest { public final static Instant USER_2_LAST_MODIFIED = USER_1_CREATED; public final static UUID USER_2_REALM_ID = REALM_DBREPO_ID; - public final static List<UserAttribute> USER_2_ATTRIBUTES = List.of(UserAttribute.builder() - .id(UUID.fromString("23da2c08-cb8a-4e18-a7f0-70c30de2771e")) - .userId(USER_2_ID) - .name("theme_dark") - .value("false") - .build(), - UserAttribute.builder() - .id(UUID.fromString("83223dfd-1c80-4132-8c74-a38994f45f4a")) - .userId(USER_2_ID) - .name("orcid") - .value(USER_2_ORCID_UNCOMPRESSED) - .build(), - UserAttribute.builder() - .id(UUID.fromString("a29879fd-9801-4adf-bf3a-16bbff6ea207")) - .userId(USER_2_ID) - .name("affiliation") - .value(USER_2_AFFILIATION) - .build()); - - public final static List<UserAttributeDto> USER_2_ATTRIBUTES_DTO = List.of(UserAttributeDto.builder() - .id(UUID.fromString("23da2c08-cb8a-4e18-a7f0-70c30de2771e")) - .userId(USER_2_ID) - .name("theme_dark") - .value("false") - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("83223dfd-1c80-4132-8c74-a38994f45f4a")) - .userId(USER_2_ID) - .name("orcid") - .value(USER_2_ORCID_UNCOMPRESSED) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("a29879fd-9801-4adf-bf3a-16bbff6ea207")) - .userId(USER_2_ID) - .name("affiliation") - .value(USER_2_AFFILIATION) - .build()); - - public final static User USER_2 = User.builder() - .id(USER_2_ID) - .username(USER_2_USERNAME) - .email(USER_2_EMAIL) - .emailVerified(true) - .databasePassword(USER_2_DATABASE_PASSWORD) - .firstname(USER_2_FIRSTNAME) - .lastname(USER_2_LASTNAME) - .emailVerified(USER_2_VERIFIED) - .enabled(USER_2_ENABLED) - .realmId(USER_2_REALM_ID) - .attributes(USER_2_ATTRIBUTES) - .build(); - - public final static User USER_2_SIMPLE = User.builder() - .id(USER_2_ID) - .username(USER_2_USERNAME) - .email(USER_2_EMAIL) - .emailVerified(true) - .databasePassword(USER_2_DATABASE_PASSWORD) - .firstname(USER_2_FIRSTNAME) - .lastname(USER_2_LASTNAME) - .emailVerified(USER_2_VERIFIED) - .enabled(USER_2_ENABLED) - .realmId(USER_2_REALM_ID) - .attributes(List.of() /* for jpa */) + public final static UserAttributesDto USER_2_ATTRIBUTES_DTO = UserAttributesDto.builder() + .themeDark(USER_2_THEME_DARK) + .orcid(USER_2_ORCID_UNCOMPRESSED) + .affiliation(USER_2_AFFILIATION) .build(); public final static UserDto USER_2_DTO = UserDto.builder() @@ -515,7 +370,7 @@ 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 = 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 */; @@ -525,70 +380,10 @@ public abstract class BaseTest { public final static Instant USER_3_CREATED = Instant.ofEpochSecond(1677399559) /* 2023-02-26 08:19:19 (UTC) */; public final static UUID USER_3_REALM_ID = REALM_DBREPO_ID; - public final static List<UserAttribute> USER_3_ATTRIBUTES = List.of(UserAttribute.builder() - .id(UUID.fromString("58062219-7b99-4c0d-b00b-136b7d916c04")) - .userId(USER_3_ID) - .name("theme_dark") - .value(USER_3_THEME_DARK.toString()) - .build(), - UserAttribute.builder() - .id(UUID.fromString("384851ee-83c4-4cda-805e-be0c1bab71eb")) - .userId(USER_3_ID) - .name("orcid") - .value(null) - .build(), - UserAttribute.builder() - .id(UUID.fromString("c2cb2357-5e34-453f-b080-ca1c97f56d4a")) - .userId(USER_3_ID) - .name("affiliation") - .value(USER_3_AFFILIATION) - .build()); - - public final static List<UserAttributeDto> USER_3_ATTRIBUTES_DTO = List.of(UserAttributeDto.builder() - .id(UUID.fromString("58062219-7b99-4c0d-b00b-136b7d916c04")) - .userId(USER_3_ID) - .name("theme_dark") - .value(USER_3_THEME_DARK.toString()) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("384851ee-83c4-4cda-805e-be0c1bab71eb")) - .userId(USER_3_ID) - .name("orcid") - .value(null) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("c2cb2357-5e34-453f-b080-ca1c97f56d4a")) - .userId(USER_3_ID) - .name("affiliation") - .value(USER_3_AFFILIATION) - .build()); - - public final static User USER_3 = User.builder() - .id(USER_3_ID) - .username(USER_3_USERNAME) - .email(USER_3_EMAIL) - .emailVerified(true) - .databasePassword(USER_3_DATABASE_PASSWORD) - .firstname(USER_3_FIRSTNAME) - .lastname(USER_3_LASTNAME) - .emailVerified(USER_3_VERIFIED) - .enabled(USER_3_ENABLED) - .realmId(USER_3_REALM_ID) - .attributes(USER_3_ATTRIBUTES) - .build(); - - public final static User USER_3_SIMPLE = User.builder() - .id(USER_3_ID) - .username(USER_3_USERNAME) - .email(USER_3_EMAIL) - .emailVerified(true) - .databasePassword(USER_3_DATABASE_PASSWORD) - .firstname(USER_3_FIRSTNAME) - .lastname(USER_3_LASTNAME) - .emailVerified(USER_3_VERIFIED) - .enabled(USER_3_ENABLED) - .realmId(USER_3_REALM_ID) - .attributes(List.of() /* for jpa */) + public final static UserAttributesDto USER_3_ATTRIBUTES_DTO = UserAttributesDto.builder() + .themeDark(USER_3_THEME_DARK) + .orcid(USER_3_ORCID_UNCOMPRESSED) + .affiliation(USER_3_AFFILIATION) .build(); public final static UserDto USER_3_DTO = UserDto.builder() @@ -620,7 +415,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 = null; + public final static String USER_4_ORCID_UNCOMPRESSED = 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"; @@ -630,70 +425,10 @@ public abstract class BaseTest { public final static Instant USER_4_CREATED = Instant.ofEpochSecond(1677399592) /* 2023-02-26 08:19:52 (UTC) */; public final static UUID USER_4_REALM_ID = REALM_DBREPO_ID; - public final static List<UserAttribute> USER_4_ATTRIBUTES = List.of(UserAttribute.builder() - .id(UUID.fromString("58062219-7b99-4c0d-b00b-236b7d916c04")) - .userId(USER_4_ID) - .name("theme_dark") - .value(USER_4_THEME_DARK.toString()) - .build(), - UserAttribute.builder() - .id(UUID.fromString("384851ee-83c4-4cda-805e-ce0c1bab71eb")) - .userId(USER_4_ID) - .name("orcid") - .value(null) - .build(), - UserAttribute.builder() - .id(UUID.fromString("c2cb2357-5e34-453f-b080-da1c97f56d4a")) - .userId(USER_4_ID) - .name("affiliation") - .value(USER_4_AFFILIATION) - .build()); - - public final static List<UserAttributeDto> USER_4_ATTRIBUTES_DTO = List.of(UserAttributeDto.builder() - .id(UUID.fromString("58062219-7b99-4c0d-b00b-236b7d916c04")) - .userId(USER_4_ID) - .name("theme_dark") - .value(USER_4_THEME_DARK.toString()) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("384851ee-83c4-4cda-805e-ce0c1bab71eb")) - .userId(USER_4_ID) - .name("orcid") - .value(null) - .build(), - UserAttributeDto.builder() - .id(UUID.fromString("c2cb2357-5e34-453f-b080-da1c97f56d4a")) - .userId(USER_4_ID) - .name("affiliation") - .value(USER_4_AFFILIATION) - .build()); - - public final static User USER_4 = User.builder() - .id(USER_4_ID) - .username(USER_4_USERNAME) - .email(USER_4_EMAIL) - .emailVerified(true) - .databasePassword(USER_4_DATABASE_PASSWORD) - .firstname(USER_4_FIRSTNAME) - .lastname(USER_4_LASTNAME) - .emailVerified(USER_4_VERIFIED) - .enabled(USER_4_ENABLED) - .realmId(USER_4_REALM_ID) - .attributes(USER_4_ATTRIBUTES) - .build(); - - public final static User USER_4_SIMPLE = User.builder() - .id(USER_4_ID) - .username(USER_4_USERNAME) - .email(USER_4_EMAIL) - .emailVerified(true) - .databasePassword(USER_4_DATABASE_PASSWORD) - .firstname(USER_4_FIRSTNAME) - .lastname(USER_4_LASTNAME) - .emailVerified(USER_4_VERIFIED) - .enabled(USER_4_ENABLED) - .realmId(USER_4_REALM_ID) - .attributes(List.of() /* for jpa */) + public final static UserAttributesDto USER_4_ATTRIBUTES_DTO = UserAttributesDto.builder() + .themeDark(USER_4_THEME_DARK) + .orcid(USER_4_ORCID_UNCOMPRESSED) + .affiliation(USER_4_AFFILIATION) .build(); public final static UserDto USER_4_DTO = UserDto.builder() @@ -741,16 +476,6 @@ public abstract class BaseTest { public final static Instant USER_5_CREATED = Instant.ofEpochSecond(1677399592) /* 2023-02-26 08:19:52 (UTC) */; public final static UUID USER_5_REALM_ID = REALM_DBREPO_ID; - public final static User USER_5 = User.builder() - .id(USER_5_ID) - .username(USER_5_USERNAME) - .email(USER_5_EMAIL) - .emailVerified(USER_5_VERIFIED) - .enabled(USER_5_ENABLED) - .databasePassword(USER_5_DATABASE_PASSWORD) - .realmId(USER_5_REALM_ID) - .build(); - public final static UserDto USER_5_DTO = UserDto.builder() .id(USER_5_ID) .username(USER_5_USERNAME) @@ -785,16 +510,6 @@ public abstract class BaseTest { public final static Instant USER_6_CREATED = Instant.ofEpochSecond(1677399592) /* 2023-02-26 08:19:52 (UTC) */; public final static UUID USER_6_REALM_ID = REALM_DBREPO_ID; - public final static User USER_6 = User.builder() - .id(USER_6_ID) - .username(USER_6_USERNAME) - .email(USER_6_EMAIL) - .emailVerified(USER_6_VERIFIED) - .enabled(USER_6_ENABLED) - .databasePassword(USER_6_DATABASE_PASSWORD) - .realmId(USER_6_REALM_ID) - .build(); - public final static UserDto USER_6_DTO = UserDto.builder() .id(USER_6_ID) .username(USER_6_USERNAME) @@ -978,7 +693,6 @@ public abstract class BaseTest { public final static Long IMAGE_2_SIZE = 12000L; public final static Instant IMAGE_2_BUILT = Instant.now().minus(38, HOURS); - public final static Long CONTAINER_1_ID = 1L; public final static ContainerImage CONTAINER_1_IMAGE = IMAGE_1; public final static ImageBriefDto CONTAINER_1_IMAGE_BRIEF_DTO = IMAGE_1_BRIEF_DTO; @@ -1169,8 +883,8 @@ public abstract class BaseTest { public final static String DATABASE_1_EXCHANGE = "dbrepo." + DATABASE_1_INTERNALNAME; public final static Instant DATABASE_1_CREATED = Instant.ofEpochSecond(1677399741) /* 2023-02-26 08:22:21 (UTC) */; public final static Instant DATABASE_1_LAST_MODIFIED = Instant.ofEpochSecond(1677399741) /* 2023-02-26 08:22:21 (UTC) */; - public final static User DATABASE_1_OWNER = USER_1; - public final static User DATABASE_1_CREATOR = USER_1; + public final static UUID DATABASE_1_OWNER = USER_1_ID; + public final static UUID DATABASE_1_CREATOR = USER_1_ID; public final static Database DATABASE_1 = Database.builder() .id(DATABASE_1_ID) @@ -1185,12 +899,9 @@ public abstract class BaseTest { .exchangeName(DATABASE_1_EXCHANGE) .created(DATABASE_1_CREATED) .lastModified(DATABASE_1_LAST_MODIFIED) - .createdBy(USER_1_ID) - .ownedBy(USER_1_ID) + .createdBy(DATABASE_1_CREATOR) + .ownedBy(DATABASE_1_OWNER) .contactPerson(USER_1_ID) - .contact(USER_1) - .creator(DATABASE_1_CREATOR) - .owner(DATABASE_1_OWNER) .tables(List.of()) /* TABLE_1, TABLE_2, TABLE_3, TABLE_7 */ .views(List.of()) /* VIEW_2, VIEW_3 */ .build(); @@ -1211,9 +922,6 @@ public abstract class BaseTest { .createdBy(USER_1_ID) .ownedBy(USER_1_ID) .contactPerson(USER_1_ID) - .contact(null /* for jpa */) - .creator(null /* for jpa */) - .owner(null /* for jpa */) .tables(List.of() /* for jpa */) .views(List.of() /* for jpa */) .build(); @@ -1242,63 +950,54 @@ public abstract class BaseTest { .type(AccessType.READ) .hdbid(DATABASE_1_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_1_USER_1_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_1_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_1_USER_1_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_1_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_1_USER_2_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_1_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_1_USER_2_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_1_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_1_USER_2_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_1_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_1_USER_3_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_1_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_1_USER_3_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_1_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_1_USER_3_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_1_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseCreateDto DATABASE_1_CREATE = DatabaseCreateDto.builder() @@ -1315,8 +1014,8 @@ public abstract class BaseTest { public final static String DATABASE_2_EXCHANGE = "dbrepo." + DATABASE_2_INTERNALNAME; public final static Instant DATABASE_2_CREATED = Instant.ofEpochSecond(1677399772) /* 2023-02-26 08:22:52 (UTC) */; public final static Instant DATABASE_2_LAST_MODIFIED = Instant.ofEpochSecond(1677399772) /* 2023-02-26 08:22:52 (UTC) */; - public final static User DATABASE_2_OWNER = USER_2; - public final static User DATABASE_2_CREATOR = USER_2; + public final static UUID DATABASE_2_OWNER = USER_2_ID; + public final static UUID DATABASE_2_CREATOR = USER_2_ID; public final static Database DATABASE_2 = Database.builder() .id(DATABASE_2_ID) @@ -1331,12 +1030,9 @@ public abstract class BaseTest { .exchangeName(DATABASE_2_EXCHANGE) .created(DATABASE_2_CREATED) .lastModified(DATABASE_2_LAST_MODIFIED) - .createdBy(USER_2_ID) + .createdBy(DATABASE_2_CREATOR) .contactPerson(USER_2_ID) - .contact(USER_2) - .ownedBy(USER_2_ID) - .creator(DATABASE_2_CREATOR) - .owner(DATABASE_2_OWNER) + .ownedBy(DATABASE_2_OWNER) .tables(List.of()) /* TABLE_4, TABLE_5, TABLE_6 */ .views(List.of()) /* VIEW_4 */ .build(); @@ -1357,9 +1053,6 @@ public abstract class BaseTest { .createdBy(USER_2_ID) .ownedBy(USER_2_ID) .contactPerson(USER_1_ID) - .contact(null /* for jpa */) - .creator(null /* for jpa */) - .owner(null /* for jpa */) .tables(List.of() /* for jpa */) .views(List.of() /* for jpa */) .build(); @@ -1388,63 +1081,54 @@ public abstract class BaseTest { .type(AccessType.READ) .hdbid(DATABASE_2_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_2_USER_1_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_2_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_2_USER_1_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_2_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_2_USER_2_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_2_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_2_USER_2_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_2_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_2_USER_2_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_2_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_2_USER_3_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_2_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_2_USER_3_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_2_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_2_USER_3_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_2_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseCreateDto DATABASE_2_CREATE = DatabaseCreateDto.builder() @@ -1461,8 +1145,6 @@ public abstract class BaseTest { public final static String DATABASE_3_EXCHANGE = "dbrepo." + DATABASE_3_INTERNALNAME; public final static Instant DATABASE_3_CREATED = Instant.ofEpochSecond(1677399792) /* 2023-02-26 08:23:12 (UTC) */; public final static Instant DATABASE_3_LAST_MODIFIED = Instant.ofEpochSecond(1677399792) /* 2023-02-26 08:23:12 (UTC) */; - public final static User DATABASE_3_OWNER = USER_3; - public final static User DATABASE_3_CREATOR = USER_3; public final static Database DATABASE_3 = Database.builder() .id(DATABASE_3_ID) @@ -1478,11 +1160,8 @@ public abstract class BaseTest { .created(DATABASE_3_CREATED) .lastModified(DATABASE_3_LAST_MODIFIED) .contactPerson(USER_3_ID) - .contact(USER_3) .createdBy(USER_3_ID) .ownedBy(USER_3_ID) - .creator(DATABASE_3_CREATOR) - .owner(DATABASE_3_OWNER) .tables(List.of()) /* TABLE_8 */ .views(List.of()) /* VIEW_5 */ .build(); @@ -1501,11 +1180,8 @@ public abstract class BaseTest { .created(DATABASE_3_CREATED) .lastModified(DATABASE_3_LAST_MODIFIED) .contactPerson(USER_3_ID) - .contact(null /* for jpa */) .createdBy(USER_3_ID) .ownedBy(USER_3_ID) - .creator(null /* for jpa */) - .owner(null /* for jpa */) .tables(List.of() /* for jpa */) .views(List.of() /* for jpa */) .build(); @@ -1533,63 +1209,54 @@ public abstract class BaseTest { .type(AccessType.READ) .hdbid(DATABASE_3_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_3_USER_1_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_3_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_3_USER_1_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_3_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_3_USER_2_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_3_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_3_USER_2_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_3_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_3_USER_2_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_3_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_3_USER_3_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_3_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_3_USER_3_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_3_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_3_USER_3_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_3_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseCreateDto DATABASE_3_CREATE = DatabaseCreateDto.builder() @@ -1621,11 +1288,8 @@ public abstract class BaseTest { .created(DATABASE_4_CREATED) .lastModified(DATABASE_4_LAST_MODIFIED) .contactPerson(USER_4_ID) - .contact(USER_4) .createdBy(USER_4_ID) .ownedBy(USER_4_ID) - .creator(USER_4) - .owner(USER_4) .tables(List.of()) .views(List.of()) .build(); @@ -1671,11 +1335,8 @@ public abstract class BaseTest { .created(DATABASE_4_CREATED) .lastModified(DATABASE_4_LAST_MODIFIED) .contactPerson(USER_4_ID) - .contact(null /* for jpa */) .createdBy(USER_4_ID) .ownedBy(USER_4_ID) - .creator(null /* for jpa */) - .owner(null /* for jpa */) .tables(List.of() /* for jpa */) .views(List.of() /* for jpa */) .build(); @@ -1684,63 +1345,54 @@ public abstract class BaseTest { .type(AccessType.READ) .hdbid(DATABASE_4_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_4_USER_1_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_4_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_4_USER_1_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_4_ID) .huserid(USER_1_ID) - .user(USER_1) .build(); public final static DatabaseAccess DATABASE_4_USER_2_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_4_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_4_USER_2_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_4_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_4_USER_2_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_4_ID) .huserid(USER_2_ID) - .user(USER_2) .build(); public final static DatabaseAccess DATABASE_4_USER_3_READ_ACCESS = DatabaseAccess.builder() .type(AccessType.READ) .hdbid(DATABASE_4_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_4_USER_3_WRITE_OWN_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_OWN) .hdbid(DATABASE_4_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static DatabaseAccess DATABASE_4_USER_3_WRITE_ALL_ACCESS = DatabaseAccess.builder() .type(AccessType.WRITE_ALL) .hdbid(DATABASE_4_ID) .huserid(USER_3_ID) - .user(USER_3) .build(); public final static Long TABLE_1_ID = 1L; @@ -1769,9 +1421,9 @@ public abstract class BaseTest { .routingKey(TABLE_1_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null /* TABLE_1_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) .created(TABLE_1_CREATED) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .lastModified(TABLE_1_LAST_MODIFIED) .build(); @@ -1789,9 +1441,9 @@ public abstract class BaseTest { .routingKey(TABLE_1_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null /* TABLE_1_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) .created(TABLE_1_CREATED) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .lastModified(TABLE_1_LAST_MODIFIED) .build(); @@ -1821,8 +1473,8 @@ public abstract class BaseTest { .routingKey(TABLE_2_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null /* TABLE_2_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_2_ID) + .ownedBy(USER_2_ID) .created(TABLE_2_CREATED) .lastModified(TABLE_2_LAST_MODIFIED) .build(); @@ -1841,8 +1493,8 @@ public abstract class BaseTest { .routingKey(TABLE_2_ROUTING_KEY) .columns(List.of() /* for jpa */) .constraints(null /* TABLE_2_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_2_ID) + .ownedBy(USER_2_ID) .created(TABLE_2_CREATED) .lastModified(TABLE_2_LAST_MODIFIED) .build(); @@ -1873,8 +1525,8 @@ public abstract class BaseTest { .routingKey(TABLE_3_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null /* TABLE_3_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_3_ID) + .ownedBy(USER_3_ID) .created(TABLE_3_CREATED) .lastModified(TABLE_3_LAST_MODIFIED) .build(); @@ -1893,8 +1545,8 @@ public abstract class BaseTest { .routingKey(TABLE_3_ROUTING_KEY) .columns(List.of() /* for jpa */) .constraints(null /* TABLE_3_CONSTRAINTS */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_3_ID) + .ownedBy(USER_3_ID) .created(TABLE_3_CREATED) .lastModified(TABLE_3_LAST_MODIFIED) .build(); @@ -1949,8 +1601,8 @@ public abstract class BaseTest { .routingKey(TABLE_4_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null) /* TABLE_4_CONSTRAINTS */ - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .build(); public final static Table TABLE_4_SIMPLE = Table.builder() @@ -1967,8 +1619,8 @@ public abstract class BaseTest { .routingKey(TABLE_4_ROUTING_KEY) .columns(List.of() /* for jpa */) .constraints(null /* for jpa */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .build(); public final static TableCsvDto TABLE_4_CSV_DTO = TableCsvDto.builder() @@ -2001,8 +1653,8 @@ public abstract class BaseTest { .routingKey(TABLE_5_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null) /* TABLE_5_CONSTRAINTS */ - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_5_CREATED) .lastModified(TABLE_5_LAST_MODIFIED) .build(); @@ -2021,8 +1673,8 @@ public abstract class BaseTest { .routingKey(TABLE_5_ROUTING_KEY) .columns(List.of() /* for jpa */) .constraints(null /* for jpa */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_5_CREATED) .lastModified(TABLE_5_LAST_MODIFIED) .build(); @@ -2051,8 +1703,8 @@ public abstract class BaseTest { .routingKey(TABLE_6_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) .constraints(null) /* TABLE_6_CONSTRAINTS */ - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_6_CREATED) .lastModified(TABLE_6_LAST_MODIFIED) .build(); @@ -2070,8 +1722,8 @@ public abstract class BaseTest { .queueName(TABLE_6_QUEUE_NAME) .routingKey(TABLE_6_ROUTING_KEY) .columns(List.of() /* for jpa */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_6_CREATED) .lastModified(TABLE_6_LAST_MODIFIED) .build(); @@ -2098,8 +1750,8 @@ public abstract class BaseTest { .queueName(TABLE_7_QUEUE_NAME) .routingKey(TABLE_7_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_7_CREATED) .lastModified(TABLE_7_LAST_MODIFIED) .build(); @@ -2116,8 +1768,8 @@ public abstract class BaseTest { .queueName(TABLE_7_QUEUE_NAME) .routingKey(TABLE_7_ROUTING_KEY) .columns(List.of() /* for jpa */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_7_CREATED) .lastModified(TABLE_7_LAST_MODIFIED) .build(); @@ -2207,8 +1859,8 @@ public abstract class BaseTest { .queueName(TABLE_8_QUEUE_NAME) .routingKey(TABLE_8_ROUTING_KEY) .columns(List.of() /* needs to be set in the junit tests */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_8_CREATED) .lastModified(TABLE_8_LAST_MODIFIED) .build(); @@ -2225,8 +1877,8 @@ public abstract class BaseTest { .queueName(TABLE_8_QUEUE_NAME) .routingKey(TABLE_8_ROUTING_KEY) .columns(List.of() /* for jpa */) - .creator(USER_1) - .owner(USER_1) + .createdBy(USER_1_ID) + .ownedBy(USER_1_ID) .created(TABLE_8_CREATED) .lastModified(TABLE_8_LAST_MODIFIED) .build(); @@ -5271,7 +4923,6 @@ public abstract class BaseTest { .query(VIEW_1_QUERY) .queryHash(VIEW_1_QUERY_HASH) .createdBy(USER_1_ID) - .creator(USER_1) .columns(VIEW_1_COLUMNS) .build(); @@ -5375,7 +5026,6 @@ public abstract class BaseTest { .columns(VIEW_2_COLUMNS) .query(VIEW_2_QUERY) .queryHash(VIEW_2_QUERY_HASH) - .creator(USER_1) .createdBy(USER_1_ID) .build(); @@ -5515,7 +5165,6 @@ public abstract class BaseTest { .columns(VIEW_3_COLUMNS) .query(VIEW_3_QUERY) .queryHash(VIEW_3_QUERY_HASH) - .creator(USER_1) .createdBy(USER_1_ID) .build(); @@ -5777,7 +5426,6 @@ public abstract class BaseTest { .query(VIEW_4_QUERY) .queryHash(VIEW_4_QUERY_HASH) .createdBy(USER_1_ID) - .creator(USER_1) .columns(VIEW_4_COLUMNS) .build(); @@ -5800,7 +5448,6 @@ public abstract class BaseTest { .isPublic(VIEW_5_PUBLIC) .query(VIEW_5_QUERY) .queryHash(VIEW_5_QUERY_HASH) - .creator(USER_1) .createdBy(USER_1_ID) .build(); @@ -5916,7 +5563,6 @@ public abstract class BaseTest { public final static IdentifierType IDENTIFIER_1_TYPE = IdentifierType.DATABASE; public final static IdentifierTypeDto IDENTIFIER_1_TYPE_DTO = IdentifierTypeDto.DATABASE; public final static UUID IDENTIFIER_1_CREATED_BY = USER_1_ID; - public final static User IDENTIFIER_1_CREATOR = USER_1; public final static VisibilityType IDENTIFIER_1_VISIBILITY = VisibilityType.EVERYONE; public final static VisibilityTypeDto IDENTIFIER_1_VISIBILITY_DTO = VisibilityTypeDto.EVERYONE; @@ -6139,7 +5785,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_1_RESULT_NUMBER) .publisher(IDENTIFIER_1_PUBLISHER) .type(IDENTIFIER_1_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of(LICENSE_1)) .creators(List.of(IDENTIFIER_1_CREATOR_1)) .funders(List.of(IDENTIFIER_1_FUNDER_1)) @@ -6166,7 +5812,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_1_RESULT_NUMBER) .publisher(IDENTIFIER_1_PUBLISHER) .type(IDENTIFIER_1_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of() /* for jpa */) .creators(List.of() /* for jpa */) .funders(List.of() /* for jpa */) @@ -6193,7 +5839,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_1_RESULT_NUMBER) .publisher(IDENTIFIER_1_PUBLISHER) .type(IDENTIFIER_1_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of(LICENSE_1)) .creators(List.of(IDENTIFIER_1_CREATOR_1)) .funders(List.of(IDENTIFIER_1_FUNDER_1)) @@ -6322,8 +5968,6 @@ public abstract class BaseTest { public final static String IDENTIFIER_2_PUBLISHER = "Australian Government"; public final static IdentifierType IDENTIFIER_2_TYPE = IdentifierType.SUBSET; public final static IdentifierTypeDto IDENTIFIER_2_TYPE_DTO = IdentifierTypeDto.SUBSET; - public final static UUID IDENTIFIER_2_CREATED_BY = USER_2_ID; - public final static User IDENTIFIER_2_CREATOR = USER_2; public final static VisibilityType IDENTIFIER_2_VISIBILITY = VisibilityType.SELF; public final static VisibilityTypeDto IDENTIFIER_2_VISIBILITY_DTO = VisibilityTypeDto.SELF; @@ -6487,7 +6131,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_2_RESULT_NUMBER) .publisher(IDENTIFIER_2_PUBLISHER) .type(IDENTIFIER_2_TYPE) - .creator(USER_2) + .createdBy(USER_2_ID) .creators(List.of(IDENTIFIER_2_CREATOR_1, IDENTIFIER_2_CREATOR_2)) .visibility(IDENTIFIER_2_VISIBILITY) .build(); @@ -6513,7 +6157,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_2_RESULT_NUMBER) .publisher(IDENTIFIER_2_PUBLISHER) .type(IDENTIFIER_2_TYPE) - .creator(USER_2) + .createdBy(USER_2_ID) .creators(List.of() /* for jpa */) .visibility(IDENTIFIER_2_VISIBILITY) .build(); @@ -6616,8 +6260,6 @@ public abstract class BaseTest { public final static String IDENTIFIER_3_PUBLISHER = "Norwegian Government"; public final static IdentifierType IDENTIFIER_3_TYPE = IdentifierType.SUBSET; public final static IdentifierTypeDto IDENTIFIER_3_TYPE_DTO = IdentifierTypeDto.SUBSET; - public final static UUID IDENTIFIER_3_CREATOR_ID = USER_3_ID; - public final static User IDENTIFIER_3_CREATOR = USER_3; public final static VisibilityType IDENTIFIER_3_VISIBILITY = VisibilityType.EVERYONE; public final static VisibilityTypeDto IDENTIFIER_3_VISIBILITY_DTO = VisibilityTypeDto.EVERYONE; @@ -6796,7 +6438,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_3_RESULT_NUMBER) .publisher(IDENTIFIER_3_PUBLISHER) .type(IDENTIFIER_3_TYPE) - .creator(IDENTIFIER_3_CREATOR) + .createdBy(USER_3_ID) .licenses(List.of(LICENSE_1)) .creators(List.of(IDENTIFIER_3_CREATOR_1, IDENTIFIER_3_CREATOR_2, IDENTIFIER_3_CREATOR_3)) .visibility(IDENTIFIER_3_VISIBILITY) @@ -6823,7 +6465,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_3_RESULT_NUMBER) .publisher(IDENTIFIER_3_PUBLISHER) .type(IDENTIFIER_3_TYPE) - .creator(IDENTIFIER_3_CREATOR) + .createdBy(USER_3_ID) .licenses(List.of() /* for jpa */) .creators(List.of() /* for jpa */) .visibility(IDENTIFIER_3_VISIBILITY) @@ -6903,8 +6545,6 @@ public abstract class BaseTest { public final static String IDENTIFIER_4_PUBLISHER = "Swedish Government"; public final static IdentifierType IDENTIFIER_4_TYPE = IdentifierType.DATABASE; public final static IdentifierTypeDto IDENTIFIER_4_TYPE_DTO = IdentifierTypeDto.DATABASE; - public final static UUID IDENTIFIER_4_CREATOR_ID = USER_4_ID; - public final static User IDENTIFIER_4_CREATOR = USER_4; public final static VisibilityType IDENTIFIER_4_VISIBILITY = VisibilityType.EVERYONE; public final static VisibilityTypeDto IDENTIFIER_4_VISIBILITY_DTO = VisibilityTypeDto.EVERYONE; @@ -6956,7 +6596,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_4_RESULT_NUMBER) .publisher(IDENTIFIER_4_PUBLISHER) .type(IDENTIFIER_4_TYPE) - .creator(IDENTIFIER_4_CREATOR) + .createdBy(USER_4_ID) .licenses(List.of()) .creators(List.of()) .funders(List.of()) @@ -6983,7 +6623,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_4_RESULT_NUMBER) .publisher(IDENTIFIER_4_PUBLISHER) .type(IDENTIFIER_4_TYPE) - .creator(IDENTIFIER_4_CREATOR) + .createdBy(USER_4_ID) .licenses(List.of()) .funders(List.of()) .creators(List.of()) @@ -7059,8 +6699,6 @@ public abstract class BaseTest { public final static String IDENTIFIER_5_PUBLISHER = "Swedish Government"; public final static IdentifierType IDENTIFIER_5_TYPE = IdentifierType.SUBSET; public final static IdentifierTypeDto IDENTIFIER_5_TYPE_DTO = IdentifierTypeDto.SUBSET; - public final static UUID IDENTIFIER_5_CREATOR_ID = USER_1_ID; - public final static User IDENTIFIER_5_CREATOR = USER_1; public final static VisibilityType IDENTIFIER_5_VISIBILITY = VisibilityType.EVERYONE; public final static VisibilityTypeDto IDENTIFIER_5_VISIBILITY_DTO = VisibilityTypeDto.EVERYONE; @@ -7084,7 +6722,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_5_RESULT_NUMBER) .publisher(IDENTIFIER_5_PUBLISHER) .type(IDENTIFIER_5_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of(LICENSE_1)) .creators(List.of()) .visibility(IDENTIFIER_5_VISIBILITY) @@ -7110,7 +6748,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_5_RESULT_NUMBER) .publisher(IDENTIFIER_5_PUBLISHER) .type(IDENTIFIER_5_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of() /* for jpa */) .creators(List.of() /* for jpa */) .visibility(IDENTIFIER_5_VISIBILITY) @@ -7175,8 +6813,6 @@ public abstract class BaseTest { public final static String IDENTIFIER_6_PUBLISHER = "Polish Government"; public final static IdentifierType IDENTIFIER_6_TYPE = IdentifierType.VIEW; public final static IdentifierTypeDto IDENTIFIER_6_TYPE_DTO = IdentifierTypeDto.VIEW; - public final static UUID IDENTIFIER_6_CREATOR_ID = USER_1_ID; - public final static User IDENTIFIER_6_CREATOR = USER_1; public final static VisibilityType IDENTIFIER_6_VISIBILITY = VisibilityType.EVERYONE; public final static VisibilityTypeDto IDENTIFIER_6_VISIBILITY_DTO = VisibilityTypeDto.EVERYONE; @@ -7201,7 +6837,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_6_RESULT_NUMBER) .publisher(IDENTIFIER_6_PUBLISHER) .type(IDENTIFIER_6_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of(LICENSE_1)) .creators(List.of()) .visibility(IDENTIFIER_6_VISIBILITY) @@ -7228,7 +6864,7 @@ public abstract class BaseTest { .resultNumber(IDENTIFIER_6_RESULT_NUMBER) .publisher(IDENTIFIER_6_PUBLISHER) .type(IDENTIFIER_6_TYPE) - .creator(USER_1) + .createdBy(USER_1_ID) .licenses(List.of(LICENSE_1)) .creators(List.of()) .visibility(IDENTIFIER_6_VISIBILITY)