From 5649054ef3800ff9aa48588449addae2efc68e28 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:37:13 +0900 Subject: [PATCH 1/8] =?UTF-8?q?[Chore]=20#236=20-=20build.gradle=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 5 +++++ moonshot-api/build.gradle | 1 - moonshot-auth/build.gradle | 5 ++--- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index fc366cc9..bcfe5ce5 100644 --- a/build.gradle +++ b/build.gradle @@ -29,6 +29,11 @@ subprojects { } dependencies { + // Spring Security + + //Spring Security + implementation 'org.springframework.boot:spring-boot-starter-security' + // lombok compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' diff --git a/moonshot-api/build.gradle b/moonshot-api/build.gradle index 458f2724..ee1917f9 100644 --- a/moonshot-api/build.gradle +++ b/moonshot-api/build.gradle @@ -1,7 +1,6 @@ dependencies { // Spring Framework implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-actuator' diff --git a/moonshot-auth/build.gradle b/moonshot-auth/build.gradle index 181573b7..effb204d 100644 --- a/moonshot-auth/build.gradle +++ b/moonshot-auth/build.gradle @@ -3,13 +3,11 @@ jar { enabled = true } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' //External API implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' - //Spring Security - implementation 'org.springframework.boot:spring-boot-starter-security' - //JWT implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5' implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5' @@ -19,6 +17,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-redis:3.2.1' implementation project(":moonshot-common") + implementation project(":moonshot-domain") } ext { From 57b154f692f83628018de607f7ecea0e33c50d16 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:40:56 +0900 Subject: [PATCH 2/8] =?UTF-8?q?[Del]=20#236=20-=20UserRepository=20?= =?UTF-8?q?=EA=B3=B5=EB=B0=B1=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/org/moonshot/user/repository/UserRepository.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/moonshot-domain/src/main/java/org/moonshot/user/repository/UserRepository.java b/moonshot-domain/src/main/java/org/moonshot/user/repository/UserRepository.java index 65b47f76..2527f08d 100644 --- a/moonshot-domain/src/main/java/org/moonshot/user/repository/UserRepository.java +++ b/moonshot-domain/src/main/java/org/moonshot/user/repository/UserRepository.java @@ -6,15 +6,12 @@ import java.util.Optional; import org.moonshot.user.model.User; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; -import org.springframework.transaction.annotation.Transactional; public interface UserRepository extends JpaRepository { Optional findUserBySocialId(String socialId); Optional findUserByNickname(String nickname); - @Query("SELECT u FROM User u WHERE u.deleteAt < :currentDate") List findIdByDeletedAtBefore(LocalDateTime currentDate); From 29cdb6fdf6829f27078b50e233f3fda79a5874e5 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:41:39 +0900 Subject: [PATCH 3/8] =?UTF-8?q?[Feat]=20#236=20-=20@LoginUser=20=EC=96=B4?= =?UTF-8?q?=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 2 +- .../moonshot/user/service/UserService.java | 14 ++--- .../org/moonshot/jwt/JwtTokenProvider.java | 25 +++++--- .../security/JwtAuthenticationFilter.java | 5 +- .../moonshot/security/UserAuthentication.java | 24 ++++++-- .../service/UserPrincipalDetailsService.java | 25 ++++++++ .../exception/user/UnauthorizedException.java | 12 ++++ .../org/moonshot/user/model/LoginUser.java | 14 +++++ .../moonshot/user/model/UserPrincipal.java | 60 +++++++++++++++++++ 9 files changed, 155 insertions(+), 26 deletions(-) create mode 100644 moonshot-auth/src/main/java/org/moonshot/security/service/UserPrincipalDetailsService.java create mode 100644 moonshot-common/src/main/java/org/moonshot/exception/user/UnauthorizedException.java create mode 100644 moonshot-domain/src/main/java/org/moonshot/user/model/LoginUser.java create mode 100644 moonshot-domain/src/main/java/org/moonshot/user/model/UserPrincipal.java diff --git a/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java b/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java index c9e73539..9d813b04 100644 --- a/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java +++ b/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java @@ -73,7 +73,7 @@ public ResponseEntity withdrawal(final Principal principal) { @PatchMapping("/profile") @Logging(item = "User", action = "Patch") - public ResponseEntity modifyProfile(final Principal principal, @Valid @RequestBody final UserInfoRequest userInfoRequest) { + public ResponseEntity modifyProfile(final Principal principal, @Valid @RequestBody final UserInfoRequest userInfoRequest) { userService.modifyProfile(JwtTokenProvider.getUserIdFromPrincipal(principal), userInfoRequest); return ResponseEntity.noContent().build(); } diff --git a/moonshot-api/src/main/java/org/moonshot/user/service/UserService.java b/moonshot-api/src/main/java/org/moonshot/user/service/UserService.java index 342ef5f6..884c5f2f 100644 --- a/moonshot-api/src/main/java/org/moonshot/user/service/UserService.java +++ b/moonshot-api/src/main/java/org/moonshot/user/service/UserService.java @@ -1,6 +1,8 @@ package org.moonshot.user.service; -import static org.moonshot.user.service.validator.UserValidator.*; +import static org.moonshot.user.service.validator.UserValidator.hasChange; +import static org.moonshot.user.service.validator.UserValidator.isNewUser; +import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization; import static org.moonshot.util.MDCUtil.USER_REQUEST_ORIGIN; import static org.moonshot.util.MDCUtil.get; @@ -24,7 +26,6 @@ import org.moonshot.openfeign.google.GoogleAuthApiClient; import org.moonshot.openfeign.kakao.KakaoApiClient; import org.moonshot.openfeign.kakao.KakaoAuthApiClient; -import org.moonshot.security.UserAuthentication; import org.moonshot.user.dto.request.SocialLoginRequest; import org.moonshot.user.dto.request.UserInfoRequest; import org.moonshot.user.dto.response.SocialLoginResponse; @@ -99,8 +100,7 @@ public SocialLoginResponse googleLogin(final SocialLoginRequest request) throws user = findUser.get(); user.resetDeleteAt(); } - UserAuthentication userAuthentication = new UserAuthentication(user.getId(), null, null); - TokenResponse token = new TokenResponse(jwtTokenProvider.generateAccessToken(userAuthentication), jwtTokenProvider.generateRefreshToken(userAuthentication)); + TokenResponse token = new TokenResponse(jwtTokenProvider.generateAccessToken(user.getId()), jwtTokenProvider.generateRefreshToken(user.getId())); return SocialLoginResponse.of(user.getId(), user.getName(), token); } @@ -129,8 +129,7 @@ public SocialLoginResponse kakaoLogin(final SocialLoginRequest request) { user = findUser.get(); user.resetDeleteAt(); } - UserAuthentication userAuthentication = new UserAuthentication(user.getId(), null, null); - TokenResponse token = new TokenResponse(jwtTokenProvider.generateAccessToken(userAuthentication), jwtTokenProvider.generateRefreshToken(userAuthentication)); + TokenResponse token = new TokenResponse(jwtTokenProvider.generateAccessToken(user.getId()), jwtTokenProvider.generateRefreshToken(user.getId())); return SocialLoginResponse.of(user.getId(), user.getName(), token); } @@ -138,8 +137,7 @@ public TokenResponse reissue(final String refreshToken) { String token = refreshToken.substring("Bearer ".length()); Long userId = jwtTokenProvider.validateRefreshToken(token); jwtTokenProvider.deleteRefreshToken(userId); - UserAuthentication userAuthentication = new UserAuthentication(userId, null, null); - return jwtTokenProvider.reissuedToken(userAuthentication); + return jwtTokenProvider.reissuedToken(userId); } public void logout(final Long userId) { diff --git a/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java b/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java index cbb95d8d..df5bdeb8 100644 --- a/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java +++ b/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java @@ -23,6 +23,9 @@ import org.moonshot.exception.global.auth.InvalidRefreshTokenException; import org.moonshot.exception.global.common.MoonshotException; import org.moonshot.response.ErrorType; +import org.moonshot.security.UserAuthentication; +import org.moonshot.security.service.UserPrincipalDetailsService; +import org.moonshot.user.model.UserPrincipal; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; @@ -36,6 +39,7 @@ public class JwtTokenProvider { private final RedisTemplate redisTemplate; + private final UserPrincipalDetailsService userPrincipalDetailsService; @Value("${jwt.secret}") private String JWT_SECRET; @@ -45,19 +49,19 @@ protected void init() { JWT_SECRET = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes(StandardCharsets.UTF_8)); } - public TokenResponse reissuedToken(Authentication authentication) { + public TokenResponse reissuedToken(Long userId) { return TokenResponse.of( - generateAccessToken(authentication), - generateRefreshToken(authentication)); + generateAccessToken(userId), + generateRefreshToken(userId)); } - public String generateAccessToken(Authentication authentication) { + public String generateAccessToken(Long userId) { final Date now = new Date(); final Claims claims = Jwts.claims() .setIssuedAt(now) .setExpiration(new Date(now.getTime() + JWTConstants.ACCESS_TOKEN_EXPIRATION_TIME)); - claims.put(JWTConstants.USER_ID, authentication.getPrincipal()); + claims.put(JWTConstants.USER_ID, userId); return Jwts.builder() .setHeaderParam(Header.TYPE, Header.JWT_TYPE) @@ -66,13 +70,13 @@ public String generateAccessToken(Authentication authentication) { .compact(); } - public String generateRefreshToken(Authentication authentication) { + public String generateRefreshToken(Long userId) { final Date now = new Date(); final Claims claims = Jwts.claims() .setIssuedAt(now) .setExpiration(new Date(now.getTime() + JWTConstants.REFRESH_TOKEN_EXPIRATION_TIME)); - claims.put(JWTConstants.USER_ID, authentication.getPrincipal()); + claims.put(JWTConstants.USER_ID, userId); String refreshToken = Jwts.builder() .setHeaderParam(Header.TYPE, Header.JWT_TYPE) @@ -81,7 +85,7 @@ public String generateRefreshToken(Authentication authentication) { .compact(); redisTemplate.opsForValue().set( - authentication.getName(), + String.valueOf(userId), refreshToken, JWTConstants.REFRESH_TOKEN_EXPIRATION_TIME, TimeUnit.MILLISECONDS @@ -158,4 +162,9 @@ public static Long getUserIdFromPrincipal(Principal principal) { return Long.valueOf(principal.getName()); } + public Authentication getAuthentication(Long userId) { + UserPrincipal userDetails = (UserPrincipal) userPrincipalDetailsService.loadUserByUsername(String.valueOf(userId)); + return new UserAuthentication(userDetails); + } + } \ No newline at end of file diff --git a/moonshot-auth/src/main/java/org/moonshot/security/JwtAuthenticationFilter.java b/moonshot-auth/src/main/java/org/moonshot/security/JwtAuthenticationFilter.java index ddb91376..62ef5992 100644 --- a/moonshot-auth/src/main/java/org/moonshot/security/JwtAuthenticationFilter.java +++ b/moonshot-auth/src/main/java/org/moonshot/security/JwtAuthenticationFilter.java @@ -11,8 +11,8 @@ import org.moonshot.constants.WhiteListConstants; import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.jwt.JwtValidationType; +import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -35,8 +35,7 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull Ht final String token = getJwtFromRequest(request); if (jwtTokenProvider.validateAccessToken(token) == JwtValidationType.VALID_JWT) { Long userId = jwtTokenProvider.getUserFromJwt(token); - UserAuthentication authentication = new UserAuthentication(userId, null, null); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + Authentication authentication = jwtTokenProvider.getAuthentication(userId); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(request, response); diff --git a/moonshot-auth/src/main/java/org/moonshot/security/UserAuthentication.java b/moonshot-auth/src/main/java/org/moonshot/security/UserAuthentication.java index ae130a59..ee4f53e7 100644 --- a/moonshot-auth/src/main/java/org/moonshot/security/UserAuthentication.java +++ b/moonshot-auth/src/main/java/org/moonshot/security/UserAuthentication.java @@ -1,14 +1,26 @@ package org.moonshot.security; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import java.util.Collection; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.userdetails.UserDetails; -public class UserAuthentication extends UsernamePasswordAuthenticationToken { +public class UserAuthentication extends AbstractAuthenticationToken { - public UserAuthentication(Object principal, Object credentials, Collection authorities) { - super(principal, credentials, authorities); + private final UserDetails userPrincipal; + + public UserAuthentication(UserDetails userPrincipal) { + super(userPrincipal.getAuthorities()); + super.setAuthenticated(true); + this.userPrincipal = userPrincipal; + } + + @Override + public Object getCredentials() { + return null; } + @Override + public Object getPrincipal() { + return userPrincipal; + } } \ No newline at end of file diff --git a/moonshot-auth/src/main/java/org/moonshot/security/service/UserPrincipalDetailsService.java b/moonshot-auth/src/main/java/org/moonshot/security/service/UserPrincipalDetailsService.java new file mode 100644 index 00000000..10e12f4f --- /dev/null +++ b/moonshot-auth/src/main/java/org/moonshot/security/service/UserPrincipalDetailsService.java @@ -0,0 +1,25 @@ +package org.moonshot.security.service; + +import lombok.RequiredArgsConstructor; +import org.moonshot.exception.user.UnauthorizedException; +import org.moonshot.user.model.UserPrincipal; +import org.moonshot.user.repository.UserRepository; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class UserPrincipalDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return userRepository.findById(Long.parseLong(username)) + .map(UserPrincipal::new) + .orElseThrow(UnauthorizedException::new); + } + +} diff --git a/moonshot-common/src/main/java/org/moonshot/exception/user/UnauthorizedException.java b/moonshot-common/src/main/java/org/moonshot/exception/user/UnauthorizedException.java new file mode 100644 index 00000000..ee5192e7 --- /dev/null +++ b/moonshot-common/src/main/java/org/moonshot/exception/user/UnauthorizedException.java @@ -0,0 +1,12 @@ +package org.moonshot.exception.user; + +import org.moonshot.exception.global.common.MoonshotException; +import org.moonshot.response.ErrorType; + +public class UnauthorizedException extends MoonshotException { + + public UnauthorizedException() { + super(ErrorType.INVALID_AUTH_ERROR); + } + +} diff --git a/moonshot-domain/src/main/java/org/moonshot/user/model/LoginUser.java b/moonshot-domain/src/main/java/org/moonshot/user/model/LoginUser.java new file mode 100644 index 00000000..c30c69a8 --- /dev/null +++ b/moonshot-domain/src/main/java/org/moonshot/user/model/LoginUser.java @@ -0,0 +1,14 @@ +package org.moonshot.user.model; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.springframework.security.core.annotation.AuthenticationPrincipal; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@AuthenticationPrincipal(expression = "userId == null ? 0L : userId") +public @interface LoginUser { +} diff --git a/moonshot-domain/src/main/java/org/moonshot/user/model/UserPrincipal.java b/moonshot-domain/src/main/java/org/moonshot/user/model/UserPrincipal.java new file mode 100644 index 00000000..9fd69a82 --- /dev/null +++ b/moonshot-domain/src/main/java/org/moonshot/user/model/UserPrincipal.java @@ -0,0 +1,60 @@ +package org.moonshot.user.model; + +import java.util.Collection; +import java.util.List; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +public class UserPrincipal implements UserDetails { + + private final User user; + private final List grantedAuthorities; + + public UserPrincipal(User user) { + this.user = user; + this.grantedAuthorities = user.getId() == null ? + List.of(new SimpleGrantedAuthority("ANONYMOUS")) : + List.of(new SimpleGrantedAuthority("USER")); + } + + @Override + public Collection getAuthorities() { + return grantedAuthorities; + } + + @Override + public String getPassword() { + return null; + } + + @Override + public String getUsername() { + return user.getName(); + } + + @Override + public boolean isAccountNonExpired() { + return false; + } + + @Override + public boolean isAccountNonLocked() { + return false; + } + + @Override + public boolean isCredentialsNonExpired() { + return false; + } + + @Override + public boolean isEnabled() { + return false; + } + + public Long getUserId() { + return user.getId(); + } + +} From 7366077042d6447b4918b8350cf78ad3352ed5e9 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:51:14 +0900 Subject: [PATCH 4/8] =?UTF-8?q?[Fix]=20#236=20-=20Controller=EC=97=90?= =?UTF-8?q?=EC=84=9C=20Principal=20=EC=A0=9C=EA=B1=B0=20=ED=9B=84=20@Login?= =?UTF-8?q?User=EB=A1=9C=20userId=20=EC=A3=BC=EC=9E=85=20=EB=B0=A9?= =?UTF-8?q?=EC=8B=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/KeyResultController.java | 20 ++++++------- .../log/controller/LogController.java | 11 ++++---- .../controller/ObjectiveController.java | 23 ++++++++------- .../task/controller/TaskController.java | 18 +++++++----- .../user/controller/UserController.java | 28 +++++++------------ 5 files changed, 46 insertions(+), 54 deletions(-) diff --git a/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultController.java b/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultController.java index 2194830b..5b87f188 100644 --- a/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultController.java +++ b/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultController.java @@ -6,10 +6,8 @@ import static org.moonshot.response.SuccessType.POST_KEY_RESULT_SUCCESS; import jakarta.validation.Valid; -import java.security.Principal; import java.util.Optional; import lombok.RequiredArgsConstructor; -import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.keyresult.dto.request.KeyResultCreateRequestDto; import org.moonshot.keyresult.dto.request.KeyResultModifyRequestDto; import org.moonshot.keyresult.dto.response.KRDetailResponseDto; @@ -18,6 +16,7 @@ import org.moonshot.model.Logging; import org.moonshot.response.MoonshotResponse; import org.moonshot.response.SuccessType; +import org.moonshot.user.model.LoginUser; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -38,22 +37,22 @@ public class KeyResultController implements KeyResultApi { @PostMapping @Logging(item = "KeyResult", action = "Post") - public ResponseEntity> createKeyResult(final Principal principal, @RequestBody @Valid final KeyResultCreateRequestDto request) { - keyResultService.createKeyResult(request, JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity> createKeyResult(@LoginUser Long userId, @RequestBody @Valid final KeyResultCreateRequestDto request) { + keyResultService.createKeyResult(request, userId); return ResponseEntity.status(HttpStatus.CREATED).body(MoonshotResponse.success(POST_KEY_RESULT_SUCCESS)); } @DeleteMapping("/{keyResultId}") @Logging(item = "KeyResult", action = "Delete") - public ResponseEntity deleteKeyResult(final Principal principal, @PathVariable("keyResultId") final Long keyResultId) { - keyResultService.deleteKeyResult(keyResultId, JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity deleteKeyResult(@LoginUser Long userId, @PathVariable("keyResultId") final Long keyResultId) { + keyResultService.deleteKeyResult(keyResultId, userId); return ResponseEntity.noContent().build(); } @PatchMapping @Logging(item = "KeyResult", action = "Patch") - public ResponseEntity> modifyKeyResult(final Principal principal, @RequestBody @Valid final KeyResultModifyRequestDto request) { - Optional response = keyResultService.modifyKeyResult(request, JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity> modifyKeyResult(@LoginUser Long userId, @RequestBody @Valid final KeyResultModifyRequestDto request) { + Optional response = keyResultService.modifyKeyResult(request, userId); if (response.isPresent()) { return ResponseEntity.ok(MoonshotResponse.success(PATCH_KR_ACHIEVE_SUCCESS, response)); } @@ -62,9 +61,8 @@ public ResponseEntity> modifyKeyResult(final Principal princ @GetMapping("/{keyResultId}") @Logging(item = "KeyResult", action = "Get") - public ResponseEntity> getKRDetails(final Principal principal, @PathVariable("keyResultId") final Long keyResultId) { - return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_KR_DETAIL_SUCCESS, keyResultService.getKRDetails( - JwtTokenProvider.getUserIdFromPrincipal(principal), keyResultId))); + public ResponseEntity> getKRDetails(@LoginUser Long userId, @PathVariable("keyResultId") final Long keyResultId) { + return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_KR_DETAIL_SUCCESS, keyResultService.getKRDetails(userId, keyResultId))); } } diff --git a/moonshot-api/src/main/java/org/moonshot/log/controller/LogController.java b/moonshot-api/src/main/java/org/moonshot/log/controller/LogController.java index 660b2d1e..fd37c665 100644 --- a/moonshot-api/src/main/java/org/moonshot/log/controller/LogController.java +++ b/moonshot-api/src/main/java/org/moonshot/log/controller/LogController.java @@ -1,16 +1,15 @@ package org.moonshot.log.controller; import jakarta.validation.Valid; -import java.security.Principal; import java.util.Optional; import lombok.RequiredArgsConstructor; -import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.log.dto.request.LogCreateRequestDto; import org.moonshot.log.dto.response.AchieveResponseDto; import org.moonshot.log.service.LogService; import org.moonshot.model.Logging; import org.moonshot.response.MoonshotResponse; import org.moonshot.response.SuccessType; +import org.moonshot.user.model.LoginUser; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; @@ -27,11 +26,11 @@ public class LogController implements LogApi { @PostMapping @Logging(item = "Log", action = "Post") - public ResponseEntity> create(final Principal principal, @RequestBody @Valid final LogCreateRequestDto logCreateRequestDto) { - Optional response = logService.createRecordLog(JwtTokenProvider.getUserIdFromPrincipal(principal), logCreateRequestDto); + public ResponseEntity> create(@LoginUser Long userId, @RequestBody @Valid final LogCreateRequestDto logCreateRequestDto) { + Optional response = logService.createRecordLog(userId, logCreateRequestDto); + if (response.isPresent()) { - return ResponseEntity.status(HttpStatus.CREATED).body( - MoonshotResponse.success(SuccessType.POST_LOG_ACHIEVE_SUCCESS, response)); + return ResponseEntity.status(HttpStatus.CREATED).body(MoonshotResponse.success(SuccessType.POST_LOG_ACHIEVE_SUCCESS, response)); } return ResponseEntity.status(HttpStatus.CREATED).body(MoonshotResponse.success(SuccessType.POST_LOG_SUCCESS)); } diff --git a/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveController.java b/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveController.java index a7e6cc4d..157e0d37 100644 --- a/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveController.java +++ b/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveController.java @@ -2,10 +2,8 @@ import jakarta.annotation.Nullable; import jakarta.validation.Valid; -import java.security.Principal; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.model.Logging; import org.moonshot.objective.dto.request.ModifyObjectiveRequestDto; import org.moonshot.objective.dto.request.OKRCreateRequestDto; @@ -16,6 +14,7 @@ import org.moonshot.objective.service.ObjectiveService; import org.moonshot.response.MoonshotResponse; import org.moonshot.response.SuccessType; +import org.moonshot.user.model.LoginUser; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -38,38 +37,38 @@ public class ObjectiveController implements ObjectiveApi { @PostMapping @Logging(item = "Objective", action = "Post") - public ResponseEntity> createObjective(final Principal principal, @RequestBody @Valid final OKRCreateRequestDto request) { - objectiveService.createObjective(JwtTokenProvider.getUserIdFromPrincipal(principal), request); + public ResponseEntity> createObjective(@LoginUser Long userId, @RequestBody @Valid final OKRCreateRequestDto request) { + objectiveService.createObjective(userId, request); return ResponseEntity.status(HttpStatus.CREATED).body(MoonshotResponse.success(SuccessType.POST_OKR_SUCCESS)); } @DeleteMapping("/{objectiveId}") @Logging(item = "Objective", action = "Delete") - public ResponseEntity> deleteObjective(final Principal principal, @PathVariable("objectiveId") final Long objectiveId) { - DashboardResponseDto response = objectiveService.deleteObjective(JwtTokenProvider.getUserIdFromPrincipal(principal), objectiveId); + public ResponseEntity> deleteObjective(@LoginUser Long userId, @PathVariable("objectiveId") final Long objectiveId) { + DashboardResponseDto response = objectiveService.deleteObjective(userId, objectiveId); return ResponseEntity.ok(MoonshotResponse.success(SuccessType.DELETE_OBJECTIVE_SUCCESS, response)); } @PatchMapping @Logging(item = "Objective", action = "Patch") - public ResponseEntity modifyObjective(final Principal principal, @RequestBody final ModifyObjectiveRequestDto request) { - objectiveService.modifyObjective(JwtTokenProvider.getUserIdFromPrincipal(principal), request); + public ResponseEntity modifyObjective(@LoginUser Long userId, @RequestBody final ModifyObjectiveRequestDto request) { + objectiveService.modifyObjective(userId, request); return ResponseEntity.noContent().build(); } @GetMapping @Logging(item = "Objective", action = "Get") - public ResponseEntity> getObjectiveInDashboard(final Principal principal, @Nullable @RequestParam("objectiveId") final Long objectiveId) { - DashboardResponseDto response = objectiveService.getObjectiveInDashboard(JwtTokenProvider.getUserIdFromPrincipal(principal), objectiveId); + public ResponseEntity> getObjectiveInDashboard(@LoginUser Long userId, @Nullable @RequestParam("objectiveId") final Long objectiveId) { + DashboardResponseDto response = objectiveService.getObjectiveInDashboard(userId, objectiveId); return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_OKR_LIST_SUCCESS, response)); } @GetMapping("/history") @Logging(item = "Objective", action = "Get") - public ResponseEntity> getObjectiveHistory(final Principal principal, @RequestParam(required = false) final Integer year, + public ResponseEntity> getObjectiveHistory(@LoginUser Long userId, @RequestParam(required = false) final Integer year, @RequestParam(required = false) final Category category, @RequestParam(required = false) final Criteria criteria) { - HistoryResponseDto response = objectiveService.getObjectiveHistory(JwtTokenProvider.getUserIdFromPrincipal(principal), year, category, criteria); + HistoryResponseDto response = objectiveService.getObjectiveHistory(userId, year, category, criteria); return ResponseEntity.ok(MoonshotResponse.success(SuccessType.OK, response)); } diff --git a/moonshot-api/src/main/java/org/moonshot/task/controller/TaskController.java b/moonshot-api/src/main/java/org/moonshot/task/controller/TaskController.java index 0c8bc7a7..226a033a 100644 --- a/moonshot-api/src/main/java/org/moonshot/task/controller/TaskController.java +++ b/moonshot-api/src/main/java/org/moonshot/task/controller/TaskController.java @@ -3,16 +3,20 @@ import static org.moonshot.response.SuccessType.POST_TASK_SUCCESS; import jakarta.validation.Valid; -import java.security.Principal; import lombok.RequiredArgsConstructor; -import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.model.Logging; import org.moonshot.response.MoonshotResponse; import org.moonshot.task.dto.request.TaskSingleCreateRequestDto; import org.moonshot.task.service.TaskService; +import org.moonshot.user.model.LoginUser; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor @@ -23,15 +27,15 @@ public class TaskController implements TaskApi { @PostMapping @Logging(item = "Task", action = "Post") - public ResponseEntity> createTask(final Principal principal, @RequestBody @Valid final TaskSingleCreateRequestDto request) { - taskService.createTask(request, JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity> createTask(@LoginUser Long userId, @RequestBody @Valid final TaskSingleCreateRequestDto request) { + taskService.createTask(request, userId); return ResponseEntity.status(HttpStatus.CREATED).body(MoonshotResponse.success(POST_TASK_SUCCESS)); } @DeleteMapping("/{taskId}") @Logging(item = "Task", action = "Delete") - public ResponseEntity deleteTask (final Principal principal, @PathVariable("taskId") final Long taskId) { - taskService.deleteTask(JwtTokenProvider.getUserIdFromPrincipal(principal), taskId); + public ResponseEntity deleteTask (@LoginUser Long userId, @PathVariable("taskId") final Long taskId) { + taskService.deleteTask(userId, taskId); return ResponseEntity.noContent().build(); } diff --git a/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java b/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java index 9d813b04..8f9af71e 100644 --- a/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java +++ b/moonshot-api/src/main/java/org/moonshot/user/controller/UserController.java @@ -4,10 +4,8 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import java.io.IOException; -import java.security.Principal; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.moonshot.jwt.JwtTokenProvider; import org.moonshot.jwt.TokenResponse; import org.moonshot.model.Logging; import org.moonshot.response.MoonshotResponse; @@ -16,6 +14,7 @@ import org.moonshot.user.dto.request.UserInfoRequest; import org.moonshot.user.dto.response.SocialLoginResponse; import org.moonshot.user.dto.response.UserInfoResponse; +import org.moonshot.user.model.LoginUser; import org.moonshot.user.service.UserService; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; @@ -33,6 +32,7 @@ @RequiredArgsConstructor @RequestMapping("/v1/user") public class UserController implements UserApi { + @Value("${google.client-id}") private String googleClientId; @@ -59,29 +59,29 @@ public ResponseEntity> reissue(@RequestHeader("A @PostMapping("/log-out") @Logging(item = "User", action = "Post") - public ResponseEntity> logout(final Principal principal) { - userService.logout(JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity> logout(@LoginUser Long userId) { + userService.logout(userId); return ResponseEntity.ok(MoonshotResponse.success(SuccessType.POST_LOGOUT_SUCCESS)); } @DeleteMapping("/withdrawal") @Logging(item = "User", action = "Delete") - public ResponseEntity withdrawal(final Principal principal) { - userService.withdrawal(JwtTokenProvider.getUserIdFromPrincipal(principal)); + public ResponseEntity withdrawal(@LoginUser Long userId) { + userService.withdrawal(userId); return ResponseEntity.noContent().build(); } @PatchMapping("/profile") @Logging(item = "User", action = "Patch") - public ResponseEntity modifyProfile(final Principal principal, @Valid @RequestBody final UserInfoRequest userInfoRequest) { - userService.modifyProfile(JwtTokenProvider.getUserIdFromPrincipal(principal), userInfoRequest); + public ResponseEntity modifyProfile(@LoginUser Long userId, @Valid @RequestBody final UserInfoRequest userInfoRequest) { + userService.modifyProfile(userId, userInfoRequest); return ResponseEntity.noContent().build(); } @GetMapping("/mypage") @Logging(item = "User", action = "Get") - public ResponseEntity> getMyProfile(final Principal principal) { - return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_PROFILE_SUCCESS, userService.getMyProfile(JwtTokenProvider.getUserIdFromPrincipal(principal)))); + public ResponseEntity> getMyProfile(@LoginUser Long userId) { + return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_PROFILE_SUCCESS, userService.getMyProfile(userId))); } @GetMapping("/googleLogin") @@ -98,12 +98,4 @@ public String authTest(final HttpServletRequest request, final HttpServletRespon return "SUCCESS"; } -// @GetMapping("/login/oauth2/code/kakao") -// public String kakaoSuccess(@RequestParam String code) { -// return code; -// } -// -// @GetMapping("/login/oauth2/code/google") -// public String googleSuccess(@RequestParam String code, @RequestParam String scope, @RequestParam String prompt) { return code; } - } \ No newline at end of file From ac469f3937d0af527a809e3cdb3865519acce232 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:51:33 +0900 Subject: [PATCH 5/8] =?UTF-8?q?[Fix]=20#236=20-=20Principal=EC=97=90?= =?UTF-8?q?=EC=84=9C=20@LoginUser=EB=A1=9C=20=EB=B3=80=EA=B2=BD=20?= =?UTF-8?q?=ED=9B=84=20Swagger=20=EC=9D=B8=ED=84=B0=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EC=8B=9C=EA=B7=B8=EB=8B=88=EC=B2=98=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../keyresult/controller/KeyResultApi.java | 10 +++++----- .../org/moonshot/log/controller/LogApi.java | 4 ++-- .../objective/controller/ObjectiveApi.java | 18 ++++++------------ .../org/moonshot/task/controller/TaskApi.java | 6 +++--- .../org/moonshot/user/controller/UserApi.java | 10 +++++----- 5 files changed, 21 insertions(+), 27 deletions(-) diff --git a/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultApi.java b/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultApi.java index 1c30fca0..351b8b45 100644 --- a/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultApi.java +++ b/moonshot-api/src/main/java/org/moonshot/keyresult/controller/KeyResultApi.java @@ -7,11 +7,11 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; -import java.security.Principal; import org.moonshot.keyresult.dto.request.KeyResultCreateRequestDto; import org.moonshot.keyresult.dto.request.KeyResultModifyRequestDto; import org.moonshot.keyresult.dto.response.KRDetailResponseDto; import org.moonshot.response.MoonshotResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -27,7 +27,7 @@ public interface KeyResultApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 Objective입니다\t\n존재하지 않는 KeyResult입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "KeyResult 데이터 생성") - public ResponseEntity> createKeyResult(Principal principal, @RequestBody @Valid KeyResultCreateRequestDto request); + public ResponseEntity> createKeyResult(@LoginUser Long userId, @RequestBody @Valid KeyResultCreateRequestDto request); @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "KeyResult 삭제를 성공하였습니다"), @@ -36,7 +36,7 @@ public interface KeyResultApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 KeyResult입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "KeyResult 데이터 삭제") - public ResponseEntity deleteKeyResult(Principal principal, @PathVariable("keyResultId") Long keyResultId); + public ResponseEntity deleteKeyResult(@LoginUser Long userId, @PathVariable("keyResultId") Long keyResultId); @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "KeyResult 수정 후 목표를 달성하였습니다\t\nKeyResult 수정을 성공하였습니다"), @@ -46,7 +46,7 @@ public interface KeyResultApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 KeyResult입니다\t\n존재하지 않는 Log입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "KeyResult 데이터 수정") - public ResponseEntity> modifyKeyResult(Principal principal, @RequestBody @Valid KeyResultModifyRequestDto request); + public ResponseEntity> modifyKeyResult(@LoginUser Long userId, @RequestBody @Valid KeyResultModifyRequestDto request); @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "O-KR을 생성을 성공하였습니다"), @@ -56,5 +56,5 @@ public interface KeyResultApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 유저입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "KeyResult 상세 조회 (사이드바)") - public ResponseEntity> getKRDetails(Principal principal, @PathVariable("keyResultId") Long keyResultId); + public ResponseEntity> getKRDetails(@LoginUser Long userId, @PathVariable("keyResultId") Long keyResultId); } diff --git a/moonshot-api/src/main/java/org/moonshot/log/controller/LogApi.java b/moonshot-api/src/main/java/org/moonshot/log/controller/LogApi.java index c0eca92a..ff986bd7 100644 --- a/moonshot-api/src/main/java/org/moonshot/log/controller/LogApi.java +++ b/moonshot-api/src/main/java/org/moonshot/log/controller/LogApi.java @@ -9,9 +9,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; -import java.security.Principal; import org.moonshot.log.dto.request.LogCreateRequestDto; import org.moonshot.response.MoonshotResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; @@ -26,7 +26,7 @@ public interface LogApi { content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "Log 생성") - public ResponseEntity> create(Principal principal, + public ResponseEntity> create(@LoginUser Long userId, @Parameter(in = ParameterIn.DEFAULT, name = "TaskSingleCreateRequest", description = "task 추가 요청 body") @RequestBody @Valid LogCreateRequestDto logCreateRequestDto); diff --git a/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveApi.java b/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveApi.java index 03327ff8..c24bb36b 100644 --- a/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveApi.java +++ b/moonshot-api/src/main/java/org/moonshot/objective/controller/ObjectiveApi.java @@ -1,8 +1,6 @@ package org.moonshot.objective.controller; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; @@ -10,7 +8,6 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.Nullable; import jakarta.validation.Valid; -import java.security.Principal; import org.moonshot.objective.dto.request.ModifyObjectiveRequestDto; import org.moonshot.objective.dto.request.OKRCreateRequestDto; import org.moonshot.objective.dto.response.DashboardResponseDto; @@ -18,6 +15,7 @@ import org.moonshot.objective.model.Category; import org.moonshot.objective.model.Criteria; import org.moonshot.response.MoonshotResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -33,8 +31,7 @@ interface ObjectiveApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 유저입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "O-KR 데이터 생성") - ResponseEntity> createObjective(@Parameter(in = ParameterIn.HEADER, name = "Authorization", description = "Access Token", required = true, schema = @Schema(type = "string")) final Principal principal, - @RequestBody @Valid final OKRCreateRequestDto request); + ResponseEntity> createObjective(@LoginUser Long userId, @RequestBody @Valid final OKRCreateRequestDto request); @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "O-KR 트리 삭제를 성공하였습니다"), @@ -43,8 +40,7 @@ ResponseEntity> createObjective(@Parameter(in = ParameterIn. @ApiResponse(responseCode = "404", description = "존재하지 않는 Objective입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "O-KR 데이터 삭제") - ResponseEntity> deleteObjective(@Parameter(in = ParameterIn.HEADER, name = "Authorization", description = "Access Token", required = true, schema = @Schema(type = "string")) final Principal principal, - @PathVariable("objectiveId") final Long objectiveId); + ResponseEntity> deleteObjective(@LoginUser Long userId, @PathVariable("objectiveId") final Long objectiveId); @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "Objective 수정에 성공하였습니다"), @@ -54,8 +50,7 @@ ResponseEntity> deleteObjective(@Paramete @ApiResponse(responseCode = "404", description = "존재하지 않는 Objective입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "Objective 데이터 수정") - ResponseEntity modifyObjective(@Parameter(in = ParameterIn.HEADER, name = "Authorization", description = "Access Token", required = true, schema = @Schema(type = "string")) final Principal principal, - @RequestBody final ModifyObjectiveRequestDto request); + ResponseEntity modifyObjective(@LoginUser Long userId, @RequestBody final ModifyObjectiveRequestDto request); @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "O-KR 목록 조회에 성공하였습니다"), @@ -64,8 +59,7 @@ ResponseEntity modifyObjective(@Parameter(in = ParameterIn.HEADER, name = "Au @ApiResponse(responseCode = "404", description = "존재하지 않는 Objective입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "O-KR 목록 조회") - ResponseEntity> getObjectiveInDashboard(@Parameter(in = ParameterIn.HEADER, name = "Authorization", description = "Access Token", required = true, schema = @Schema(type = "string")) final Principal principal, - @Nullable @RequestParam("objectiveId") final Long objectiveId); + ResponseEntity> getObjectiveInDashboard(@LoginUser Long userId, @Nullable @RequestParam("objectiveId") final Long objectiveId); @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "히스토리 조회에 성공하였습니다."), @@ -73,7 +67,7 @@ ResponseEntity> getObjectiveInDashboard(@ @ApiResponse(responseCode = "403", description = "해당 자원에 접근 권한이 없습니다.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))), }) @Operation(summary = "히스토리 목록 조회") - ResponseEntity> getObjectiveHistory(final Principal principal, @RequestParam(required = false) final Integer year, + ResponseEntity> getObjectiveHistory(@LoginUser Long userId, @RequestParam(required = false) final Integer year, @RequestParam(required = false) final Category category, @RequestParam(required = false) final Criteria criteria); diff --git a/moonshot-api/src/main/java/org/moonshot/task/controller/TaskApi.java b/moonshot-api/src/main/java/org/moonshot/task/controller/TaskApi.java index b207fa96..2b75ca57 100644 --- a/moonshot-api/src/main/java/org/moonshot/task/controller/TaskApi.java +++ b/moonshot-api/src/main/java/org/moonshot/task/controller/TaskApi.java @@ -9,9 +9,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; -import java.security.Principal; import org.moonshot.response.MoonshotResponse; import org.moonshot.task.dto.request.TaskSingleCreateRequestDto; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -25,7 +25,7 @@ public interface TaskApi { content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "Task 추가") - public ResponseEntity> createTask(Principal principal, + public ResponseEntity> createTask(@LoginUser Long userId, @Parameter(in = ParameterIn.DEFAULT, name = "TaskSingleCreateRequest", description = "task 추가 요청 body") @RequestBody @Valid TaskSingleCreateRequestDto request); @@ -36,7 +36,7 @@ public ResponseEntity> createTask(Principal principal, content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "Task 삭제") - public ResponseEntity deleteTask(Principal principal, @PathVariable("taskId") Long taskId); + public ResponseEntity deleteTask(@LoginUser Long userId, @PathVariable("taskId") Long taskId); } diff --git a/moonshot-api/src/main/java/org/moonshot/user/controller/UserApi.java b/moonshot-api/src/main/java/org/moonshot/user/controller/UserApi.java index 7129829a..7ac724e6 100644 --- a/moonshot-api/src/main/java/org/moonshot/user/controller/UserApi.java +++ b/moonshot-api/src/main/java/org/moonshot/user/controller/UserApi.java @@ -12,13 +12,13 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import java.io.IOException; -import java.security.Principal; import org.moonshot.jwt.TokenResponse; import org.moonshot.response.MoonshotResponse; import org.moonshot.user.dto.request.SocialLoginRequest; import org.moonshot.user.dto.request.UserInfoRequest; import org.moonshot.user.dto.response.SocialLoginResponse; import org.moonshot.user.dto.response.UserInfoResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -38,7 +38,7 @@ public ResponseEntity> login(@Parameter(in @ApiResponse(responseCode = "200", description = "로그아웃에 성공하였습니다.") @Operation(summary = "로그아웃") - public ResponseEntity> logout(Principal principal); + public ResponseEntity> logout(@LoginUser Long userId); @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "로그아웃에 성공하였습니다."), @@ -46,7 +46,7 @@ public ResponseEntity> login(@Parameter(in content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "로그아웃") - public ResponseEntity withdrawal(Principal principal); + public ResponseEntity withdrawal(@LoginUser Long userId); @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "사용자 프로필 업데이트에 성공하였습니다."), @@ -54,7 +54,7 @@ public ResponseEntity> login(@Parameter(in content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "프로필 수정") - public ResponseEntity modifyProfile(Principal principal, + public ResponseEntity modifyProfile(@LoginUser Long userId, @Parameter(in = ParameterIn.DEFAULT, name = "UserInfoRequest", description = "유저 정보 요청 body") @Valid @RequestBody UserInfoRequest userInfoRequest); @@ -64,7 +64,7 @@ public ResponseEntity modifyProfile(Principal principal, content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "프로필 조회") - public ResponseEntity> getMyProfile(Principal principal); + public ResponseEntity> getMyProfile(@LoginUser Long userId); @ApiResponse(responseCode = "200", description = "구글 로그인에 성공하였습니다.") @Operation(summary = "구글 로그인") From 7ab385b9f53ac824dd887e19e488b266bb8b49fc Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:58:20 +0900 Subject: [PATCH 6/8] =?UTF-8?q?[Fix]=20#236=20-=20IndexController=20@Login?= =?UTF-8?q?User=EB=A1=9C=20=EB=B3=80=EA=B2=BD=20=ED=9B=84=20Swagger=20?= =?UTF-8?q?=EC=9D=B8=ED=84=B0=ED=8E=98=EC=9D=B4=EC=8A=A4=EB=8F=84=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/moonshot/objective/controller/IndexApi.java | 4 ++-- .../org/moonshot/objective/controller/IndexController.java | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexApi.java b/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexApi.java index d2d0f9ce..3727ae08 100644 --- a/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexApi.java +++ b/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexApi.java @@ -7,9 +7,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; -import java.security.Principal; import org.moonshot.objective.dto.request.ModifyIndexRequestDto; import org.moonshot.response.MoonshotResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; @@ -24,6 +24,6 @@ public interface IndexApi { @ApiResponse(responseCode = "404", description = "존재하지 않는 Objective입니다\t\n존재하지 않는 KeyResult입니다\t\n존재하지 않는 Task입니다", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MoonshotResponse.class))) }) @Operation(summary = "Objective, KeyResult, Task Index 변경") - public ResponseEntity> modifyIdx(Principal principal, @RequestBody @Valid ModifyIndexRequestDto request); + public ResponseEntity> modifyIdx(@LoginUser Long userId, @RequestBody @Valid ModifyIndexRequestDto request); } diff --git a/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexController.java b/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexController.java index 06e18448..6b810685 100644 --- a/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexController.java +++ b/moonshot-api/src/main/java/org/moonshot/objective/controller/IndexController.java @@ -8,6 +8,7 @@ import org.moonshot.objective.model.IndexService; import org.moonshot.objective.service.IndexTargetProvider; import org.moonshot.response.MoonshotResponse; +import org.moonshot.user.model.LoginUser; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -22,9 +23,9 @@ public class IndexController implements IndexApi { private final IndexTargetProvider indexTargetProvider; @PatchMapping - public ResponseEntity> modifyIdx(final Principal principal, @RequestBody @Valid final ModifyIndexRequestDto request) { + public ResponseEntity> modifyIdx(@LoginUser Long userId, @RequestBody @Valid final ModifyIndexRequestDto request) { IndexService indexService = indexTargetProvider.getIndexService(request.target()); - indexService.modifyIdx(request, JwtTokenProvider.getUserIdFromPrincipal(principal)); + indexService.modifyIdx(request, userId); return ResponseEntity.noContent().build(); } From 7a39c96a8da0d3ef1a4073d06ed0ebd23b5be4c7 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 22:58:40 +0900 Subject: [PATCH 7/8] =?UTF-8?q?[Del]=20#236=20-=20JwtTokenProvider?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EC=9D=B4=EC=A0=9C=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20method=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/org/moonshot/jwt/JwtTokenProvider.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java b/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java index df5bdeb8..f95ad796 100644 --- a/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java +++ b/moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java @@ -10,16 +10,13 @@ import io.jsonwebtoken.security.SignatureException; import jakarta.annotation.PostConstruct; import java.nio.charset.StandardCharsets; -import java.security.Principal; import java.util.Base64; import java.util.Date; -import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.crypto.SecretKey; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.moonshot.constants.JWTConstants; -import org.moonshot.exception.global.auth.InvalidAuthException; import org.moonshot.exception.global.auth.InvalidRefreshTokenException; import org.moonshot.exception.global.common.MoonshotException; import org.moonshot.response.ErrorType; @@ -155,13 +152,6 @@ public Long getUserFromJwt(String token) { return Long.parseLong(claims.get(JWTConstants.USER_ID).toString()); } - public static Long getUserIdFromPrincipal(Principal principal) { - if (Objects.isNull(principal)) { - throw new InvalidAuthException(); - } - return Long.valueOf(principal.getName()); - } - public Authentication getAuthentication(Long userId) { UserPrincipal userDetails = (UserPrincipal) userPrincipalDetailsService.loadUserByUsername(String.valueOf(userId)); return new UserAuthentication(userDetails); From d7d1d04dff838a9ac174603c77fc0a08c9a45d74 Mon Sep 17 00:00:00 2001 From: its-sky Date: Sun, 3 Mar 2024 23:04:07 +0900 Subject: [PATCH 8/8] =?UTF-8?q?[Fix]=20#236=20-=20TaskService=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20API=EC=97=90=EC=84=9C=20KeyResult=20=EC=A1=B0?= =?UTF-8?q?=ED=9A=8C=20=EC=8B=9C=20=EC=98=88=EC=99=B8=EB=A5=BC=20=EB=8D=98?= =?UTF-8?q?=EC=A7=80=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/moonshot/task/service/TaskService.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/moonshot-api/src/main/java/org/moonshot/task/service/TaskService.java b/moonshot-api/src/main/java/org/moonshot/task/service/TaskService.java index 6fa3c143..5791b0f3 100644 --- a/moonshot-api/src/main/java/org/moonshot/task/service/TaskService.java +++ b/moonshot-api/src/main/java/org/moonshot/task/service/TaskService.java @@ -1,7 +1,15 @@ package org.moonshot.task.service; +import static org.moonshot.task.service.validator.TaskValidator.validateActiveTaskSizeExceeded; +import static org.moonshot.task.service.validator.TaskValidator.validateIndex; +import static org.moonshot.task.service.validator.TaskValidator.validateIndexUnderMaximum; +import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization; +import static org.moonshot.validator.IndexValidator.isIndexIncreased; +import static org.moonshot.validator.IndexValidator.isSameIndex; + import java.util.List; import lombok.RequiredArgsConstructor; +import org.moonshot.exception.keyresult.KeyResultNotFoundException; import org.moonshot.exception.task.TaskNotFoundException; import org.moonshot.keyresult.model.KeyResult; import org.moonshot.keyresult.repository.KeyResultRepository; @@ -14,11 +22,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import static org.moonshot.task.service.validator.TaskValidator.*; -import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization; -import static org.moonshot.validator.IndexValidator.isIndexIncreased; -import static org.moonshot.validator.IndexValidator.isSameIndex; - @Service @Transactional @RequiredArgsConstructor @@ -28,7 +31,7 @@ public class TaskService implements IndexService { private final TaskRepository taskRepository; public void createTask(final TaskSingleCreateRequestDto request, final Long userId) { KeyResult keyResult = keyResultRepository.findKeyResultAndObjective(request.keyResultId()) - .orElseThrow(); + .orElseThrow(KeyResultNotFoundException::new); validateUserAuthorization(keyResult.getObjective().getUser().getId(), userId); List taskList = taskRepository.findAllByKeyResultOrderByIdx(keyResult);