Skip to content

Commit

Permalink
fix(#5) : 앱 회원가입 시 webToken 발급
Browse files Browse the repository at this point in the history
  • Loading branch information
aeeazip committed Jul 24, 2023
1 parent aa099b8 commit 41c2f29
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public enum ErrorCode { // BaseResponseStatus와 같은 역할
INVALID_USER_JWT(2006,"권한이 없는 유저의 접근입니다.", BAD_REQUEST),
NOT_AGREE_EMAIL(2007, "이메일 동의가 거부되었습니다.", BAD_REQUEST),
MEMBER_NOT_FOUND(2008, "해당되는 유저를 찾을 수 없습니다.", BAD_REQUEST),
DUPLICATED_MEMBER(2009, "중복된 WEB 토큰 입니다.", BAD_REQUEST),

/**
* 3000 : Response 오류
Expand Down
21 changes: 20 additions & 1 deletion src/main/java/trothly/trothcam/service/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import trothly.trothcam.domain.member.*;
import trothly.trothcam.dto.auth.TokenDto;
Expand All @@ -19,6 +20,7 @@

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Date;

Expand All @@ -40,7 +42,7 @@ public String encodeJwtToken(TokenDto tokenDto) {

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
.setIssuer("memotion")
.setIssuer("trothcam")
.setIssuedAt(now)
.setSubject(tokenDto.getMemberId().toString())
.setExpiration(new Date(now.getTime() + tokenValidTime))
Expand All @@ -66,6 +68,23 @@ public String encodeJwtRefreshToken(Long memberId) {
.compact();
}

@Transactional
public String encodeWebToken(Long memberId, LocalDateTime createdAt) {
Date now = new Date();
String webToken = String.valueOf(memberId) + String.valueOf(createdAt);
log.info("webToken : " + webToken);

return Jwts.builder()
.setIssuedAt(now)
.setSubject(memberId.toString())
.claim("webToken", webToken)
.claim("roles", "USER")
.signWith(SignatureAlgorithm.HS256,
Base64.getEncoder().encodeToString(("" + JWT_SECRET).getBytes(
StandardCharsets.UTF_8)))
.compact();
}

// JWT 토큰 으로부터 memberId 추출
public Long getMemberIdFromJwtToken(String token) {
Claims claims = Jwts.parser()
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/trothly/trothcam/service/auth/OAuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public class OAuthService {
private final GoogleOauth googleOauth;
private final HttpServletResponse response;

private final WebTokenService webTokenService;

// 비밀번호 암호화
private final PasswordEncoder passwordEncoder;

Expand Down Expand Up @@ -107,6 +109,8 @@ public LoginResDto appleLogin(LoginReqDto loginReqDto) throws BaseException {
// DB에 refreshToken 저장
member.updateRefreshToken(newRefreshToken);
memberRepository.save(member);

webTokenService.encodeWebToken(member.getId(), member.getCreatedAt());
return new LoginResDto(newAccessToken, newRefreshToken);
}

Expand Down Expand Up @@ -187,6 +191,8 @@ public LoginResDto oauthLogin(String socialLoginType, String code) throws JsonPr
// DB에 refreshToken 저장
member.updateRefreshToken(newRefreshToken);
memberRepository.save(member);

webTokenService.encodeWebToken(member.getId(), member.getCreatedAt());
return new LoginResDto(newAccessToken, newRefreshToken);

}
Expand Down
22 changes: 20 additions & 2 deletions src/main/java/trothly/trothcam/service/auth/WebTokenService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package trothly.trothcam.service.auth;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -8,9 +10,18 @@
import trothly.trothcam.dto.auth.TokenDto;
import trothly.trothcam.dto.auth.web.ValidateWebTokenReqDto;
import trothly.trothcam.dto.auth.web.ValidateWebTokenResDto;
import trothly.trothcam.exception.base.BaseException;
import trothly.trothcam.exception.base.ErrorCode;
import trothly.trothcam.exception.custom.BadRequestException;
import trothly.trothcam.exception.custom.SignupException;
import trothly.trothcam.service.JwtService;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Date;
import java.util.Optional;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
Expand All @@ -21,11 +32,18 @@ public class WebTokenService {

/* 웹 토큰 발급 */
@Transactional
public String generateWebToken(Long memberId) {
public String encodeWebToken(Long memberId, LocalDateTime createdAt) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new IllegalArgumentException("해당되는 member_id를 찾을 수 없습니다."));

String webToken = jwtService.encodeJwtToken(new TokenDto(member.getId()));
String webToken = jwtService.encodeWebToken(memberId, createdAt);

// 해당 WEB TOKEN으로 가입한 적이 있는지 검사
// 같은 WEB TOKEN으로 1번을 초과하여 가입하지 못하도록
Optional<Member> duplicatedMember = memberRepository.findByWebToken(webToken);
if(duplicatedMember.isPresent())
throw new BaseException(ErrorCode.DUPLICATED_MEMBER);

member.generateWebToken(webToken); // Dirty checking(변경 감지)로 DB 업데이트
return webToken;
}
Expand Down

0 comments on commit 41c2f29

Please sign in to comment.