Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

프로젝트 엔티티 생성시 프로젝트 키를 만든다. (#111) #116

Merged
merged 5 commits into from
Jul 15, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,34 +37,34 @@ public CommentResponse save(User user, CommentCreateRequest commentRequest) {

private Project getBySecretKey(CommentCreateRequest commentRequest) {
return projects.findBySecretKey(commentRequest.getProjectSecretKey())
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException);
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException);
}

private Comment savedComment(User user, CommentCreateRequest commentRequest, Project project) {
Comment comment = Comment.builder()
.user(user)
.content(commentRequest.getContent())
.project(project)
.url(commentRequest.getUrl())
.build();
.user(user)
.content(commentRequest.getContent())
.project(project)
.url(commentRequest.getUrl())
.build();
return comments.save(comment);
}

private User savedGuestUser(CommentCreateRequest commentRequest) {
User user = GuestUser.builder()
.nickName(commentRequest.getGuestNickName())
.password(commentRequest.getGuestPassword())
.build();
.nickName(commentRequest.getGuestNickName())
.password(commentRequest.getGuestPassword())
.build();
return users.save(user);
}

public List<CommentResponse> findAllComments(String url) {
List<Comment> foundComments = comments.findByUrl(url);
return foundComments.stream()
.map(comment -> CommentResponse.of(
comment, UserResponse.of(
comment.getUser(), users.findUserTypeById(comment.getUser().getId()))))
.collect(Collectors.toList());
.map(comment -> CommentResponse.of(
comment, UserResponse.of(
comment.getUser(), users.findUserTypeById(comment.getUser().getId()))))
.collect(Collectors.toList());
}

public void updateContent(Long id, User user, CommentUpdateRequest request) {
Expand All @@ -82,15 +82,15 @@ public void delete(Long id, User user, CommentDeleteRequest request) {

private Comment returnValidatedComment(Long id, User user) {
Comment comment = comments.findById(id)
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_COMMENT::getException);
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_COMMENT::getException);
matchUserWithComment(user, comment);
return comment;
}

private User findRegisteredUser(User user, Long guestUserId, String guestUserPassword) {
if (!user.isLoginUser()) {
user = users.findById(guestUserId)
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException);
.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException);
validateGuestUser(user, guestUserPassword);
}
return user;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,4 @@ public class ProjectCreateRequest {

@NotNull
private String name;
@NotNull
private String secretKey;
@NotNull
private Long userId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ public class ProjectResponse {

private Long id;
private String name;
private String secretKey;

public static ProjectResponse of(Project project) {
return new ProjectResponse(project.getId(), project.getName());
return new ProjectResponse(project.getId(), project.getName(), project.getSecretKey());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.darass.darass.common.domain.BaseTimeEntity;
import com.darass.darass.user.domain.User;
import java.util.Random;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
Expand Down Expand Up @@ -34,9 +35,22 @@ public class Project extends BaseTimeEntity {
private String secretKey;

@Builder
public Project(User user, String name, String secretKey) {
public Project(User user, String name) {
this.user = user;
this.name = name;
this.secretKey = secretKey;
this.secretKey = createRandomSecretKey();
}

private String createRandomSecretKey() {
int leftLimit = 48; // numeral '0'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();

return random.ints(leftLimit, rightLimit + 1)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아주 확률이 낮지만 secretKey가 중복될 수 있지 않을까요? 더 확률을 낮춰 보는것은 어떨까요??

Copy link
Collaborator

@jujubebat jujubebat Jul 15, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가로 ProjectKey를 VO로 만들고, 그 안에 키 생성 로직을 담아도 될 것 같아요! (단일책임원칙)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • targetStringLength의 길이를 늘려서 중복될 확률을 낮춰봤어요!
  • 테스트 가능한 코드를 만들다 보니, 인터페이스를 분리하게 됐는 데, 자연스럽게 단일 책임 원칙을 지키게 된 건지 확인 부탁드릴게요!
  • 시크릿 키가 중복으로 들어올 때, 예외 발생을 하도록 추가 처리했어요! 그리고 이에 따른 테스트 코드도 추가했습니다.
  • 부가적으로 중복 부분에 해당하는 테스트 코드를 작성했는데 자코코에서 통과가 안되길래, 자코코의 테스트 통과율을 더 낮췄습니당

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public class ProjectService {
public ProjectResponse save(ProjectCreateRequest projectRequest, User user) {
Project project = Project.builder()
.name(projectRequest.getName())
.secretKey(projectRequest.getSecretKey())
.user(user)
.build();
projects.save(project);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,6 @@ void deleteUnauthorized() throws Exception {
private void setUpProject() {
project = Project.builder()
.name("project")
.secretKey("secretKey")
.user(socialLoginUser)
.build();
projects.save(project);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,12 @@ public void save() throws Exception {
headerWithName("Authorization").description("JWT - Bearer 토큰")
),
requestFields(
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름"),
fieldWithPath("secretKey").type(JsonFieldType.STRING).description("프로젝트 시크릿 키"),
fieldWithPath("userId").type(JsonFieldType.NUMBER).description("사용자 id")
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름")
),
responseFields(
fieldWithPath("id").type(JsonFieldType.NUMBER).description("프로젝트 id"),
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름")
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름"),
fieldWithPath("secretKey").type(JsonFieldType.STRING).description("프로젝트 Secret Key")
))
);
}
Expand All @@ -77,7 +76,7 @@ public void save() throws Exception {
public void save_fail() throws Exception {
this.mockMvc.perform(post("/api/v1/projects")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(new ProjectCreateRequest("프로젝트이름", "a1nc3K", socialLoginUser.getId()))))
.content(asJsonString(new ProjectCreateRequest("프로젝트이름"))))
.andExpect(status().isUnauthorized())
.andDo(
document("api/v1/projects/post/2",
Expand All @@ -92,7 +91,7 @@ public void save_fail() throws Exception {
return this.mockMvc.perform(post("/api/v1/projects")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token)
.content(asJsonString(new ProjectCreateRequest("프로젝트이름", "a1nc3K", socialLoginUser.getId())))
.content(asJsonString(new ProjectCreateRequest("프로젝트이름")))
)
.andExpect(status().isCreated());
}
Expand All @@ -119,7 +118,8 @@ public void findAll() throws Exception {
),
responseFields(
fieldWithPath("[].id").type(JsonFieldType.NUMBER).description("프로젝트 id"),
fieldWithPath("[].name").type(JsonFieldType.STRING).description("프로젝트 이름")
fieldWithPath("[].name").type(JsonFieldType.STRING).description("프로젝트 이름"),
fieldWithPath("[].secretKey").type(JsonFieldType.STRING).description("프로젝트 Secret Key")
))
);
}
Expand Down Expand Up @@ -164,7 +164,8 @@ public void findOne() throws Exception {
),
responseFields(
fieldWithPath("id").type(JsonFieldType.NUMBER).description("프로젝트 id"),
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름")
fieldWithPath("name").type(JsonFieldType.STRING).description("프로젝트 이름"),
fieldWithPath("secretKey").type(JsonFieldType.STRING).description("프로젝트 Secret Key")
))
);
}
Expand Down