Skip to content

Commit

Permalink
Merge pull request #49 from IoTeaTime/refactor/48-kan-103-mapper
Browse files Browse the repository at this point in the history
refactor: Mapper 구현, 프로필 설정 분리 등
  • Loading branch information
ywonchae1 authored Oct 31, 2024
2 parents 22722e3 + 998bce8 commit b7cfc8e
Show file tree
Hide file tree
Showing 23 changed files with 183 additions and 135 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.ioteatime.meonghanyangserver.auth.mapper;

import org.ioteatime.meonghanyangserver.user.domain.UserEntity;
import org.ioteatime.meonghanyangserver.user.dto.UserDto;

public class AuthEntityMapper {
public static UserEntity of(UserDto userDto, String encodedPassword) {
return UserEntity.builder()
.nickname(userDto.getNickname())
.email(userDto.getEmail())
.password(encodedPassword)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.ioteatime.meonghanyangserver.auth.mapper;

import org.ioteatime.meonghanyangserver.auth.dto.reponse.LoginResponse;
import org.ioteatime.meonghanyangserver.auth.dto.reponse.RefreshResponse;
import org.ioteatime.meonghanyangserver.user.dto.response.UserSimpleResponse;

public class AuthResponseMapper {
public static UserSimpleResponse from(Long id, String email) {
return new UserSimpleResponse(id, email);
}

public static LoginResponse from(Long id, String accessToken, String refreshToken) {
return LoginResponse.builder()
.userId(id)
.accessToken(accessToken)
.refreshToken(refreshToken)
.build();
}

public static RefreshResponse from(String newAccessToken) {
return new RefreshResponse(newAccessToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
import org.ioteatime.meonghanyangserver.auth.dto.reponse.LoginResponse;
import org.ioteatime.meonghanyangserver.auth.dto.reponse.RefreshResponse;
import org.ioteatime.meonghanyangserver.auth.dto.request.LoginRequest;
import org.ioteatime.meonghanyangserver.auth.mapper.AuthEntityMapper;
import org.ioteatime.meonghanyangserver.auth.mapper.AuthResponseMapper;
import org.ioteatime.meonghanyangserver.clients.google.GoogleMailClient;
import org.ioteatime.meonghanyangserver.common.error.ErrorTypeCode;
import org.ioteatime.meonghanyangserver.common.exception.ApiException;
import org.ioteatime.meonghanyangserver.common.exception.ApiExceptionImpl;
import org.ioteatime.meonghanyangserver.common.utils.JwtUtils;
import org.ioteatime.meonghanyangserver.group.repository.groupuser.GroupUserRepository;
import org.ioteatime.meonghanyangserver.redis.RefreshToken;
Expand All @@ -33,47 +35,34 @@ public LoginResponse login(LoginRequest loginRequest) {
userRepository
.findByEmail(loginRequest.getEmail())
.orElseThrow(
() -> new ApiException(ErrorTypeCode.BAD_REQUEST, "없는 회원입니다."));
() -> new ApiExceptionImpl(ErrorTypeCode.BAD_REQUEST, "없는 회원입니다."));

boolean passwordMatch =
bCryptPasswordEncoder.matches(loginRequest.getPassword(), userEntity.getPassword());
if (!passwordMatch) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "비밀번호가 틀렸습니다.");
throw new ApiExceptionImpl(ErrorTypeCode.BAD_REQUEST, "비밀번호가 틀렸습니다.");
}

String accessToken = jwtUtils.generateAccessToken(userEntity);
String refreshToken = jwtUtils.generateRefreshToken(userEntity);

if (accessToken.isEmpty() || refreshToken.isEmpty()) {
throw new ApiException(ErrorTypeCode.SERVER_ERROR);
throw new ApiExceptionImpl(ErrorTypeCode.SERVER_ERROR);
}
RefreshToken refreshTokenEntity = RefreshToken.builder().refreshToken(refreshToken).build();

refreshTokenRepository.save(refreshTokenEntity);
accessToken = jwtUtils.includeBearer(accessToken);
refreshToken = jwtUtils.includeBearer(refreshToken);

return LoginResponse.builder()
.userId(userEntity.getId())
.accessToken(accessToken)
.refreshToken(refreshToken)
.build();
return AuthResponseMapper.from(userEntity.getId(), accessToken, refreshToken);
}

public UserSimpleResponse joinProcess(UserDto userDto) {
String encodedPassword = bCryptPasswordEncoder.encode(userDto.getPassword());
UserEntity user = userRepository.save(AuthEntityMapper.of(userDto, encodedPassword));

UserEntity userEntity =
UserEntity.builder()
.nickname(userDto.getNickname())
.email(userDto.getEmail())
.password(encodedPassword)
.build();

userRepository.save(userEntity);

// 회원가입 응답 생성
return new UserSimpleResponse(userEntity.getId(), userEntity.getEmail());
return AuthResponseMapper.from(user.getId(), user.getEmail());
}

public void send(String email) {
Expand All @@ -85,8 +74,9 @@ public UserSimpleResponse verifyEmail(String email) {
UserEntity userEntity =
userRepository
.findByEmail(email)
.orElseThrow(() -> new ApiException(ErrorTypeCode.NULL_POINT));
return UserSimpleResponse.from(userEntity);
.orElseThrow(() -> new ApiExceptionImpl(ErrorTypeCode.NULL_POINT));

return AuthResponseMapper.from(userEntity.getId(), userEntity.getEmail());
}

public RefreshResponse reissueAccessToken(String authorizationHeader) {
Expand All @@ -98,28 +88,30 @@ public RefreshResponse reissueAccessToken(String authorizationHeader) {
.findById(userId)
.orElseThrow(
() ->
new ApiException(
new ApiExceptionImpl(
ErrorTypeCode.BAD_REQUEST, "유효하지 않은 사용자입니다."));

if (!jwtUtils.validateToken(refreshToken, userEntity)) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "Refresh token이 만료되었거나 유효하지 않습니다.");
throw new ApiExceptionImpl(
ErrorTypeCode.BAD_REQUEST, "Refresh token이 만료되었거나 유효하지 않습니다.");
}

RefreshToken storedToken =
refreshTokenRepository
.findByRefreshToken(refreshToken)
.orElseThrow(
() ->
new ApiException(
new ApiExceptionImpl(
ErrorTypeCode.BAD_REQUEST,
"유효하지 않은 Refresh token입니다."));

if (!storedToken.getRefreshToken().equals(refreshToken)) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "토큰이 일치하지 않습니다.");
throw new ApiExceptionImpl(ErrorTypeCode.BAD_REQUEST, "토큰이 일치하지 않습니다.");
}

String newAccessToken = jwtUtils.generateAccessToken(userEntity);
newAccessToken = jwtUtils.includeBearer(newAccessToken);
return new RefreshResponse(newAccessToken);

return AuthResponseMapper.from(newAccessToken);
}
}
22 changes: 11 additions & 11 deletions src/main/java/org/ioteatime/meonghanyangserver/common/api/Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.ioteatime.meonghanyangserver.common.error.TypeCodeIfs;
import org.ioteatime.meonghanyangserver.common.error.TypeCode;

@Data
@AllArgsConstructor
Expand Down Expand Up @@ -33,17 +33,17 @@ public static Api<Object> OK() {
}

// 정상 응답
public static <T> Api<T> OK(TypeCodeIfs typeCodeIfs, T data) {
public static <T> Api<T> OK(TypeCode typeCode, T data) {
Api<T> api = new Api<T>();
api.result = Result.OK(typeCodeIfs);
api.result = Result.OK(typeCode);
api.body = data;
return api;
}

// 정상 응답
public static <T> Api<T> OK(TypeCodeIfs typeCodeIfs) {
public static <T> Api<T> OK(TypeCode typeCode) {
Api<T> api = new Api<T>();
api.result = Result.OK(typeCodeIfs);
api.result = Result.OK(typeCode);
return api;
}

Expand All @@ -60,23 +60,23 @@ public static <T> Api<T> CREATE(T data) {
return api;
}

public static Api<Object> CREATE(TypeCodeIfs typeCodeIfs) {
public static Api<Object> CREATE(TypeCode typeCode) {
Api<Object> api = new Api<>();
api.result = Result.CREATE(typeCodeIfs);
api.result = Result.CREATE(typeCode);
return api;
}

public static <T> Api<T> CREATE(TypeCodeIfs typeCodeIfs, T data) {
public static <T> Api<T> CREATE(TypeCode typeCode, T data) {
Api<T> api = new Api<T>();
api.result = Result.CREATE(typeCodeIfs);
api.result = Result.CREATE(typeCode);
api.body = data;
return api;
}

// 에러 응답
public static Api<Object> ERROR(TypeCodeIfs typeCodeIfs) {
public static Api<Object> ERROR(TypeCode typeCode) {
Api<Object> api = new Api<Object>();
api.result = Result.ERROR(typeCodeIfs);
api.result = Result.ERROR(typeCode);
return api;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.Data;
import lombok.NoArgsConstructor;
import org.ioteatime.meonghanyangserver.common.error.SuccessTypeCode;
import org.ioteatime.meonghanyangserver.common.error.TypeCodeIfs;
import org.ioteatime.meonghanyangserver.common.error.TypeCode;

@Builder
@Data
Expand All @@ -26,11 +26,11 @@ public static Result OK() {
}

// 성공 응답 커스텀
public static Result OK(TypeCodeIfs typeCodeIfs) {
public static Result OK(TypeCode typeCode) {
return Result.builder()
.code(typeCodeIfs.getCode())
.message(typeCodeIfs.getMessage())
.description(typeCodeIfs.getDescription())
.code(typeCode.getCode())
.message(typeCode.getMessage())
.description(typeCode.getDescription())
.build();
}

Expand All @@ -43,19 +43,19 @@ public static Result CREATE() {
.build();
}

public static Result CREATE(TypeCodeIfs typeCodeIfs) {
public static Result CREATE(TypeCode typeCode) {
return Result.builder()
.code(typeCodeIfs.getCode())
.message(typeCodeIfs.getMessage())
.description(typeCodeIfs.getDescription())
.code(typeCode.getCode())
.message(typeCode.getMessage())
.description(typeCode.getDescription())
.build();
}

// 에러 응답
public static Result ERROR(TypeCodeIfs typeCodeIfs) {
public static Result ERROR(TypeCode typeCode) {
return Result.builder()
.code(typeCodeIfs.getCode())
.message(typeCodeIfs.getMessage())
.code(typeCode.getCode())
.message(typeCode.getMessage())
.description("ERROR")
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

@AllArgsConstructor
@Getter
public enum ErrorTypeCode implements TypeCodeIfs {
public enum ErrorTypeCode implements TypeCode {
// 잘못된 요청
BAD_REQUEST(400, "bad request", "잘못된 요청"),
// 서버 오류
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

@AllArgsConstructor
@Getter
public enum SuccessTypeCode implements TypeCodeIfs {
public enum SuccessTypeCode implements TypeCode {
// 성공
OK(200, "OK", "success"),
// 생성
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.ioteatime.meonghanyangserver.common.error;

public interface TypeCodeIfs {
public interface TypeCode {
Integer getCode();

String getMessage();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
package org.ioteatime.meonghanyangserver.common.exception;

import lombok.Getter;
import org.ioteatime.meonghanyangserver.common.error.TypeCodeIfs;
import org.ioteatime.meonghanyangserver.common.error.TypeCode;

@Getter
public class ApiException extends RuntimeException implements ApiExceptionItf {
private final TypeCodeIfs typeCodeIfs;
private final String errorDescription;
public interface ApiException {
TypeCode getTypeCode();

public ApiException(TypeCodeIfs typeCodeIfs) {
super(typeCodeIfs.getDescription());
this.typeCodeIfs = typeCodeIfs;
this.errorDescription = typeCodeIfs.getDescription();
}

public ApiException(TypeCodeIfs typeCodeIfs, String errorDescription) {
super(errorDescription);
this.typeCodeIfs = typeCodeIfs;
this.errorDescription = errorDescription;
}
String getErrorDescription();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.ioteatime.meonghanyangserver.common.exception;

import lombok.Getter;
import org.ioteatime.meonghanyangserver.common.error.TypeCode;

@Getter
public class ApiExceptionImpl extends RuntimeException implements ApiException {
private final TypeCode typeCode;
private final String errorDescription;

public ApiExceptionImpl(TypeCode typeCode) {
super(typeCode.getDescription());
this.typeCode = typeCode;
this.errorDescription = typeCode.getDescription();
}

public ApiExceptionImpl(TypeCode typeCode, String errorDescription) {
super(errorDescription);
this.typeCode = typeCode;
this.errorDescription = errorDescription;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public boolean validateToken(String token, UserEntity userEntity) {
}

public String extractTokenFromHeader(String authorizationHeader) {
return authorizationHeader.replace("Bearer ", "");
return authorizationHeader.substring(7);
}

public Long getIdFromToken(String token) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ioteatime.meonghanyangserver.common.error.ErrorTypeCode;
import org.ioteatime.meonghanyangserver.common.exception.ApiException;
import org.ioteatime.meonghanyangserver.common.exception.ApiExceptionImpl;
import org.ioteatime.meonghanyangserver.common.utils.JwtUtils;
import org.ioteatime.meonghanyangserver.group.repository.groupuser.GroupUserRepository;
import org.ioteatime.meonghanyangserver.user.domain.UserEntity;
Expand Down Expand Up @@ -53,13 +53,14 @@ protected void doFilterInternal(
log.debug("jwt : ", jwtToken);
} else {
log.error("Authorization 헤더 누락 또는 토큰 형식 오류");
throw new ApiException(ErrorTypeCode.UNAUTHORIZED, "Authorization 헤더 누락 또는 토큰 형식 오류");
throw new ApiExceptionImpl(
ErrorTypeCode.UNAUTHORIZED, "Authorization 헤더 누락 또는 토큰 형식 오류");
}
if (jwtId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserEntity entity =
userRepository
.findById(jwtId)
.orElseThrow(() -> new ApiException(ErrorTypeCode.BAD_REQUEST));
.orElseThrow(() -> new ApiExceptionImpl(ErrorTypeCode.BAD_REQUEST));

log.debug(entity.getEmail());
if (jwtUtils.validateToken(jwtToken, entity)) {
Expand Down
Loading

0 comments on commit b7cfc8e

Please sign in to comment.