Skip to content

Commit

Permalink
enhancements(test): fixed database structure and enhanced tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zZHorizonZz committed Aug 3, 2023
1 parent 875206d commit 55a52e3
Show file tree
Hide file tree
Showing 26 changed files with 182 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ public class AccountEntity extends PanacheEntityBase {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "user_id")
private Long userId;

@Column(name = "type")
private String type;

Expand Down Expand Up @@ -52,7 +49,6 @@ public class AccountEntity extends PanacheEntityBase {
private String sessionState;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
private UserEntity user;

public AccountEntity() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ public class RefreshTokenEntity extends PanacheEntityBase {
@Column(name = "token", unique = true, length = 1024)
private String token;

@Column(name = "user_id")
private Long userId;

@Column(name = "revoked")
private boolean revoked;

Expand All @@ -36,7 +33,6 @@ public class RefreshTokenEntity extends PanacheEntityBase {
private Date updatedAt;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
private UserEntity user;

public RefreshTokenEntity() {
Expand Down
11 changes: 11 additions & 0 deletions server/src/main/java/dev/shiperist/entity/account/UserEntity.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package dev.shiperist.entity.account;

import dev.shiperist.entity.project.ProjectMemberEntity;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Date;
import java.util.List;

@Data
@Entity(name = "User")
Expand Down Expand Up @@ -33,6 +35,15 @@ public class UserEntity extends PanacheEntityBase {
@Column(name = "password")
private String password;

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<AccountEntity> accounts;

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<RefreshTokenEntity> refreshTokens;

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProjectMemberEntity> projectMembers;

public UserEntity() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,13 @@ public class ProjectAppEntity extends PanacheEntityBase {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "project_id")
private Long projectId;

@Column(name = "name", unique = true)
private String name;

@Column(name = "display_name")
@Column(name = "display_name", length = 128)
private String displayName;

@Column(name = "description")
@Column(name = "description", length = 1024)
private String description;

@Column(name = "image")
Expand All @@ -52,7 +49,6 @@ public class ProjectAppEntity extends PanacheEntityBase {
@Column(name = "release_type")
private ReleaseType releaseType;

@ManyToOne
@JoinColumn(name = "project_id", insertable = false, updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private ProjectEntity project;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.CreationTimestamp;

import java.util.ArrayList;
import java.util.List;

@Data
@Entity(name = "Project")
@Table(name = "project", schema = "public")
Expand Down Expand Up @@ -34,4 +37,10 @@ public class ProjectEntity extends PanacheEntityBase {
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private String createdAt;

@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProjectMemberEntity> projectMembers = new ArrayList<>();

@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProjectAppEntity> projectApps = new ArrayList<>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,12 @@ public class ProjectMemberEntity extends PanacheEntityBase {
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;

@Column(name = "user_id")
private Long userId;

@Column(name = "project_id")
private Long projectId;

@Column(name = "role")
private String role;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private UserEntity user;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "project_id", insertable = false, updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private ProjectEntity project;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import dev.shiperist.entity.account.AccountEntity;
import dev.shiperist.mapper.QuarkusMappingConfig;
import dev.shiperist.model.account.Account;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.*;

import java.util.List;

Expand All @@ -14,6 +12,9 @@ public interface AccountMapper {

List<Account> toDomainList(List<AccountEntity> entities);

@Mappings({
@Mapping(target="userId", expression="java(entity.getUser().getId())")
})
Account toDomain(AccountEntity entity);

@InheritInverseConfiguration(name = "toDomain")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import dev.shiperist.entity.account.RefreshTokenEntity;
import dev.shiperist.mapper.QuarkusMappingConfig;
import dev.shiperist.model.account.RefreshToken;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.*;

import java.util.List;

Expand All @@ -14,6 +12,9 @@ public interface RefreshTokenMapper {

List<RefreshToken> toDomainList(List<RefreshTokenEntity> entities);

@Mappings({
@Mapping(target = "userId", expression = "java(entity.getUser().getId())"),
})
RefreshToken toDomain(RefreshTokenEntity entity);

@InheritInverseConfiguration(name = "toDomain")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import dev.shiperist.entity.project.ProjectAppEntity;
import dev.shiperist.mapper.QuarkusMappingConfig;
import dev.shiperist.model.project.ProjectApp;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.*;

import java.util.List;

Expand All @@ -14,6 +12,9 @@ public interface ProjectAppMapper {

List<ProjectApp> toDomainList(List<ProjectAppEntity> entities);

@Mappings({
@Mapping(target="projectId", expression="java(entity.getProject().getId())")
})
ProjectApp toDomain(ProjectAppEntity entity);

@InheritInverseConfiguration(name = "toDomain")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
import dev.shiperist.entity.project.ProjectMemberEntity;
import dev.shiperist.mapper.QuarkusMappingConfig;
import dev.shiperist.model.project.ProjectMember;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.*;

import java.util.List;

@Mapper(config = QuarkusMappingConfig.class)
public interface ProjectMemberMapper {
List<ProjectMember> toDomainList(List<ProjectMemberEntity> entities);

@Mappings({
@Mapping(target="userId", expression="java(entity.getUser().getId())"),
@Mapping(target="projectId", expression="java(entity.getProject().getId())")
})
ProjectMember toDomain(ProjectMemberEntity entity);

@InheritInverseConfiguration(name = "toDomain")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import dev.shiperist.entity.account.AccountEntity;
import io.quarkus.hibernate.reactive.panache.PanacheRepositoryBase;
import io.quarkus.hibernate.reactive.panache.common.WithSession;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;

@WithSession
@ApplicationScoped
public class AccountRepository implements PanacheRepositoryBase<AccountEntity, Long> {

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ public Uni<RefreshTokenEntity> findByToken(String token) {
}

public Uni<Boolean> revokeAllForUser(Long userId) {
return update("revoked = true where userId = ?1", userId).map(updateResult -> updateResult > 0);
return update("revoked = true where user.id = ?1", userId).map(updateResult -> updateResult > 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ public class UserRepository implements PanacheRepositoryBase<UserEntity, Long> {
public Uni<UserEntity> findByEmail(String email) {
return find("email", email).firstResult();
}

public Uni<Boolean> isMember(Long userId, Long projectId) {
return count("id = ?1 and projects.id = ?2", userId, projectId).map(count -> count > 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
public class ProjectMemberRepository implements PanacheRepositoryBase<ProjectMemberEntity, Long> {

public Uni<Boolean> isMember(Long projectId, Long userId) {
return count("projectId = ?1 and userId = ?2", projectId, userId).map(count -> count > 0);
return count("project.id = ?1 and user.id = ?2", projectId, userId).map(count -> count > 0);
}
}
12 changes: 10 additions & 2 deletions server/src/main/java/dev/shiperist/resource/AuthResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,16 @@ public Uni<Response> getSettings() {
description = "The user with the given email already exists"
)
public Uni<Response> signUp(User user) {
return userService.createUser(user.getName(), user.getEmail(), user.getImage(), user.getPassword())
.onItem().ifNotNull().transform(u -> Response.status(Response.Status.CREATED).entity(u).build());
return userService.doesUserExist(user.getEmail()).flatMap(
exists -> {
if (exists) {
return Uni.createFrom().item(Response.status(Response.Status.BAD_REQUEST).entity(ErrorMessage.EMAIL_ALREADY_EXISTS).build());
} else {
return userService.createUser(user.getName(), user.getEmail(), user.getImage(), user.getPassword())
.onItem().ifNotNull().transform(u -> Response.status(Response.Status.CREATED).entity(u).build());
}
}
);
}

@POST
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.shiperist.resource.project;

import dev.shiperist.exception.ErrorMessage;
import dev.shiperist.model.project.Project;
import dev.shiperist.model.request.ProjectRequest;
import dev.shiperist.service.project.ProjectMemberService;
Expand Down Expand Up @@ -54,9 +55,14 @@ public class ProjectResource {
description = "The project already exists"
)
public Uni<Response> createProject(ProjectRequest request) {
return projectService.createProject(Long.parseLong(sub), request.getName(), request.getDisplayName(), request.getDescription(), request.getImage())
.onItem().ifNotNull().transform(project -> Response.status(Response.Status.CREATED).entity(project).build())
.onItem().ifNull().continueWith(Response.status(Response.Status.BAD_REQUEST).build());
return projectService.doesProjectExist(request.getName()).flatMap(exists -> {
if (!exists) {
return projectService.createProject(Long.parseLong(sub), request.getName(), request.getDisplayName(), request.getDescription(), request.getImage())
.map(project -> Response.status(Response.Status.CREATED).entity(project).build());
} else {
return Uni.createFrom().item(Response.status(Response.Status.BAD_REQUEST).entity(ErrorMessage.PROJECT_ALREADY_EXISTS).build());
}
});
}

@GET
Expand Down Expand Up @@ -95,9 +101,15 @@ public Uni<Response> getProject(@PathParam("id") Long id) {
description = "The project does not exist"
)
public Uni<Response> updateProject(@PathParam("id") Long id, ProjectRequest request) {
return projectService.updateProject(id, request.getName(), request.getDisplayName(), request.getDescription(), request.getImage())
.onItem().ifNotNull().transform(updated -> Response.ok(updated).build())
.onItem().ifNull().continueWith(Response.status(Response.Status.NOT_FOUND).build());
return projectService.doesProjectExist(request.getName()).flatMap(exists -> {
if (!exists) {
return projectService.updateProject(id, request.getName(), request.getDisplayName(), request.getDescription(), request.getImage())
.onItem().ifNotNull().transform(updated -> Response.ok(updated).build())
.onItem().ifNull().continueWith(Response.status(Response.Status.NOT_FOUND).build());
} else {
return Uni.createFrom().item(Response.status(Response.Status.BAD_REQUEST).entity(ErrorMessage.PROJECT_ALREADY_EXISTS).build());
}
});
}

@GET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import dev.shiperist.model.account.RefreshToken;
import dev.shiperist.model.account.User;
import dev.shiperist.repository.account.RefreshTokenRepository;
import dev.shiperist.repository.account.UserRepository;
import dev.shiperist.util.SecurityUtil;
import io.quarkus.hibernate.reactive.panache.common.WithTransaction;
import io.smallrye.mutiny.Uni;
Expand All @@ -18,17 +19,26 @@ public class TokenService {
@Inject
RefreshTokenRepository refreshTokenRepository;

@Inject
UserRepository userRepository;

@Inject
RefreshTokenMapper refreshTokenMapper;

@WithTransaction
public Uni<RefreshToken> createRefreshToken(User user) {
RefreshTokenEntity refreshToken = new RefreshTokenEntity();
return userRepository.findById(user.getId())
.flatMap(foundUser -> {
if (foundUser == null) {
return Uni.createFrom().failure(new NotFoundException("User not found"));
}

refreshToken.setUserId(user.getId());
refreshToken.setToken(SecurityUtil.generateRefreshToken());
RefreshTokenEntity refreshToken = new RefreshTokenEntity();
refreshToken.setUser(foundUser);
refreshToken.setToken(SecurityUtil.generateRefreshToken());

return refreshTokenRepository.persist(refreshToken).map(refreshTokenMapper::toDomain);
return refreshTokenRepository.persist(refreshToken).map(refreshTokenMapper::toDomain);
});
}

@WithTransaction
Expand All @@ -47,7 +57,7 @@ public Uni<RefreshToken> swapRefreshToken(String token) {

RefreshTokenEntity newRefreshToken = new RefreshTokenEntity();

newRefreshToken.setUserId(refreshToken.getUserId());
newRefreshToken.setUser(refreshToken.getUser());
newRefreshToken.setToken(SecurityUtil.generateRefreshToken());

return refreshTokenRepository.persist(refreshToken).replaceWith(refreshTokenRepository.persist(newRefreshToken));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public Uni<ProjectApp> createProjectApp(Long projectId, String name, String disp
projectApp.setImage(image);
projectApp.setOs(os);
projectApp.setReleaseType(releaseType);
projectApp.setProjectId(projectId);
projectApp.setProject(project);
return projectApp;
})
.onItem().ifNotNull().transformToUni(projectAppRepository::persistAndFlush)
Expand Down
Loading

0 comments on commit 55a52e3

Please sign in to comment.