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

Feat/#462 닉네임 변경 API 구현 #470

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
9ef006e
feat: 닉네임 변경 API 구현
Cyma-s Sep 26, 2023
95bd4c7
docs: API 명세 추가
Cyma-s Sep 26, 2023
ee8bc8a
style: 개행 추가 및 불필요한 공백 삭제, static import 삭제
Cyma-s Sep 27, 2023
3d14050
refactor: 에러 코드 이름 수정
Cyma-s Sep 27, 2023
ded41a5
refactor: 변수 이름 리팩터링
Cyma-s Sep 27, 2023
d52d13c
style: 헤더 위치 변경
Cyma-s Sep 27, 2023
9bfb040
test: 엣지 케이스를 테스트하도록 변경
Cyma-s Sep 27, 2023
621a625
refactor: member 에게 닉네임이 같은지 물어 보도록 메서드 변경
Cyma-s Sep 27, 2023
4685592
fix: @Valid 어노테이션 추가
Cyma-s Sep 27, 2023
5a64990
feat: 리프레시 토큰이 member id 로만 만들어지도록 수정
Cyma-s Sep 29, 2023
2847c8d
refactor: 닉네임 최소 길이 추가
Cyma-s Sep 29, 2023
05fdcf1
fix: cookie setPath 설정 변경
Cyma-s Sep 29, 2023
514c475
fix: cookie 테스트 수정
Cyma-s Sep 29, 2023
f0e54f9
refactor: 에러코드 문구 수정
Cyma-s Sep 30, 2023
04af872
fix: 닉네임 변경 시 응답을 내려주지 않도록 수정
Cyma-s Oct 3, 2023
3d46182
refactor: 토큰 검증 책임 ReissueController 로 이동
Cyma-s Oct 5, 2023
72ea86a
refactor: 검증 순서 변경
Cyma-s Oct 5, 2023
d9115bf
refactor: delete 메서드도 memberId 를 입력 받도록 변경
Cyma-s Oct 5, 2023
21358a7
refactor: 사용하지 않는 클래스 삭제
Cyma-s Oct 5, 2023
8ca6f07
refactor: 검증 로직 간소화
Cyma-s Oct 5, 2023
9c6fc11
refactor: save 문 삭제
Cyma-s Oct 5, 2023
21f4d60
refactor: TokenProvider, InMemoryTokenPairRepository 의존성 삭제
Cyma-s Oct 6, 2023
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
@@ -1,11 +1,8 @@
package shook.shook.auth.application;

import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shook.shook.auth.application.dto.ReissueAccessTokenResponse;
import shook.shook.auth.application.dto.TokenPair;
import shook.shook.auth.repository.InMemoryTokenPairRepository;
import shook.shook.member.application.MemberService;
import shook.shook.member.domain.Member;

Expand All @@ -15,8 +12,7 @@ public class AuthService {

private final MemberService memberService;
private final OAuthProviderFinder oauthProviderFinder;
private final TokenProvider tokenProvider;
private final InMemoryTokenPairRepository inMemoryTokenPairRepository;
private final TokenService tokenService;

public TokenPair oAuthLogin(final String oauthType, final String authorizationCode) {
final OAuthInfoProvider oAuthInfoProvider = oauthProviderFinder.getOAuthInfoProvider(oauthType);
Expand All @@ -26,24 +22,9 @@ public TokenPair oAuthLogin(final String oauthType, final String authorizationCo

final Member member = memberService.findByEmail(memberInfo)
.orElseGet(() -> memberService.register(memberInfo));

final Long memberId = member.getId();
final String nickname = member.getNickname();
final String accessToken = tokenProvider.createAccessToken(memberId, nickname);
final String refreshToken = tokenProvider.createRefreshToken(memberId, nickname);
inMemoryTokenPairRepository.addOrUpdateTokenPair(refreshToken, accessToken);
return new TokenPair(accessToken, refreshToken);
}

public ReissueAccessTokenResponse reissueAccessTokenByRefreshToken(final String refreshToken,
final String accessToken) {
final Claims claims = tokenProvider.parseClaims(refreshToken);
final Long memberId = claims.get("memberId", Long.class);
final String nickname = claims.get("nickname", String.class);

inMemoryTokenPairRepository.validateTokenPair(refreshToken, accessToken);
final String reissuedAccessToken = tokenProvider.createAccessToken(memberId, nickname);
inMemoryTokenPairRepository.addOrUpdateTokenPair(refreshToken, reissuedAccessToken);
return new ReissueAccessTokenResponse(reissuedAccessToken);
return tokenService.updateWithNewTokenPair(memberId, nickname);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ private String createToken(final long memberId, final String nickname, final lon
claims.put("memberId", memberId);
claims.put("nickname", nickname);
final Date now = new Date();

return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package shook.shook.auth.application;

import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shook.shook.auth.application.dto.ReissueAccessTokenResponse;
import shook.shook.auth.application.dto.TokenPair;
import shook.shook.auth.repository.InMemoryTokenPairRepository;

@Transactional(readOnly = true)
@RequiredArgsConstructor
@Service
public class TokenService {

public static final String TOKEN_PREFIX = "Bearer ";

private final TokenProvider tokenProvider;
private final InMemoryTokenPairRepository inMemoryTokenPairRepository;

public String createAccessToken(final Long memberId, final String nickname) {
return tokenProvider.createAccessToken(memberId, nickname);
}

public String createRefreshToken(final Long memberId, final String nickname) {
return tokenProvider.createRefreshToken(memberId, nickname);
}

public ReissueAccessTokenResponse reissueAccessTokenByRefreshToken(final String refreshToken,
final String accessToken) {
inMemoryTokenPairRepository.validateTokenPair(refreshToken, accessToken);
final Claims claims = tokenProvider.parseClaims(refreshToken);
final Long memberId = claims.get("memberId", Long.class);
final String nickname = claims.get("nickname", String.class);

final String reissuedAccessToken = tokenProvider.createAccessToken(memberId, nickname);
inMemoryTokenPairRepository.addOrUpdateTokenPair(refreshToken, reissuedAccessToken);

return new ReissueAccessTokenResponse(reissuedAccessToken);
}

public TokenPair updateWithNewTokenPair(final Long memberId, final String nickname) {
final String accessToken = createAccessToken(memberId, nickname);
final String refreshToken = createRefreshToken(memberId, nickname);
inMemoryTokenPairRepository.addOrUpdateTokenPair(refreshToken, accessToken);

return new TokenPair(refreshToken, accessToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ private HandlerInterceptor tokenInterceptor() {
.includePathPattern("/songs/*/parts/*/likes", PathMethod.PUT)
.includePathPattern("/voting-songs/*/parts", PathMethod.POST)
.includePathPattern("/songs/*/parts/*/comments", PathMethod.POST)
.includePathPattern("/members/*", PathMethod.DELETE);
.includePathPattern("/members/*", PathMethod.DELETE)
.includePathPattern("/members/*/nickname", PathMethod.PATCH);
Copy link
Collaborator

Choose a reason for hiding this comment

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

👍👍

}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package shook.shook.auth.ui;

import static shook.shook.auth.application.TokenService.TOKEN_PREFIX;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import shook.shook.auth.application.AuthService;
import shook.shook.auth.application.TokenService;
import shook.shook.auth.application.dto.ReissueAccessTokenResponse;
import shook.shook.auth.exception.AuthorizationException;
import shook.shook.auth.ui.openapi.AccessTokenReissueApi;
Expand All @@ -18,22 +20,29 @@ public class AccessTokenReissueController implements AccessTokenReissueApi {

private static final String EMPTY_REFRESH_TOKEN = "none";
private static final String REFRESH_TOKEN_KEY = "refreshToken";
private static final String TOKEN_PREFIX = "Bearer ";

private final AuthService authService;
private final TokenService tokenService;
Copy link
Collaborator

Choose a reason for hiding this comment

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

👍


@PostMapping("/reissue")
public ResponseEntity<ReissueAccessTokenResponse> reissueAccessToken(
@CookieValue(value = REFRESH_TOKEN_KEY, defaultValue = EMPTY_REFRESH_TOKEN) final String refreshToken,
@RequestHeader(HttpHeaders.AUTHORIZATION) final String authorization
) {
validateRefreshToken(refreshToken);
final String accessToken = extractAccessToken(authorization);
final ReissueAccessTokenResponse response = tokenService.reissueAccessTokenByRefreshToken(refreshToken,
accessToken);

return ResponseEntity.ok(response);
}

private void validateRefreshToken(final String refreshToken) {
if (refreshToken.equals(EMPTY_REFRESH_TOKEN)) {
throw new AuthorizationException.RefreshTokenNotFoundException();
}
final String accessToken = authorization.split(TOKEN_PREFIX)[1];
final ReissueAccessTokenResponse response =
authService.reissueAccessTokenByRefreshToken(refreshToken, accessToken);
}

return ResponseEntity.ok(response);
private String extractAccessToken(final String authorization) {
return authorization.substring(TOKEN_PREFIX.length());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public ResponseEntity<LoginResponse> googleLogin(
final Cookie cookie = cookieProvider.createRefreshTokenCookie(tokenPair.getRefreshToken());
response.addCookie(cookie);
final LoginResponse loginResponse = new LoginResponse(tokenPair.getAccessToken());

return ResponseEntity.ok(loginResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public Cookie createRefreshTokenCookie(final String refreshToken) {
cookie.setPath("/api/reissue");
cookie.setHttpOnly(true);
cookie.setSecure(true);

return cookie;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,22 +60,24 @@ public enum ErrorCode {
VOTING_PART_END_OVER_SONG_LENGTH(4003, "파트의 끝 초는 노래 길이를 초과할 수 없습니다."),
INVALID_VOTING_PART_LENGTH(4004, "파트의 길이는 5, 10, 15초 중 하나여야합니다."),
VOTING_PART_DUPLICATE_START_AND_LENGTH_EXCEPTION(4005,
"한 노래에 동일한 파트를 두 개 이상 등록할 수 없습니다."),
"한 노래에 동일한 파트를 두 개 이상 등록할 수 없습니다."),
VOTING_SONG_PART_NOT_EXIST(4006, "투표 대상 파트가 존재하지 않습니다."),

VOTING_SONG_PART_FOR_OTHER_SONG(4007, "해당 파트는 다른 노래의 파트입니다."),
VOTING_SONG_NOT_EXIST(4008, "존재하지 않는 투표 노래입니다."),
VOTE_FOR_OTHER_PART(4009, "해당 투표는 다른 파트에 대한 투표입니다."),
DUPLICATE_VOTE_EXIST(4010, "중복된 투표입니다."),
// 5000: 사용자

// 5000: 사용자
EMPTY_EMAIL(5001, "이메일은 비어있을 수 없습니다."),
TOO_LONG_EMAIL(5002, "이메일은 100자를 초과할 수 없습니다."),
INVALID_EMAIL_FORM(5003, "이메일 형식에 맞지 않습니다."),
EMPTY_NICKNAME(5004, "닉네임은 비어있을 수 없습니다."),
TOO_LONG_NICKNAME(5005, "닉네임은 100자를 초과할 수 없습니다."),
TOO_LONG_NICKNAME(5005, "닉네임은 20자를 초과할 수 없습니다."),
EXIST_MEMBER(5006, "이미 회원가입 된 멤버입니다."),
MEMBER_NOT_EXIST(5007, "존재하지 않는 멤버입니다."),
DUPLICATE_NICKNAME(5008, "중복되는 닉네임입니다."),
TOO_SHORT_NICKNAME(5009, "닉네임은 2자 이상이어야 합니다."),

REQUEST_BODY_VALIDATION_FAIL(10001, ""),
WRONG_REQUEST_URL(10002, "URL의 pathVariable 은 비어있을 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shook.shook.auth.application.TokenProvider;
import shook.shook.auth.exception.AuthorizationException;
import shook.shook.auth.ui.argumentresolver.MemberInfo;
import shook.shook.auth.repository.InMemoryTokenPairRepository;
import shook.shook.member.application.dto.NicknameUpdateRequest;
import shook.shook.member.domain.Email;
import shook.shook.member.domain.Member;
import shook.shook.member.domain.Nickname;
Expand All @@ -27,6 +30,8 @@ public class MemberService {
private final MemberRepository memberRepository;
private final KillingPartCommentRepository commentRepository;
private final KillingPartLikeRepository likeRepository;
private final TokenProvider tokenProvider;
private final InMemoryTokenPairRepository inMemoryTokenPairRepository;

@Transactional
public Member register(final String email) {
Expand All @@ -37,6 +42,7 @@ public Member register(final String email) {
final Member newMember = new Member(email, BASIC_NICKNAME);
final Member savedMember = memberRepository.save(newMember);
savedMember.updateNickname(savedMember.getNickname() + savedMember.getId());

return savedMember;
}

Expand All @@ -54,20 +60,27 @@ public Member findByIdAndNicknameThrowIfNotExist(final Long id, final Nickname n
}

@Transactional
public void deleteById(final Long id, final MemberInfo memberInfo) {
final long requestMemberId = memberInfo.getMemberId();
final Member requestMember = findById(requestMemberId);
final Member targetMember = findById(id);
validateMemberAuthentication(requestMember, targetMember);

final List<KillingPartLike> membersExistLikes = likeRepository.findAllByMemberAndIsDeleted(
targetMember,
false
);
public void deleteById(final Long id, final Long requestMemberId) {
final Member member = getMemberIfValidRequest(id, requestMemberId);

final List<KillingPartLike> membersExistLikes = likeRepository.findAllByMemberAndIsDeleted(member, false);

membersExistLikes.forEach(KillingPartLike::updateDeletion);
commentRepository.deleteAllByMember(targetMember);
memberRepository.delete(targetMember);
commentRepository.deleteAllByMember(member);
memberRepository.delete(member);
}

private Member getMemberIfValidRequest(final Long memberId, final Long requestMemberId) {
if (Objects.equals(memberId, requestMemberId)) {
return findById(memberId);
}

throw new AuthorizationException.UnauthenticatedException(
Map.of(
"tokenMemberId", String.valueOf(requestMemberId),
"pathMemberId", String.valueOf(memberId)
)
);
}

private Member findById(final Long id) {
Expand All @@ -77,14 +90,27 @@ private Member findById(final Long id) {
));
}

private void validateMemberAuthentication(final Member requestMember,
final Member targetMember) {
if (!requestMember.equals(targetMember)) {
throw new AuthorizationException.UnauthenticatedException(
Map.of(
"tokenMemberId", String.valueOf(requestMember.getId()),
"pathMemberId", String.valueOf(targetMember.getId())
)
@Transactional
public boolean updateNickname(final Long memberId, final Long requestMemberId,
Copy link
Collaborator

Choose a reason for hiding this comment

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

💬 위의 deleteByIdmemberInfo 를 그대로 파라미터로 받아오고 있는데, 두 메서드가 파라미터를 받는 방식을 통일해보면 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

현재 memberInfo 의 id 만 쓰이고 있는 상태라 id 만 넘겨주는 걸로 통일했습니다 😄

Copy link
Collaborator

Choose a reason for hiding this comment

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

MemberService에서 Token을 재발급 해주는 로직이 사라지니 확실히 더 책임 분리가 잘 된 느낌이 드네용 ㅎㅎ 👍

final NicknameUpdateRequest request) {
final Member member = getMemberIfValidRequest(memberId, requestMemberId);
final Nickname nickname = new Nickname(request.getNickname());

if (member.hasSameNickname(nickname)) {
return false;
}

validateDuplicateNickname(nickname);
member.updateNickname(nickname.getValue());

return true;
}

private void validateDuplicateNickname(final Nickname nickname) {
final boolean isDuplicated = memberRepository.existsMemberByNickname(nickname);
if (isDuplicated) {
throw new MemberException.ExistNicknameException(
Map.of("Nickname", nickname.getValue())
);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package shook.shook.member.application.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Schema(description = "닉네임 변경 요청")
@NoArgsConstructor(access = lombok.AccessLevel.PRIVATE)
@AllArgsConstructor
@Getter
public class NicknameUpdateRequest {

@Schema(description = "닉네임", example = "shookshook")
@NotBlank
private String nickname;
}
8 changes: 8 additions & 0 deletions backend/src/main/java/shook/shook/member/domain/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ public void updateNickname(final String newNickName) {
this.nickname = new Nickname(newNickName);
}

public void updateNickname(final Nickname newNickname) {
this.nickname = newNickname;
}
Comment on lines 51 to +54
Copy link
Collaborator

Choose a reason for hiding this comment

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

의견)

  1. isSameNickname의 책임을 Member한테 넘기면서, 내부적으로 new Nickname() 을 통해 닉네임 형식 검증 + 중복 검증을 해보면 어떨까요?
  2. 그렇게 되면 이 Nickname 객체를 받는 메서드는 사라질 것 같습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

isSameNickname 의 검증 책임을 멤버에게 넘기려고 했는데, memberRepository 에서 중복을 확인할 때 Nickname 객체가 필요하더라고요. 그래서 해당 메서드는 그대로 두고, Nickname 객체는 외부에서 생성하여 검증하는 걸로 했습니다!


public boolean hasSameNickname(final Nickname nickname) {
return nickname.equals(this.nickname);
}

public String getEmail() {
return email.getValue();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
@Embeddable
public class Nickname {

private static final int NICKNAME_MAXIMUM_LENGTH = 100;
private static final int NICKNAME_MAXIMUM_LENGTH = 20;
private static final int NICKNAME_MINIMUM_LENGTH = 2;

@Column(name = "nickname", length = NICKNAME_MAXIMUM_LENGTH, nullable = false)
private String value;
Expand All @@ -35,5 +36,10 @@ private void validateNickname(final String value) {
Map.of("Nickname", value)
);
}
if (value.length() < NICKNAME_MINIMUM_LENGTH) {
throw new MemberException.TooShortNicknameException(
Map.of("Nickname", value)
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ public interface MemberRepository extends JpaRepository<Member, Long> {
Optional<Member> findByEmail(final Email email);

Optional<Member> findByIdAndNickname(final Long id, final Nickname nickname);

boolean existsMemberByNickname(final Nickname nickname);
}
Loading