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

Refactor/320 auth memberid #355

Merged
merged 20 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
7c37505
chore: 불필요한 import 구문 제거
tco0427 Sep 7, 2022
1a54d82
refactor: MemberService memberId 받도록 변경 & MemberData `memberId` 를 담아서 반환
tco0427 Sep 7, 2022
13302c5
refactor: ReferenceRoom `memberId` 사용하도록 변경
tco0427 Sep 7, 2022
4283368
refactor: SearchingReferenceRoom `memberId` 사용하도록 변경
tco0427 Sep 7, 2022
55b994e
refactor: Review `memberId` 사용하도록 변경
tco0427 Sep 7, 2022
dd067ad
refactor: Study `memberId` 사용하도록 변경
tco0427 Sep 7, 2022
f842f38
refactor: AuthenticationPrincipal 제거
tco0427 Sep 7, 2022
4bb0cbf
refactor: 액세스 토큰 재발급 memberId 사용
tco0427 Sep 13, 2022
6452b45
refactor: token 엔티티 memberId 가지도록 수정
tco0427 Sep 13, 2022
965e9ee
fix: Auth 인수 테스트 수정
tco0427 Sep 13, 2022
30c3413
feat: 사용하지 않는 필드 제거 및 DB 조회 최소화
tco0427 Sep 14, 2022
9f57a82
refactor: orElseThrow 예외 타입 명시
tco0427 Sep 14, 2022
0cd2733
test: orElseThrow -> get 으로 수정
tco0427 Sep 14, 2022
624d511
refactor: 스터디장 Fixture 제거
tco0427 Sep 14, 2022
ae13bf9
chore: 코드 냄새 제거
tco0427 Sep 15, 2022
3a6aca7
feta: 충돌 해결
tco0427 Sep 15, 2022
bfad90d
Merge branch 'develop' into refactor/320-auth-memberid
tco0427 Sep 15, 2022
b52a673
Merge branch 'develop' of https://github.com/woowacourse-teams/2022-m…
tco0427 Sep 15, 2022
2c1dcd8
feat: 로그 추가
tco0427 Sep 15, 2022
a47f96c
test: 테스트 수정
tco0427 Sep 15, 2022
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 @@ -2,14 +2,11 @@

import com.woowacourse.moamoa.auth.controller.AuthenticatedMemberResolver;
import com.woowacourse.moamoa.auth.controller.AuthenticatedRefreshArgumentResolver;
import com.woowacourse.moamoa.auth.controller.AuthenticationArgumentResolver;
import com.woowacourse.moamoa.auth.controller.interceptor.AuthenticationInterceptor;

import com.woowacourse.moamoa.auth.controller.interceptor.PathMatcherContainer;
import com.woowacourse.moamoa.auth.controller.interceptor.PathMatcherInterceptor;
import com.woowacourse.moamoa.auth.infrastructure.TokenProvider;
import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -25,15 +22,13 @@
public class AuthConfig implements WebMvcConfigurer {

private final AuthenticatedRefreshArgumentResolver authenticatedRefreshArgumentResolver;
private final AuthenticationArgumentResolver authenticationArgumentResolver;
private final AuthenticatedMemberResolver authenticatedMemberResolver;

private final PathMatcherContainer pathMatcherContainer;
private final TokenProvider jwtTokenProvider;

@Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(authenticationArgumentResolver);
resolvers.add(authenticatedMemberResolver);
resolvers.add(authenticatedRefreshArgumentResolver);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthenticatedMember {
public @interface AuthenticatedMemberId {
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.woowacourse.moamoa.auth.controller;

import com.woowacourse.moamoa.auth.config.AuthenticatedMemberId;
import com.woowacourse.moamoa.auth.config.AuthenticatedRefresh;
import com.woowacourse.moamoa.auth.config.AuthenticationPrincipal;
import com.woowacourse.moamoa.auth.service.AuthService;
import com.woowacourse.moamoa.auth.service.response.AccessTokenResponse;
import com.woowacourse.moamoa.auth.service.response.TokensResponse;
Expand Down Expand Up @@ -35,13 +35,13 @@ public ResponseEntity<AccessTokenResponse> login(@RequestParam final String code
}

@GetMapping("/api/auth/refresh")
public ResponseEntity<AccessTokenResponse> refreshToken(@AuthenticatedRefresh Long githubId, @CookieValue String refreshToken) {
return ResponseEntity.ok().body(authService.refreshToken(githubId, refreshToken));
public ResponseEntity<AccessTokenResponse> refreshToken(@AuthenticatedRefresh Long memberId, @CookieValue String refreshToken) {
return ResponseEntity.ok().body(authService.refreshToken(memberId, refreshToken));
}

@DeleteMapping("/api/auth/logout")
public ResponseEntity<Void> logout(@AuthenticationPrincipal Long githubId) {
authService.logout(githubId);
public ResponseEntity<Void> logout(@AuthenticatedMemberId Long memberId) {
authService.logout(memberId);

return ResponseEntity.noContent().header("Set-Cookie", removeCookie().toString()).build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package com.woowacourse.moamoa.auth.controller;

import com.woowacourse.moamoa.auth.config.AuthenticatedMember;
import com.woowacourse.moamoa.auth.config.AuthenticatedMemberId;
import com.woowacourse.moamoa.auth.config.AuthenticationExtractor;
import com.woowacourse.moamoa.auth.infrastructure.TokenProvider;
import com.woowacourse.moamoa.common.exception.UnauthorizedException;
import com.woowacourse.moamoa.member.domain.Member;
import com.woowacourse.moamoa.member.domain.repository.MemberRepository;
import com.woowacourse.moamoa.member.service.exception.MemberNotFoundException;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
Expand All @@ -20,12 +17,11 @@
@RequiredArgsConstructor
public class AuthenticatedMemberResolver implements HandlerMethodArgumentResolver {

private final MemberRepository memberRepository;
private final TokenProvider tokenProvider;

@Override
public boolean supportsParameter(final MethodParameter parameter) {
return parameter.hasParameterAnnotation(AuthenticatedMember.class);
return parameter.hasParameterAnnotation(AuthenticatedMemberId.class);
}

@Override
Expand All @@ -38,9 +34,6 @@ public Object resolveArgument(final MethodParameter parameter, final ModelAndVie
throw new UnauthorizedException("인증 타입이 올바르지 않습니다.");
}

final Long githubId = Long.valueOf(tokenProvider.getPayload(token));

final Member member = memberRepository.findByGithubId(githubId).orElseThrow(MemberNotFoundException::new);
return member.getId();
return Long.valueOf(tokenProvider.getPayload(token));
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private void validateToken(final String token, final String requestURI) {
return;
}
if (token == null || !tokenProvider.validateToken(token)) {
throw new UnauthorizedException("유효하지 않은 토큰입니다.");
throw new UnauthorizedException(String.format("유효하지 않은 토큰[%s]입니다.", token));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,26 @@
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Entity
@Getter
@NoArgsConstructor(access = PROTECTED)
@AllArgsConstructor
@ToString
public class Token {

@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;

@Column(nullable = false)
private Long githubId;
private Long memberId;

private String refreshToken;

public Token(final Long githubId, final String refreshToken) {
this(null, githubId, refreshToken);
public Token(final Long memberId, final String refreshToken) {
this(null, memberId, refreshToken);
}

public void updateRefreshToken(final String refreshToken) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@

public interface TokenRepository extends JpaRepository<Token, Long> {

Optional<Token> findByGithubId(Long githubId);
Optional<Token> findByMemberId(Long memberId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public boolean validateToken(final String token) {
}

@Override
public String recreationAccessToken(final Long githubId, final String refreshToken) {
public String recreationAccessToken(final Long memberId, final String refreshToken) {
Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
Expand All @@ -102,7 +102,7 @@ public String recreationAccessToken(final Long githubId, final String refreshTok
Date tokenExpirationDate = claims.getBody().getExpiration();
validateTokenExpiration(tokenExpirationDate);

return createAccessToken(githubId);
return createAccessToken(memberId);
}

private void validateTokenExpiration(Date tokenExpirationDate) {
Expand All @@ -111,11 +111,11 @@ private void validateTokenExpiration(Date tokenExpirationDate) {
}
}

private String createAccessToken(final Long githubId) {
private String createAccessToken(final Long memberId) {
final Date now = new Date();

return Jwts.builder()
.setSubject(Long.toString(githubId))
.setSubject(Long.toString(memberId))
.setIssuedAt(now)
.setExpiration(new Date(now.getTime() + validityInMilliseconds))
.signWith(key, SignatureAlgorithm.HS256)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public interface TokenProvider {

boolean validateToken(final String token);

String recreationAccessToken(final Long githubId, final String refreshToken);
String recreationAccessToken(final Long memberId, final String refreshToken);

long getValidityInMilliseconds();
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.woowacourse.moamoa.auth.service.response.TokensResponse;
import com.woowacourse.moamoa.common.exception.UnauthorizedException;
import com.woowacourse.moamoa.member.service.MemberService;
import com.woowacourse.moamoa.member.service.response.MemberResponse;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -29,39 +30,37 @@ public class AuthService {
public TokensResponse createToken(final String code) {
final String accessToken = oAuthClient.getAccessToken(code);
final GithubProfileResponse githubProfileResponse = oAuthClient.getProfile(accessToken);
memberService.saveOrUpdate(githubProfileResponse.toMember());
final MemberResponse memberResponse = memberService.saveOrUpdate(githubProfileResponse.toMember());
final Long memberId = memberResponse.getId();

final Long githubId = githubProfileResponse.getGithubId();
final Optional<Token> token = tokenRepository.findByGithubId(githubId);

final TokensResponse tokenResponse = tokenProvider.createToken(githubProfileResponse.getGithubId());
final Optional<Token> token = tokenRepository.findByMemberId(memberId);
final TokensResponse tokenResponse = tokenProvider.createToken(memberId);

if (token.isPresent()) {
token.get().updateRefreshToken(tokenResponse.getRefreshToken());
return tokenResponse;
}

tokenRepository.save(new Token(githubProfileResponse.getGithubId(), tokenResponse.getRefreshToken()));
tokenRepository.save(new Token(memberId, tokenResponse.getRefreshToken()));

return tokenResponse;
}

public AccessTokenResponse refreshToken(final Long githubId, final String refreshToken) {
final Token token = tokenRepository.findByGithubId(githubId)
public AccessTokenResponse refreshToken(final Long memberId, final String refreshToken) {
final Token token = tokenRepository.findByMemberId(memberId)
.orElseThrow(TokenNotFoundException::new);

if (!token.getRefreshToken().equals(refreshToken)) {
throw new UnauthorizedException("유효하지 않은 토큰입니다.");
throw new UnauthorizedException(String.format("유효하지 않은 토큰[%s]입니다.", token));
}

String accessToken = tokenProvider.recreationAccessToken(githubId, refreshToken);

String accessToken = tokenProvider.recreationAccessToken(memberId, refreshToken);
return new AccessTokenResponse(accessToken, tokenProvider.getValidityInMilliseconds());
}

@Transactional
public void logout(final Long githubId) {
final Token token = tokenRepository.findByGithubId(githubId)
public void logout(final Long memberId) {
final Token token = tokenRepository.findByMemberId(memberId)
.orElseThrow(TokenNotFoundException::new);

tokenRepository.delete(token);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package com.woowacourse.moamoa.common.config;

import com.woowacourse.moamoa.MoamoaApplication;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package com.woowacourse.moamoa.member.controller;

import com.woowacourse.moamoa.auth.config.AuthenticationPrincipal;
import com.woowacourse.moamoa.member.service.response.MemberResponse;
import com.woowacourse.moamoa.auth.config.AuthenticatedMemberId;
import com.woowacourse.moamoa.member.service.MemberService;
import com.woowacourse.moamoa.member.service.response.MemberResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
Expand All @@ -17,9 +16,9 @@ public class MemberController {

@GetMapping("/api/members/me")
public ResponseEntity<MemberResponse> getCurrentMember(
@AuthenticationPrincipal Long githubId
@AuthenticatedMemberId Long memberId
) {
MemberResponse response = memberService.getByGithubId(githubId);
MemberResponse response = memberService.getByMemberId(memberId);
return ResponseEntity.ok().body(response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ private String countOwnerStudy() {
+ "FROM study)) as number_of_study ";
}

public Optional<MemberData> findByGithubId(final Long githubId) {
public Optional<MemberData> findByMemberId(final Long memberId) {
try {
final String sql = "SELECT github_id, username, image_url, profile_url "
final String sql = "SELECT id, username, image_url, profile_url "
+ "FROM member "
+ "WHERE member.github_id = :id";
final MemberData data = jdbcTemplate.queryForObject(sql, Map.of("id", githubId), MEMBER_DATA_ROW_MAPPER);
+ "WHERE member.id = :id";
final MemberData data = jdbcTemplate.queryForObject(sql, Map.of("id", memberId), MEMBER_DATA_ROW_MAPPER);
return Optional.of(data);
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
Expand All @@ -75,11 +75,11 @@ private static RowMapper<ParticipatingMemberData> createMemberFullDataRowMapper(

private static RowMapper<MemberData> createMemberDataRowMapper() {
return (resultSet, resultNumber) -> {
Long githubId = resultSet.getLong("github_id");
Long id = resultSet.getLong("id");
String username = resultSet.getString("username");
String imageUrl = resultSet.getString("image_url");
String profileUrl = resultSet.getString("profile_url");
return new MemberData(githubId, username, imageUrl, profileUrl);
return new MemberData(id, username, imageUrl, profileUrl);
};
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.woowacourse.moamoa.member.query.data;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
Expand All @@ -15,8 +14,7 @@
@ToString
public class MemberData {

@JsonProperty("id")
private Long githubId;
private Long id;

private String username;

Expand Down
Loading