Skip to content

Commit

Permalink
Merge pull request #27 from goormthon-Univ/fix/token
Browse files Browse the repository at this point in the history
[fix/token] Access token만 사용하도록 수정 및 반환 형식 원상복구
  • Loading branch information
JoongHyun-Kim authored Mar 21, 2024
2 parents 5463bde + 096b477 commit a0a7036
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 64 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
implementation 'javax.xml.bind:jaxb-api:2.3.1'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
Expand Down
15 changes: 0 additions & 15 deletions src/main/java/com/hatcher/haemo/common/BaseException.java

This file was deleted.

40 changes: 18 additions & 22 deletions src/main/java/com/hatcher/haemo/common/BaseResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,33 @@
@JsonPropertyOrder({"isSuccess", "code", "message", "result"})
public class BaseResponse<T> {

private final int code;

@JsonProperty("isSuccess")
private final Boolean isSuccess;

private final String message;
private final int code;

@JsonInclude(JsonInclude.Include.NON_NULL)
private T result;


public static <T> BaseResponse<T> success() {
return new BaseResponse<>(
SUCCESS.getCode(),
SUCCESS.isSuccess(),
SUCCESS.getMessage(),
null);
public BaseResponse(T result) {
this.isSuccess = SUCCESS.isSuccess();
this.message = SUCCESS.getMessage();
this.code = SUCCESS.getCode();
this.result = result;
}

public static <T> BaseResponse<T> success(T result) {
return new BaseResponse<>(
SUCCESS.getCode(),
SUCCESS.isSuccess(),
SUCCESS.getMessage(),
result);
public BaseResponse(BaseResponseStatus status) {
this.isSuccess = status.isSuccess();
this.message = status.getMessage();
this.code = status.getCode();
}

public static <T> BaseResponse<T> failure(BaseResponseStatus status) {
return new BaseResponse<>(
status.getCode(),
status.isSuccess(),
status.getMessage(),
null);
// 요청은 성공했지만 데이터에 이상이 있는 경우
public BaseResponse(T result, BaseResponseStatus status) {
this.isSuccess = status.isSuccess();
this.message = status.getMessage();
this.code = status.getCode();
this.result = result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ public enum BaseResponseStatus {
INVALID_ACCESS_TOKEN(false, HttpStatus.BAD_REQUEST, "잘못된 access token 입니다."),
NULL_ACCESS_TOKEN(false, HttpStatus.BAD_REQUEST, "access token을 입력해주세요."),
INVALID_JWT_SIGNATURE(false, HttpStatus.BAD_REQUEST, "유효하지 않은 JWT 시그니처입니다."),
EXPIRED_ACCESS_TOKEN(false, HttpStatus.BAD_REQUEST, "만료된 토큰입니다."),
EXPIRED_ACCESS_TOKEN(false, HttpStatus.BAD_REQUEST, "만료된 access token 입니다."),
EXPIRED_REFRESH_TOKEN(false, HttpStatus.BAD_REQUEST, "만료된 refresh token 입니다."),
EMPTY_JWT_CLAIM(false, HttpStatus.BAD_REQUEST, "JWT claims string이 비었습니다."),
UNSUPPORTED_JWT_TOKEN(false, HttpStatus.BAD_REQUEST, "지원하지 않는 JWT 토큰 형식입니다."),
INVALID_REFRESH_TOKEN(false, HttpStatus.BAD_REQUEST, "유효하지 않은 refresh token 입니다."),

ACCESS_DENIED(false, HttpStatus.FORBIDDEN, "접근 권한이 없습니다."),

Expand Down
18 changes: 13 additions & 5 deletions src/main/java/com/hatcher/haemo/common/enums/RecruitType.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.hatcher.haemo.common.enums;

import com.hatcher.haemo.common.BaseException;

import com.hatcher.haemo.common.exception.BaseException;
import java.util.Arrays;

import static com.hatcher.haemo.common.enums.BaseResponseStatus.WRONG_RECRUIT_TYPE;
Expand All @@ -16,12 +15,21 @@ public enum RecruitType {
COIN_KARAOKE("코인노래방"),
DELIVERY_FOOD("배달음식");

RecruitType(String name) {}
private final String description; // 설명 필드 추가

RecruitType(String description) {
this.description = description;
}

public String getDescription() { // 설명을 반환하는 메소드
return description;
}

public static RecruitType getEnumByName(String name) throws BaseException {
public static RecruitType getEnumByName(String name) throws BaseException{
return Arrays.stream(RecruitType.values())
.filter(recruitType -> recruitType.name().equalsIgnoreCase(name))
.filter(recruitType -> recruitType.getDescription().equalsIgnoreCase(name))
.findFirst()
//.orElseThrow(() -> new IllegalArgumentException("찾을 수 없습니다."));
.orElseThrow(() -> new BaseException(WRONG_RECRUIT_TYPE));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.hatcher.haemo.common.exception;

import com.hatcher.haemo.common.enums.BaseResponseStatus;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
public class BaseException extends Exception {
private BaseResponseStatus status;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hatcher.haemo.recruitment.application;

import com.hatcher.haemo.common.BaseException;
import com.hatcher.haemo.common.BaseResponse;
import com.hatcher.haemo.common.exception.BaseException;
import com.hatcher.haemo.common.enums.RecruitType;
import com.hatcher.haemo.recruitment.domain.Recruitment;
import com.hatcher.haemo.recruitment.dto.RecruitmentPostRequest;
Expand All @@ -13,8 +14,7 @@
import org.springframework.transaction.annotation.Transactional;

import static com.hatcher.haemo.common.constants.Constant.Recruitment.RECRUITING;
import static com.hatcher.haemo.common.enums.BaseResponseStatus.INTERNAL_SERVER_ERROR;
import static com.hatcher.haemo.common.enums.BaseResponseStatus.INVALID_USER_IDX;
import static com.hatcher.haemo.common.enums.BaseResponseStatus.*;

@Service
@RequiredArgsConstructor
Expand All @@ -26,14 +26,15 @@ public class RecruitmentService {

// 모집글 등록
@Transactional(rollbackFor = Exception.class)
public void postRecruitment(RecruitmentPostRequest recruitmentPostRequest) throws BaseException {
public BaseResponse<String> postRecruitment(RecruitmentPostRequest recruitmentPostRequest) throws BaseException{
try {
User leader = userRepository.findById(userService.getUserIdxWithValidation()).orElseThrow(() -> new BaseException(INVALID_USER_IDX));

Recruitment recruitment = new Recruitment(recruitmentPostRequest.name(), leader, RecruitType.getEnumByName(recruitmentPostRequest.type()),
recruitmentPostRequest.participantLimit(), recruitmentPostRequest.contactUrl(), recruitmentPostRequest.description());
recruitment.setStatus(RECRUITING);
recruitmentRepository.save(recruitment);
return new BaseResponse<>(SUCCESS);
} catch (BaseException e) {
throw e;
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.hatcher.haemo.recruitment.presentation;

import com.hatcher.haemo.common.BaseException;
import com.hatcher.haemo.common.exception.BaseException;
import com.hatcher.haemo.common.BaseResponse;
import com.hatcher.haemo.recruitment.application.RecruitmentService;
import com.hatcher.haemo.recruitment.dto.RecruitmentListResponse;
import com.hatcher.haemo.recruitment.dto.RecruitmentPostRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
Expand All @@ -20,8 +19,11 @@ public class RecruitmentController {
// 모집글 등록
@PostMapping("")
public BaseResponse<?> postRecruitment(@RequestBody RecruitmentPostRequest recruitmentPostRequest) {
recruitmentService.postRecruitment(recruitmentPostRequest);
return BaseResponse.success();
try {
return recruitmentService.postRecruitment(recruitmentPostRequest);
} catch(BaseException e) {
return new BaseResponse<>(e.getStatus());
}
}

// // 모집글 목록 조회
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.hatcher.haemo.user.application;

import com.hatcher.haemo.common.BaseException;
import com.hatcher.haemo.common.exception.*;
import com.hatcher.haemo.user.domain.User;
import com.hatcher.haemo.user.dto.LoginRequest;
import com.hatcher.haemo.user.dto.SignupRequest;
import com.hatcher.haemo.user.dto.TokenResponse;
import com.hatcher.haemo.user.dto.*;
import com.hatcher.haemo.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
Expand Down Expand Up @@ -37,7 +35,7 @@ public TokenResponse signup(SignupRequest signupRequest) throws BaseException {

// 로그인
@Transactional(rollbackFor = Exception.class)
public TokenResponse login(LoginRequest loginRequest) throws BaseException {
public TokenResponse login(LoginRequest loginRequest) throws BaseException{
try {
User user = userRepository.findByLoginId(loginRequest.loginId()).orElseThrow(() -> new BaseException(LOGIN_ID_NOT_FOUND));
if(!encoder.matches(loginRequest.password(), user.getPassword())) throw new BaseException(WRONG_PASSWORD);
Expand Down Expand Up @@ -67,11 +65,12 @@ public void validateLoginId(String loginId) throws BaseException {
public User getUserByUserIdx(Long userIdx) {
if(userIdx == null) return null;
else {
Optional<User> user = userRepository.findById(userIdx);
Optional<User> user = userRepository.findByUserIdx(userIdx);
return user.orElse(null);
}
}

// 회원만
public Long getUserIdxWithValidation() throws BaseException {
Long userIdx = authService.getUserIdx();
if (userIdx == null) throw new BaseException(NULL_ACCESS_TOKEN);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.hatcher.haemo.user.presentation;

import com.hatcher.haemo.common.BaseException;
import com.hatcher.haemo.common.exception.BaseException;
import com.hatcher.haemo.common.BaseResponse;
import com.hatcher.haemo.user.application.UserService;
import com.hatcher.haemo.user.dto.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import static com.hatcher.haemo.common.constants.RequestURI.user;
import static com.hatcher.haemo.common.enums.BaseResponseStatus.SUCCESS;

@RestController
@RequiredArgsConstructor
Expand All @@ -18,26 +19,42 @@ public class UserController {
// 회원가입
@PostMapping(value = "/signup")
public BaseResponse<TokenResponse> signup(@RequestBody SignupRequest signupRequest) {
return BaseResponse.success(userService.signup(signupRequest));
try {
return new BaseResponse<>(userService.signup(signupRequest));
} catch(BaseException e) {
return new BaseResponse<>(e.getStatus());
}
}

// 로그인
@PostMapping("/login")
public BaseResponse<TokenResponse> login(@RequestBody LoginRequest loginRequest) {
return BaseResponse.success(userService.login(loginRequest));
try {
return new BaseResponse<>(userService.login(loginRequest));
} catch(BaseException e) {
return new BaseResponse<>(e.getStatus());
}
}

// 닉네임 중복 체크
@PostMapping("/nickname")
public BaseResponse<String> validateNickname(@RequestBody NicknameRequest nicknameRequest) {
userService.validateNickname(nicknameRequest.nickname());
return BaseResponse.success();
try {
userService.validateNickname(nicknameRequest.nickname());
return new BaseResponse<>(SUCCESS);
} catch(BaseException e) {
return new BaseResponse<>(e.getStatus());
}
}

// 아이디 중복 체크
@PostMapping("/loginId")
public BaseResponse<String> validateLoginId(@RequestBody LoginIdRequest loginIdRequest) {
userService.validateLoginId(loginIdRequest.loginId());
return BaseResponse.success();
try {
userService.validateLoginId(loginIdRequest.loginId());
return new BaseResponse<>(SUCCESS);
} catch(BaseException e) {
return new BaseResponse<>(e.getStatus());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUserIdxAndStatusEquals(Long userIdx, String status);
boolean existsByNickname(String nickname);
boolean existsByLoginId(String loginId);
Optional<User> findByUserIdx(Long userIdx);
Optional<User> findByLoginIdAndStatusEquals(String loginId, String status);
}

0 comments on commit a0a7036

Please sign in to comment.