Skip to content

Commit

Permalink
Merge pull request #181 from urinaner/feature/180
Browse files Browse the repository at this point in the history
[BE] AOP 적용
  • Loading branch information
2Jin1031 authored Nov 29, 2024
2 parents 0444519 + 4bd23ed commit 61a76d5
Show file tree
Hide file tree
Showing 32 changed files with 299 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.example.backend.admin.exception.AdminExceptionType.ALREADY_EXIST_LOGIN_ID;
import static org.example.backend.admin.exception.AdminExceptionType.INVALID_ACCESS_TOKEN;
import static org.example.backend.user.exception.UserExceptionType.NOT_FOUND_USER;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -10,6 +11,7 @@
import org.example.backend.admin.domain.entity.Admin;
import org.example.backend.admin.exception.AdminException;
import org.example.backend.admin.repository.AdminRepository;
import org.example.backend.user.exception.UserException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -20,7 +22,7 @@
@Transactional(readOnly = true)
public class AdminService {

private final AdminRepository userRepository;
private final AdminRepository adminRepository;
private final PasswordEncoder bCryptPasswordEncoder;
private static final String BEARER_TYPE = "Bearer";

Expand All @@ -42,11 +44,11 @@ public void joinProcess(SignInReqDto joinDTO) {
.role("ROLE_ADMIN")
.build();

userRepository.save(admin);
adminRepository.save(admin);
}

private boolean validateExistLoginId(String loginId) {
Boolean isExist = userRepository.existsByLoginId(loginId);
Boolean isExist = adminRepository.existsByLoginId(loginId);

if (isExist) {
return true;
Expand All @@ -62,4 +64,9 @@ public void signOut(AccessTokenReq accessTokenReq) {
throw new AdminException(INVALID_ACCESS_TOKEN);
}
}

public Admin getAdminById(Long id) {
return adminRepository.findById(id)
.orElseThrow(() -> new AdminException(INVALID_ACCESS_TOKEN));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,26 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.board.domain.dto.BoardReqDto;
import org.example.backend.board.domain.dto.BoardResDto;
import org.example.backend.board.domain.entity.Category;
import org.example.backend.board.service.BoardService;
import org.example.backend.common.exception.dto.ResponseDto;
import org.example.backend.common.dto.ResponseDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "게시판", description = "게시판 API")
Expand All @@ -40,16 +41,23 @@ public ResponseEntity<Long> createBoard(@RequestPart(value = "boardReqDto") Boar

@Operation(summary = "모든 게시판 조회 API", description = "모든 게시판의 리스트 반환")
@GetMapping
public ResponseDto<List<BoardResDto>> getAllBoards(Pageable pageable) {
Page<BoardResDto> boardList = boardService.getAllBoards(pageable);
public ResponseDto<List<BoardResDto>> getAllBoards(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort,
@RequestParam(defaultValue = "ASC") String sortDirection) {

Page<BoardResDto> boardList = boardService.getAllBoards(page, size, sort, sortDirection);
return ResponseDto.ok(boardList.getNumber(), boardList.getTotalPages(), boardList.getContent());
}
@Operation(summary = "카테고리별 게시판 조회 API", description = "카테고리별 게시판 리스트 반환")
@GetMapping("/category/{category}")
public ResponseDto<List<BoardResDto>> getBoardsByCategory(
@PathVariable("category") Category category,
Pageable pageable) {
Page<BoardResDto> boardList = boardService.getBoardsByCategory(category, pageable);
public ResponseDto<List<BoardResDto>> getBoardsByCategory(@PathVariable("category") Category category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort,
@RequestParam(defaultValue = "ASC") String sortDirection) {

Page<BoardResDto> boardList = boardService.getBoardsByCategory(category, page, size, sort, sortDirection);
return ResponseDto.ok(boardList.getNumber(), boardList.getTotalPages(), boardList.getContent());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.example.backend.board.domain.dto.BoardReqDto;
import org.example.backend.global.config.BaseEntity;
import org.example.backend.global.config.StringListConverter;
import org.example.backend.common.domain.BaseEntity;
import org.example.backend.global.util.StringListConverter;

@Entity
@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
import org.example.backend.board.exception.BoardException;
import org.example.backend.board.exception.BoardExceptionType;
import org.example.backend.board.repository.BoardRepository;
import org.example.backend.global.config.S3Uploader;
import org.example.backend.global.config.aws.S3Uploader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
Expand Down Expand Up @@ -52,12 +54,16 @@ public BoardResDto getBoard(Long boardId) {
return BoardResDto.of(board);
}

public Page<BoardResDto> getAllBoards(Pageable pageable) {
public Page<BoardResDto> getAllBoards(int pageNo, int pageSize, String sortBy, String sortDirection) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
return boardRepository.findAll(pageable)
.map(BoardResDto::of);
}

public Page<BoardResDto> getBoardsByCategory(Category category, Pageable pageable) {
public Page<BoardResDto> getBoardsByCategory(Category category, int pageNo, int pageSize, String sortBy, String sortDirection) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
return boardRepository.findAllByCategory(category, pageable)
.map(BoardResDto::of);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.common.domain;

import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.common.exception.dto;
package org.example.backend.common.dto;

import lombok.*;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.example.backend.common.exception.auth;

import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.BaseException;
import org.example.backend.common.exception.BaseExceptionType;

@RequiredArgsConstructor
public class AuthException extends BaseException {
private final AuthExceptionType exceptionType;

@Override
public BaseExceptionType exceptionType() {
return exceptionType;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.example.backend.common.exception.auth;

import static org.springframework.http.HttpStatus.BAD_REQUEST;

import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.BaseExceptionType;
import org.springframework.http.HttpStatus;

@RequiredArgsConstructor
public enum AuthExceptionType implements BaseExceptionType {
PLEASE_LOGIN(BAD_REQUEST ,"로그인 해주세요");
private final HttpStatus httpStatus;
private final String errorMessage;

@Override
public HttpStatus httpStatus() {
return httpStatus;
}
@Override
public String errorMessage() {
return errorMessage;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.example.backend.department.domain.dto.Department.DepartmentReqDto;
import org.example.backend.global.config.BaseEntity;
import org.example.backend.common.domain.BaseEntity;

@Entity
@Getter
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.example.backend.global.aop;

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 AuthAdmin {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package org.example.backend.global.aop;

import static org.example.backend.common.exception.auth.AuthExceptionType.PLEASE_LOGIN;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.example.backend.admin.service.AdminService;
import org.example.backend.common.exception.auth.AuthException;
import org.example.backend.jwt.JWTUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.context.request.NativeWebRequest;


@Component
@RequiredArgsConstructor
public class AuthAdminResolver implements HandlerMethodArgumentResolver {

private final JWTUtil jwtUtil;
private final HttpServletRequest request;
private final AdminService adminService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(AuthUser.class);
}

@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) throws Exception {

String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new AuthException(PLEASE_LOGIN);
}

String token = authorizationHeader.substring(7);
if (!jwtUtil.validateToken(token)) {
throw new AuthException(PLEASE_LOGIN);
}

String loginId = jwtUtil.extractClaims(token).get("loginId", String.class);
return adminService.getAdminById(Long.valueOf(loginId));
}
}
11 changes: 11 additions & 0 deletions backend/src/main/java/org/example/backend/global/aop/AuthUser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.example.backend.global.aop;

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 AuthUser {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package org.example.backend.global.aop;

import static org.example.backend.common.exception.auth.AuthExceptionType.PLEASE_LOGIN;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.auth.AuthException;
import org.example.backend.jwt.JWTUtil;
import org.example.backend.user.service.UserService;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.context.request.NativeWebRequest;


@Component
@RequiredArgsConstructor
public class AuthUserResolver implements HandlerMethodArgumentResolver {

private final JWTUtil jwtUtil;
private final HttpServletRequest request;
private final UserService userService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(AuthUser.class);
}

@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) throws Exception {

String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new AuthException(PLEASE_LOGIN);
}

String token = authorizationHeader.substring(7);
if (!jwtUtil.validateToken(token)) {
throw new AuthException(PLEASE_LOGIN);
}

String loginId = jwtUtil.extractClaims(token).get("loginId", String.class);
return userService.getUserById(Long.valueOf(loginId));
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.auth;


import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package org.example.backend.global.config;
package org.example.backend.global.config.auth;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.global.config.auth.CustomAuthenticationFailureHandler;
import org.example.backend.jwt.JWTFilter;
import org.example.backend.jwt.JWTUtil;
import org.example.backend.jwt.LoginFilter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.aws;


import com.amazonaws.auth.AWSStaticCredentialsProvider;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.aws;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.jpa;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.sj;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.swagger;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.backend.global.config;
package org.example.backend.global.config.web;

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
Expand Down
Loading

0 comments on commit 61a76d5

Please sign in to comment.