Skip to content

Commit

Permalink
refactor: method 분리 및 final 키워드 추가 (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
toychip committed Nov 29, 2023
1 parent 985dac3 commit f2be95d
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ private OauthConstant() {
public static final String NAME_PATTERN = "name";
public static final String EMAIL_PATTERN = "email";
public static final long ACCESS_TOKEN_VALID_TIME = 15 * 60 * 1000L;
public static final String REDIRECT_URL = "http://localhost:5173";

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,21 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtProvider jwtProvider;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {

String requestURI = request.getRequestURI();
if (isPublicUri(requestURI)) {
// Public uri 일 경우 검증 안함
filterChain.doFilter(request, response);
return;
}

String authorizationHeader = request.getHeader("Authorization");

if (authorizationHeader != null && isBearer(authorizationHeader)) {
String jwtToken = authorizationHeader.substring(7); // "Bearer " 이후의 문자열을 추출
// "Bearer " 이후의 문자열을 추출
String jwtToken = authorizationHeader.substring(7);

// token 단순 유효성 검증
jwtProvider.isValidToken(jwtToken);
Expand All @@ -41,15 +43,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

}

private boolean isBearer(String authorizationHeader) {
private boolean isBearer(final String authorizationHeader) {
return authorizationHeader.startsWith("Bearer ");
}

private boolean isPublicUri(String requestURI) {
private boolean isPublicUri(final String requestURI) {
return
requestURI.startsWith("/oauth/**") ||
requestURI.startsWith("/swagger-ui") ||
requestURI.startsWith("/favicon.ico") ||
requestURI.startsWith("/oauth/**") ||
requestURI.startsWith("/login/**");
}
}
30 changes: 20 additions & 10 deletions src/main/java/com/api/TaveShot/global/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class JwtProvider {
@Value("${jwt.secret.key}")
private String SECRET_KEY;

public String generateJwtToken(String id) {
public String generateJwtToken(final String id) {
Claims claims = createClaims(id);
Date now = new Date();
long expiredDate = calculateExpirationDate(now);
Expand All @@ -45,21 +45,22 @@ public String generateJwtToken(String id) {
}

// JWT claims 생성
private Claims createClaims(String id) {
private Claims createClaims(final String id) {
return Jwts.claims().setSubject(id);
}

// JWT 만료 시간 계산
private long calculateExpirationDate(Date now) {
private long calculateExpirationDate(final Date now) {
return now.getTime() + ACCESS_TOKEN_VALID_TIME;
}

// Key 생성
private SecretKey generateKey() {
return Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
}

// 토큰의 유효성 검사
public void isValidToken(String jwtToken) {
public void isValidToken(final String jwtToken) {
try {
SecretKey key = generateKey();
Jwts.parserBuilder()
Expand All @@ -74,24 +75,33 @@ public void isValidToken(String jwtToken) {
}
}

public void getAuthenticationFromToken(String jwtToken) {
// jwtToken 으로 Authentication 에 사용자 등록
public void getAuthenticationFromToken(final String jwtToken) {

log.info("-------------- getAuthenticationFromToken jwt token: " + jwtToken);
String gitName = getGitName(jwtToken);
registerAuthentication(jwtToken, gitName);

}

// token 으로부터 유저 정보 확인
private String getGitName(final String jwtToken) {
Long userId = Long.valueOf(getUserIdFromToken(jwtToken));
Member findMember = memberRepository.findById(userId).orElseThrow(() -> new RuntimeException("token 으로 Member를 찾을 수 없음"));
String gitName = findMember.getGitName();

log.info("-------------- getAuthenticationFromToken 어세스토큰: " + jwtToken);
return findMember.getGitName();
}

private void registerAuthentication(final String jwtToken, final String gitName) {
// JWT 토큰이 유효하면, 사용자 정보를 연결 세션에 추가
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(gitName, jwtToken, new ArrayList<>());

// SecurityContextHolder 유저 등록
SecurityContextHolder.getContext().setAuthentication(authenticationToken);

}

// 토큰에서 유저 아이디 얻기
public String getUserIdFromToken(String jwtToken) {
public String getUserIdFromToken(final String jwtToken) {
SecretKey key = generateKey();

Claims claims = Jwts.parserBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final MemberRepository memberRepository;

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
public OAuth2User loadUser(final OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
log.info("-------------- 갖고 온 정보 -------------- getAttributes : {} ", oAuth2User.getAuthorities());

Expand All @@ -33,7 +33,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
return createCustomOauth2User(member, userInfo);
}

private Member processOAuthUser(Map<String, Object> userInfo) {
private Member processOAuthUser(final Map<String, Object> userInfo) {
String gitLoginId = (String) userInfo.get(LOGIN_PATTERN);
Long gitId = ((Integer) userInfo.get(ID_PATTERN)).longValue();
String gitEmail = (String) userInfo.get(EMAIL_PATTERN);
Expand All @@ -43,7 +43,8 @@ private Member processOAuthUser(Map<String, Object> userInfo) {
.orElseGet(() -> registerNewMember(gitId, gitLoginId, gitEmail, gitName));
}

private Member registerNewMember(Long gitId, String gitLoginId, String gitEmail, String gitName) {
private Member registerNewMember(final Long gitId, final String gitLoginId,
final String gitEmail, final String gitName) {
Member newMember = Member.builder()
.gitId(gitId)
.gitLoginId(gitLoginId)
Expand All @@ -54,10 +55,18 @@ private Member registerNewMember(Long gitId, String gitLoginId, String gitEmail,
return memberRepository.save(newMember);
}

private CustomOauth2User createCustomOauth2User(Member member, Map<String, Object> userInfo) {
private CustomOauth2User createCustomOauth2User(final Member member, final Map<String, Object> userInfo) {

GithubUserInfo githubUserInfo = generateGithubInfo(userInfo);
return CustomOauth2User.builder()
.member(member)
.attributes(userInfo)
.githubUserInfo(githubUserInfo)
.build();
}

private GithubUserInfo generateGithubInfo(final Map<String, Object> userInfo) {
return GithubUserInfo.builder()
.userInfo(userInfo)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package com.api.TaveShot.global.oauth2;

import static com.api.TaveShot.global.constant.OauthConstant.REDIRECT_URL;

import com.api.TaveShot.domain.Member.domain.Member;
import com.api.TaveShot.domain.Member.dto.response.AuthResponse;
import com.api.TaveShot.domain.Member.repository.MemberRepository;
import com.api.TaveShot.global.jwt.JwtProvider;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
Expand All @@ -22,59 +23,69 @@
@RequiredArgsConstructor
public class CustomOAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

private static final String REDIRECT_URL = "http://localhost:5173";

private final MemberRepository memberRepository;
private final JwtProvider jwtProvider;

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
final Authentication authentication) throws IOException {

CustomOauth2User oauth2User = (CustomOauth2User) authentication.getPrincipal();

Map<String, Object> userInfo = oauth2User.getAttributes();
GithubUserInfo githubUserInfo = GithubUserInfo.builder()
.userInfo(userInfo)
.build();
GithubUserInfo githubUserInfo = createGitHubUserInfo(oauth2User);

if(response.isCommitted()) {
log.debug("------------------ Response 전송 완료");
}

String profileImageUrl = githubUserInfo.getProfileImageUrl();
String loginId = githubUserInfo.getLoginId();
String name = githubUserInfo.getName();
Long gitId = githubUserInfo.getId();

log.info("------------------ "
+ "소셜 로그인 성공: " + loginId
+ "프로필 이미지: " + profileImageUrl
+ "이름" + name);
+ "프로필 이미지: " + profileImageUrl);

Member loginMember = memberRepository.findByGitId(gitId).orElseThrow(() -> new RuntimeException(""));
Member loginMember = memberRepository.findByGitId(gitId).orElseThrow(() -> new RuntimeException("해당 gitId로 회원을 찾을 수 없음"));
String loginMemberId = String.valueOf(loginMember.getId());

String accessToken = jwtProvider.generateAccessToken(loginMemberId);
// 어세스 토큰은 헤더에 담아서 응답으로 보냄
response.setHeader("Authorization", accessToken);
registerHeaderToken(response, loginMemberId);

AuthResponse authResponse = AuthResponse.builder()
.memberId(loginMember.getId())
.gitLoginId(loginId)
.gitProfileImageUrl(profileImageUrl)
.build();


// ---------------------------------------------------------------------
// ToDo 아래는 임시 데이터, front와 협의 후 수정
registerResponse(response, authResponse);
}

private void registerHeaderToken(final HttpServletResponse response, final String loginMemberId) {
String ourToken = jwtProvider.generateJwtToken(loginMemberId);
// 어세스 토큰은 헤더에 담아서 응답으로 보냄
response.setHeader("Authorization", ourToken);
}

private GithubUserInfo createGitHubUserInfo(final CustomOauth2User oauth2User) {
Map<String, Object> userInfo = oauth2User.getAttributes();

return GithubUserInfo.builder()
.userInfo(userInfo)
.build();
}

private void registerResponse(final HttpServletResponse response,
final AuthResponse authResponse) throws IOException {
String encodedMemberId = URLEncoder.encode(String.valueOf(authResponse.memberId()), StandardCharsets.UTF_8);
String encodedLoginId = URLEncoder.encode(authResponse.gitLoginId(), StandardCharsets.UTF_8);
String encodedGitProfileImageUrl = URLEncoder.encode(authResponse.gitProfileImageUrl(), StandardCharsets.UTF_8);

// 프론트엔드 페이지로 토큰과 함께 리다이렉트
String frontendRedirectUrl = String.format(
"%s/oauth2/github/code?token=%s&memberId=%s&gitLoginId=%s&profileImgUrl=%s",
REDIRECT_URL, accessToken, encodedMemberId, encodedLoginId, encodedGitProfileImageUrl);
"%s/oauth2/github/code?memberId=%s&gitLoginId=%s&profileImgUrl=%s",
REDIRECT_URL, encodedMemberId, encodedLoginId, encodedGitProfileImageUrl);

response.sendRedirect(frontendRedirectUrl);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@
public class CustomOauth2User implements OAuth2User {

private final Member member;
private final Map<String, Object> attributes;
private final GithubUserInfo githubUserInfo;

@Override
public <A> A getAttribute(String name) {
public <A> A getAttribute(final String name) {
return OAuth2User.super.getAttribute(name);
}

@Override
public Map<String, Object> getAttributes() {
return attributes;
return githubUserInfo.userInfo();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import static com.api.TaveShot.global.constant.OauthConstant.NAME_PATTERN;

import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;

@Builder
Expand Down

0 comments on commit f2be95d

Please sign in to comment.