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

Refactor #22 #25

Merged
merged 3 commits into from
Jul 13, 2024
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
Expand Up @@ -3,11 +3,10 @@
import jakarta.validation.Valid;
import leets.weeth.domain.user.dto.UserDTO;
import leets.weeth.domain.user.service.UserService;
import leets.weeth.global.auth.annotation.CurrentUser;
import leets.weeth.global.common.error.exception.custom.BusinessLogicException;
import leets.weeth.global.common.response.CommonResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -24,14 +23,14 @@ public CommonResponse<String> apply(@RequestBody @Valid UserDTO.SignUp requestDt
}

@DeleteMapping("")
public CommonResponse<String> delete(@AuthenticationPrincipal User user) {
userService.delete(user.getUsername());
public CommonResponse<String> delete(@CurrentUser Long userId) {
userService.delete(userId);
return CommonResponse.createSuccess();
}

@PostMapping("/apply/{cardinal}")
public CommonResponse<String> applyOB(@AuthenticationPrincipal User user, @PathVariable Integer cardinal) throws BusinessLogicException {
userService.applyOB(user.getUsername(), cardinal);
public CommonResponse<String> applyOB(@CurrentUser Long userId, @PathVariable Integer cardinal) throws BusinessLogicException {
userService.applyOB(userId, cardinal);
return CommonResponse.createSuccess();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ public void signUp(UserDTO.SignUp requestDto) {
}

@Transactional
public void delete(String email) {
userRepository.findByEmail(email)
public void delete(Long userId) {
userRepository.findById(userId)
.ifPresent(User::leave);
}

@Transactional
public void applyOB(String email, Integer cardinal) throws BusinessLogicException {
User user = userRepository.findByEmail(email)
public void applyOB(Long userId, Integer cardinal) throws BusinessLogicException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("존재하지 않는 사용자입니다."));

if(!user.getStatus().equals(Status.ACTIVE))
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/leets/weeth/global/auth/annotation/CurrentUser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package leets.weeth.global.auth.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {
}
13 changes: 13 additions & 0 deletions src/main/java/leets/weeth/global/auth/jwt/service/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ public Optional<String> extractEmail(String accessToken) {
}
}

public Optional<Long> extractId(String accessToken) {
try {
return Optional.ofNullable(JWT.require(Algorithm.HMAC512(key))
.build()
.verify(accessToken)
.getClaim(ID_CLAIM)
.asLong());
} catch (Exception e) {
log.error("액세스 토큰이 유효하지 않습니다.");
return Optional.empty();
}
}

public void setAccessTokenHeader(HttpServletResponse response, String accessToken) {
response.setHeader(accessHeader, accessToken);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package leets.weeth.global.auth.resolver;

import leets.weeth.global.auth.annotation.CurrentUser;
import leets.weeth.global.auth.jwt.service.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Optional;

@RequiredArgsConstructor
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

private final JwtService jwtService;

@Override
public boolean supportsParameter(MethodParameter parameter) { // parameter가 해당 resolver를 지원하는 여부 확인
boolean hasAnnotation = parameter.hasParameterAnnotation(CurrentUser.class); // @CurrentUser이 존재하는가?
boolean parameterType = Long.class.isAssignableFrom(parameter.getParameterType()); // 파라미터 타입이 Long을 상속하거나 구현하였는가?
return hasAnnotation && parameterType; // 둘 다 충족할 시 true
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // 인증 객체 가져오기

if (authentication instanceof AnonymousAuthenticationToken) { // 익명 인증 토큰의 인스턴스라면 0 반환
return 0;
}

String token = Optional.ofNullable(webRequest.getHeader("Authorization"))
.map(accessToken -> accessToken.replace("Bearer ", "")).get();

return jwtService.extractId(token).get(); // 토큰에서 userId 조회
}
}
22 changes: 22 additions & 0 deletions src/main/java/leets/weeth/global/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package leets.weeth.global.config;

import leets.weeth.global.auth.jwt.service.JwtService;
import leets.weeth.global.auth.resolver.CurrentUserArgumentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

private final JwtService jwtService;;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new CurrentUserArgumentResolver(jwtService));
}
}
Loading