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

[Feat] jwt login (#68) #69

Merged
merged 16 commits into from
Nov 26, 2023
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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ dependencies {
implementation 'com.amazonaws:aws-java-sdk-core:1.12.429'
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.429'
implementation 'software.amazon.awssdk:s3:2.16.83'

// jwt 추가
implementation 'io.jsonwebtoken:jjwt:0.9.1'
}

ext {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@
import yonseigolf.server.board.service.BoardImageService;
import yonseigolf.server.board.service.BoardService;
import yonseigolf.server.board.service.ReplyService;
import yonseigolf.server.user.dto.response.SessionUser;
import yonseigolf.server.user.entity.User;
import yonseigolf.server.util.CustomResponse;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
Expand Down Expand Up @@ -49,10 +46,9 @@ public ResponseEntity<CustomResponse<Page<SingleBoardResponse>>> findAll(Pageabl
}

@PostMapping("/boards")
public ResponseEntity<CustomResponse<Void>> createBoard(@RequestBody CreateBoardRequest createBoardRequest, HttpSession session) {
public ResponseEntity<CustomResponse<Void>> createBoard(@RequestBody CreateBoardRequest createBoardRequest, @RequestAttribute Long userId) {

SessionUser user = getSessionUser(session);
boardService.postBoard(createBoardRequest, user.getId());
boardService.postBoard(createBoardRequest, userId);

return ResponseEntity
.ok()
Expand All @@ -70,56 +66,42 @@ public ResponseEntity<CustomResponse<BoardDetailResponse>> findBoardDetail(@Path
}

@PatchMapping("/boards/{boardId}")
public ResponseEntity<CustomResponse<Void>> updateBoard(@PathVariable Long boardId, @RequestBody UpdateBoardRequest updateBoardRequest, HttpSession session) {
public ResponseEntity<CustomResponse<Void>> updateBoard(@PathVariable Long boardId, @RequestBody UpdateBoardRequest updateBoardRequest, @RequestAttribute Long userId) {

SessionUser user = getSessionUser(session);
boardService.updateBoard(boardId, updateBoardRequest, user.getId());
boardService.updateBoard(boardId, updateBoardRequest, userId);

return ResponseEntity
.ok()
.body(CustomResponse.successResponse("게시글 수정 성공"));
}

@DeleteMapping("/boards/{boardId}")
public ResponseEntity<CustomResponse<Void>> deleteBoard(@PathVariable Long boardId, HttpSession session) {
public ResponseEntity<CustomResponse<Void>> deleteBoard(@PathVariable Long boardId, @RequestAttribute Long userId) {

SessionUser user = getSessionUser(session);
boardService.deleteBoard(boardId, user.getId());
boardService.deleteBoard(boardId, userId);

return ResponseEntity
.ok()
.body(CustomResponse.successResponse("게시글 삭제 성공"));
}

@PostMapping("/boards/{boardId}/replies")
public ResponseEntity<CustomResponse<Void>> createReply(@PathVariable Long boardId, @RequestBody PostReplyRequest replyRequest, HttpSession session) {
public ResponseEntity<CustomResponse<Void>> createReply(@PathVariable Long boardId, @RequestBody PostReplyRequest replyRequest, @RequestAttribute Long userId) {

SessionUser user = getSessionUser(session);
replyService.postReply(user.getId(), boardId, replyRequest);
replyService.postReply(userId, boardId, replyRequest);

return ResponseEntity
.ok()
.body(CustomResponse.successResponse("댓글 생성 성공"));
}

@DeleteMapping("/replies/{replyId}")
public ResponseEntity<CustomResponse<Void>> deleteReply(@PathVariable Long replyId, HttpSession session) {
public ResponseEntity<CustomResponse<Void>> deleteReply(@PathVariable Long replyId, @RequestAttribute Long userId) {

SessionUser user = getSessionUser(session);

replyService.deleteReply(replyId, user.getId());
replyService.deleteReply(replyId, userId);

return ResponseEntity
.ok()
.body(CustomResponse.successResponse("댓글 삭제 성공"));
}

private SessionUser getSessionUser(HttpSession session) {
SessionUser user = (SessionUser) session.getAttribute("user");

if (user == null) {
throw new IllegalArgumentException("세션에 유저 정보가 없습니다.");
}
return user;
}
}
68 changes: 0 additions & 68 deletions src/main/java/yonseigolf/server/config/CorsConfig.java

This file was deleted.

62 changes: 62 additions & 0 deletions src/main/java/yonseigolf/server/config/DefaultInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package yonseigolf.server.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yonseigolf.server.user.exception.AccessTokenExpiredException;
import yonseigolf.server.user.exception.NoAuthorizationException;
import yonseigolf.server.user.exception.NotBearerTypeException;
import yonseigolf.server.user.exception.TokenManipulatedException;
import yonseigolf.server.user.service.JwtService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class DefaultInterceptor implements HandlerInterceptor {

private final JwtService jwtUtil;

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

if(request.getMethod().equals("OPTIONS")) {
return true;
}

if (request.getRequestURI().startsWith("/boards") && request.getMethod().equals("GET")) {
return true;
}

if (request.getRequestURI().startsWith("/boards") && request.getMethod().equals("GET")) {
return true;
}

if (request.getHeader("Authorization") == null) {
log.info("Authorization header is null");
throw new NoAuthorizationException("Authorization header is null");
}

if (request.getHeader("Authorization").split(" ").length != 2) {
log.info("Authorization header is not Bearer type");
throw new NotBearerTypeException("Authorization header is not Bearer type");
}

String token = request.getHeader("Authorization").split(" ")[1];
if (!request.getHeader("Authorization").split(" ")[0].equals("Bearer")) {
throw new NotBearerTypeException("Authorization header is not Bearer type");
}

if (!jwtUtil.validateTokenIsExpired(token)) {
throw new AccessTokenExpiredException("Token is expired");
}

if (!jwtUtil.validateTokenIsManipulated(token)) {
throw new TokenManipulatedException("Token is manipulated");
}

return true;
}
}
37 changes: 37 additions & 0 deletions src/main/java/yonseigolf/server/config/LoginInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package yonseigolf.server.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yonseigolf.server.user.dto.response.LoggedInUser;
import yonseigolf.server.user.service.JwtService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

private final JwtService jwtUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

System.out.println(request.getRequestURI());

if(request.getMethod().equals("OPTIONS")) {
return true;
}
if (request.getRequestURI().startsWith("/boards") && request.getMethod().equals("GET")) {
return true;
}
String token = request.getHeader("Authorization").split(" ")[1];
LoggedInUser loggedInUser = jwtUtil.extractedUserFromToken(token, LoggedInUser.class);
request.setAttribute("userId", loggedInUser.getId());

return true;
}
}
34 changes: 34 additions & 0 deletions src/main/java/yonseigolf/server/config/OauthInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package yonseigolf.server.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yonseigolf.server.user.dto.response.LoggedInUser;
import yonseigolf.server.user.service.JwtService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class OauthInterceptor implements HandlerInterceptor {
private final JwtService jwtUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

System.out.println(request.getRequestURI());

if(request.getMethod().equals("OPTIONS")) {
return true;
}

String token = request.getHeader("Authorization").split(" ")[1];
LoggedInUser loggedInUser = jwtUtil.extractedUserFromToken(token, LoggedInUser.class);
request.setAttribute("kakaoId", loggedInUser.getId());

return true;
}
}
51 changes: 51 additions & 0 deletions src/main/java/yonseigolf/server/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package yonseigolf.server.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private final DefaultInterceptor defaultInterceptor;
private final OauthInterceptor oauthInterceptor;
private final LoginInterceptor loginInterceptor;


@Override
public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/**") // 모든 경로에 대해
.allowedOrigins(
"http://localhost:3000",
"https://www.yonseigolf.site",
"https://yonseigolf.site"
)
.allowedMethods("GET", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS")
.allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
.allowCredentials(true);
}


@Override
public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(defaultInterceptor)
.addPathPatterns("/users/signIn")
.addPathPatterns("/boards/**")
.addPathPatterns("/replies/**")
.addPathPatterns("/users/logout");

registry.addInterceptor(oauthInterceptor)
.addPathPatterns("/users/signIn");

registry.addInterceptor(loginInterceptor)
.addPathPatterns("/boards/**")
.addPathPatterns("/users/logout")
.addPathPatterns("/replies/**")
.excludePathPatterns("/oauth/kakao");
}
}
Loading