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

[CI/CD] dev 브랜치 최신화 반영하여 배포 #77

Merged
merged 2 commits into from
Feb 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
@@ -1,14 +1,16 @@
package com.cmc.mercury.domain.user.controller;

import com.cmc.mercury.domain.user.entity.User;
import com.cmc.mercury.domain.user.response.UserTestRequest;
import com.cmc.mercury.domain.user.service.UserService;
import com.cmc.mercury.global.response.SuccessResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
Expand All @@ -19,11 +21,20 @@ public class UserController {

private final UserService userService;

// @GetMapping("/test/")
// public SuccessResponse<User> getOrCreateTestUser(@RequestParam Long testUserId) {
//
// return SuccessResponse.ok(userTestService.getOrCreateTestUser(testUserId));
// }
@PostMapping("/test")
@Operation(summary = "테스트 계정 생성", description = "개발 환경에서 사용할 테스트 계정을 생성합니다.")
public SuccessResponse<User> createTestUser(@RequestBody @Valid UserTestRequest request) {

return SuccessResponse.created(userService.createTestUser(request));
}

@DeleteMapping("/test")
@Operation(summary = "테스트 계정 삭제", description = "개발 환경에서 사용한 테스트 계정을 삭제합니다.")
public SuccessResponse<?> deleteTestUser(@RequestParam String email) {

userService.deleteTestUser(email);
return SuccessResponse.ok(new HashMap<>());
}

@GetMapping()
public SuccessResponse<List<User>> getAllUsers() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.cmc.mercury.domain.user.entity;

public enum OAuthType {
APPLE, GOOGLE, KAKAO
APPLE, GOOGLE, KAKAO, TEST
}
20 changes: 12 additions & 8 deletions src/main/java/com/cmc/mercury/domain/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.UUID;

@Entity
@Getter
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -57,14 +59,16 @@ public User(String email, OAuthType oauthType,
this.exp = 0; // 초기 경험치는 0
}

// 테스트용 생성자
// @Builder(builderMethodName = "testUserBuilder", buildMethodName = "testUserBuild")
// public User(Long testUserId) {
// this.testUserId = testUserId;
// this.nickname = "TestUser_" + testUserId;
// this.email = "test" + testUserId + "@test.com";
// this.exp = 0; // 초기 경험치는 0
// }
// 게스트용 생성자
@Builder(builderMethodName = "TestUserBuilder", buildMethodName = "TestUserBuild")
public User(String email) {
this.email = email;
this.nickname = "TestUser";
this.oauthType = OAuthType.TEST;
this.oauthId = UUID.randomUUID().toString();;
this.userStatus = UserStatus.ACTIVE;
this.exp = 0; // 초기 경험치는 0
}

public void updateExp(int exp) {
this.exp = exp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByOauthTypeAndOauthId(OAuthType oAuthType, String oauthId);

Optional<User> findByOauthId(String oauthId);

boolean existsByEmailAndOauthType(String email, OAuthType oauthType);

Optional<User> findByEmailAndOauthType(String email, OAuthType oAuthType);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.cmc.mercury.domain.user.response;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;

@Schema(title = "테스트 유저 형식")
public record UserTestRequest(

@NotBlank(message = "이메일은 필수입니다.")
String email,
boolean isShortLivedAccessToken
) {

}
59 changes: 50 additions & 9 deletions src/main/java/com/cmc/mercury/domain/user/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
package com.cmc.mercury.domain.user.service;

import com.cmc.mercury.domain.user.entity.OAuthType;
import com.cmc.mercury.domain.user.entity.User;
import com.cmc.mercury.domain.user.repository.UserRepository;
import com.cmc.mercury.domain.user.response.UserTestRequest;
import com.cmc.mercury.global.exception.CustomException;
import com.cmc.mercury.global.exception.ErrorCode;
import com.cmc.mercury.global.jwt.JwtProvider;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
Expand All @@ -11,17 +20,49 @@
@RequiredArgsConstructor
public class UserService {

@Value("${jwt.access-token-validity}")
private long accessTokenValidity;

private final UserRepository userRepository;
private final JwtProvider jwtProvider;
private final HttpServletResponse response;

@Transactional
public User createTestUser(UserTestRequest request) {

// 이메일과 OAuthType으로 중복 검증
if (userRepository.existsByEmailAndOauthType(request.email(), OAuthType.TEST)) {
throw new CustomException(ErrorCode.DUPLICATE_USER);
}

User user = User.TestUserBuilder()
.email(request.email())
.TestUserBuild();

User savedUser = userRepository.save(user);

// isShortLivedAccessToken 옵션에 따라 유효기간 선택
long tokenValidity = request.isShortLivedAccessToken()
? 20000 // 20초
: accessTokenValidity;

// access token만 발급
String accessToken = jwtProvider.createToken(user.getId(), user.getEmail(), "AccessToken", tokenValidity);

// @Transactional
// public User getOrCreateTestUser(Long testUserId) {
// return userRepository.findByTestUserId(testUserId)
// .orElseGet(() -> userRepository.save(
// User.testUserBuilder()
// .testUserId(testUserId)
// .testUserBuild()
// ));
// }
// 헤더에 access token 설정
response.setHeader("Authorization", "Bearer " + accessToken);

return savedUser;
}

@Transactional
public void deleteTestUser(String email) {

User user = userRepository.findByEmailAndOauthType(email, OAuthType.TEST)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

userRepository.delete(user);
}

public List<User> getListUsers() {
return userRepository.findAll();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public enum ErrorCode {

// User
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "User404", "사용자를 찾을 수 없습니다."),
DUPLICATE_USER(HttpStatus.CONFLICT, "User409", "이미 존재하는 사용자입니다."),

// Book
BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, "Book404", "도서를 찾을 수 없습니다."),
Expand Down Expand Up @@ -62,4 +63,4 @@ public enum ErrorCode {
private final HttpStatus httpStatus;
private final String code;
private final String message;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/cmc/mercury/global/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public String createRefreshToken(Long userId, String email) {
return refreshToken;
}

private String createToken(Long userId, String email, String tokenType, long validityInMilliseconds) {
public String createToken(Long userId, String email, String tokenType, long validityInMilliseconds) {
Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
Date now = new Date();
Date expiresAt = new Date(now.getTime() + validityInMilliseconds);
Expand Down
14 changes: 7 additions & 7 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ spring:

jpa:
hibernate:
ddl-auto: update
ddl-auto: create
properties:
hibernate:
format_sql: true
Expand All @@ -33,9 +33,9 @@ jwt:
refresh-token-validity: ${JWT_REFRESH_VALIDITY}

logging.level:
org.hibernate:
SQL: DEBUG
type: trace
org.hibernate:
SQL: DEBUG
type: trace

# swagger 관련 설정
springdoc:
Expand All @@ -59,12 +59,12 @@ springdoc:
# swagger 서버 분리
swagger:
server:
http-url: ${SWAGGER_HTTP_URL}
https-url: ${SWAGGER_HTTPS_URL}
http-url: ${SERVER_HTTP_URL}
https-url: ${SERVER_HTTPS_URL}

# 알라딘 Open API 상품 검색 관련 설정
aladin:
api:
url: https://www.aladin.co.kr/ttb/api/ItemSearch.aspx?QueryType=Keyword&SearchTarget=All&Cover=Big&Output=JS
# 검색어 종류: 제목+저자, 검색 대상: 전체, 표지 이미지 크기: 가장 큰 크기, 출력방법: JSON
# 검색어 종류: 제목+저자, 검색 대상: 전체, 표지 이미지 크기: 가장 큰 크기, 출력방법: JSON
ttbkey: ${ALADIN_TTB_KEY}