12 Commits

Author SHA1 Message Date
abel
54dd332b70 게시글 작성/수정시 금칙어 체크 로직 추가 2020-06-24 01:17:48 +09:00
abel
8effadb882 게시글 작성/수정시 금칙어 체크 로직 추가 2020-06-23 22:40:48 +09:00
kimyonghwa
9e30c2ca80 bugfix
- update ftl path
- delete duplicate security settings
2019-11-14 11:28:56 +09:00
DaddyProgrammer
e4f7f2da78 Update README.md 2019-11-13 15:09:48 +09:00
kimyonghwa
2ffb5d307e change settings
- token expire time : 1hour -> 1day
- log level : info -> debug
2019-09-19 12:12:28 +09:00
codej99
820cb20d27 Merge pull request #21 from codej99/feature/board
add api
2019-09-17 17:35:44 +09:00
codej99
37b4b9cd73 Merge branch 'master' into feature/board 2019-09-17 17:35:37 +09:00
kimyonghwa
4173fc1225 add api
- create board
2019-09-17 17:34:13 +09:00
kimyonghwa
200168c601 Merge branch 'feature/board' 2019-09-05 23:14:52 +09:00
kimyonghwa
a51dce74ad post 정렬 추가 2019-09-05 23:13:20 +09:00
kimyonghwa
d4e74d92c1 Serializable 추가 2019-09-04 00:55:07 +09:00
codej99
8cecd7edcf Merge pull request #20 from codej99/cache-data-redis
Cache data redis
2019-08-08 02:09:31 +09:00
16 changed files with 150 additions and 12 deletions

View File

@@ -3,7 +3,7 @@
### 0. 개요
- SpringBoot2 framework 기반에서 RESTful api 서비스를 Step by Step으로 만들어 나가는 프로젝트
- daddyprogrammer.org에서 연재 및 소스 Github 등록
- https://daddyprogrammer.org/post/series/springboot2%EB%A1%9C-rest-api-%EB%A7%8C%EB%93%A4%EA%B8%B0/
- https://daddyprogrammer.org/post/series/springboot2-make-rest-api/
### 1. 개발환경
- Java 8~11

View File

@@ -77,6 +77,12 @@ public class ExceptionAdvice {
return responseService.getFailResult(Integer.valueOf(getMessage("resourceNotExist.code")), getMessage("resourceNotExist.msg"));
}
@ExceptionHandler(CForbiddenWordException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResult forbiddenWordException(HttpServletRequest request, CForbiddenWordException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("forbiddenWord.code")), getMessage("forbiddenWord.msg", new Object[]{e.getMessage()}));
}
// code정보에 해당하는 메시지를 조회합니다.
private String getMessage(String code) {
return getMessage(code, null);

View File

@@ -0,0 +1,16 @@
package com.rest.api.advice.exception;
public class CForbiddenWordException extends RuntimeException {
public CForbiddenWordException(String msg, Throwable t) {
super(msg, t);
}
public CForbiddenWordException(String msg) {
super(msg);
}
public CForbiddenWordException() {
super();
}
}

View File

@@ -0,0 +1,15 @@
package com.rest.api.annotation;
import com.rest.api.model.board.ParamsPost;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ForbiddenWordCheck {
String param() default "paramsPost.content";
Class<?> checkClazz() default ParamsPost.class;
}

View File

@@ -0,0 +1,74 @@
package com.rest.api.annotation.aspect;
import com.rest.api.advice.exception.CForbiddenWordException;
import com.rest.api.annotation.ForbiddenWordCheck;
import io.micrometer.core.instrument.util.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@Aspect
@Component
public class ForbiddenWordCheckAspect {
// 어노테이션이 설정된 메서드의 메인 프로세스가 시작되기전(Before)에 금칙어 체크 로직이 적용된다.
@Before(value = "@annotation(forbiddenWordCheck)")
public void forbiddenWordCheck(JoinPoint pjp, ForbiddenWordCheck forbiddenWordCheck) throws Throwable {
// 금칙어를 체크할 메서드의 파라미터가 객체인지(객체.필드명) 일반 String인지에 따라 구분하여 처리한다.
String[] param = forbiddenWordCheck.param().split("\\.");
String paramName;
String fieldName = "";
if (param.length == 2) {
paramName = param[0];
fieldName = param[1];
} else {
paramName = forbiddenWordCheck.param();
}
// 메서드의 파라미터 이름으로 메서드의 몇번째 파라미터인지 구한다.
Integer parameterIdx = getParameterIdx(pjp, paramName);
if (parameterIdx == -1)
throw new IllegalArgumentException();
String checkWord;
// 객체내의 필드값에서 금칙어 체크 문장을 얻어내야 할 경우
if (StringUtils.isNotEmpty(fieldName)) {
Class<?> clazz = forbiddenWordCheck.checkClazz();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
checkWord = (String) field.get(pjp.getArgs()[parameterIdx]);
// 금칙어 체크 문장이 String형의 파라미터로 넘어오는 경우
} else {
checkWord = (String) pjp.getArgs()[parameterIdx];
}
// 체크할 문장에 금칙어가 포함되어 있는지 확인
checkForbiddenWord(checkWord);
}
// 메서드의 파라미터 이름으로 몇번째에 파라미터가 위치하는지 구함
private Integer getParameterIdx(JoinPoint joinPoint, String paramName) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String[] parameterNames = methodSignature.getParameterNames();
for (int i = 0; i < parameterNames.length; i++) {
String parameterName = parameterNames[i];
if (paramName.equals(parameterName)) {
return i;
}
}
return -1;
}
// 입력된 문장에 금칙어가 포함되어 있으면 Exception을 발생시킨다.
private void checkForbiddenWord(String word) {
List<String> forbiddenWords = Arrays.asList("개새끼", "쌍년", "씨발");
Optional<String> forbiddenWord = forbiddenWords.stream().filter(word::contains).findFirst();
if (forbiddenWord.isPresent())
throw new CForbiddenWordException(forbiddenWord.get());
}
}

View File

@@ -9,8 +9,6 @@ import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

View File

@@ -25,7 +25,7 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
@Value("${spring.jwt.secret}")
private String secretKey;
private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효
private long tokenValidMilisecond = 1000L * 60 * 60 * 24; // 24시간만 토큰 유효
private final UserDetailsService userDetailsService;

View File

@@ -32,7 +32,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.and()
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록 GET요청 리소스는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록 GET요청 리소스는 누구나 접근가능
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())

View File

@@ -28,6 +28,15 @@ public class BoardController {
private final BoardService boardService;
private final ResponseService responseService;
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시판 생성", notes = "신규 게시판을 생성한다.")
@PostMapping(value = "/{boardName}")
public SingleResult<Board> createBoard(@PathVariable String boardName) {
return responseService.getSingleResult(boardService.insertBoard(boardName));
}
@ApiOperation(value = "게시판 정보 조회", notes = "게시판 정보를 조회한다.")
@GetMapping(value = "/{boardName}")
public SingleResult<Board> boardInfo(@PathVariable String boardName) {
@@ -44,7 +53,7 @@ public class BoardController {
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시글 작성", notes = "게시글을 작성한다.")
@PostMapping(value = "/{boardName}")
@PostMapping(value = "/{boardName}/post")
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String uid = authentication.getName();

View File

@@ -1,15 +1,19 @@
package com.rest.api.entity.board;
import com.rest.api.entity.common.CommonDateEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Builder
@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Board extends CommonDateEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -7,12 +7,13 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.LocalDateTime;
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class CommonDateEntity {
public abstract class CommonDateEntity implements Serializable {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate

View File

@@ -7,5 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PostJpaRepo extends JpaRepository<Post, Long> {
List<Post> findByBoard(Board board);
List<Post> findByBoardOrderByPostIdDesc(Board board);
}

View File

@@ -1,8 +1,10 @@
package com.rest.api.service.board;
import com.rest.api.advice.exception.CForbiddenWordException;
import com.rest.api.advice.exception.CNotOwnerException;
import com.rest.api.advice.exception.CResourceNotExistException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.annotation.ForbiddenWordCheck;
import com.rest.api.common.CacheKey;
import com.rest.api.entity.User;
import com.rest.api.entity.board.Board;
@@ -20,6 +22,7 @@ import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@@ -34,6 +37,10 @@ public class BoardService {
private final UserJpaRepo userJpaRepo;
private final CacheSevice cacheSevice;
public Board insertBoard(String boardName) {
return boardJpaRepo.save(Board.builder().name(boardName).build());
}
// 게시판 이름으로 게시판을 조회. 없을경우 CResourceNotExistException 처리
@Cacheable(value = CacheKey.BOARD, key = "#boardName", unless = "#result == null")
public Board findBoard(String boardName) {
@@ -43,7 +50,7 @@ public class BoardService {
// 게시판 이름으로 게시글 리스트 조회.
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
public List<Post> findPosts(String boardName) {
return postJpaRepo.findByBoard(findBoard(boardName));
return postJpaRepo.findByBoardOrderByPostIdDesc(findBoard(boardName));
}
// 게시글ID로 게시글 단건 조회. 없을경우 CResourceNotExistException 처리
@@ -54,6 +61,7 @@ public class BoardService {
// 게시글을 등록합니다. 게시글의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
@ForbiddenWordCheck
public Post writePost(String uid, String boardName, ParamsPost paramsPost) {
Board board = findBoard(boardName);
Post post = new Post(userJpaRepo.findByUid(uid).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
@@ -62,6 +70,7 @@ public class BoardService {
// 게시글을 수정합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
//@CachePut(value = CacheKey.POST, key = "#postId") 갱신된 정보만 캐시할경우에만 사용!
@ForbiddenWordCheck
public Post updatePost(long postId, String uid, ParamsPost paramsPost) {
Post post = getPost(postId);
User user = post.getUser();

View File

@@ -1,6 +1,6 @@
logging:
level:
root: info
root: debug
com.rest.api: debug
spring:

View File

@@ -24,4 +24,7 @@ notOwner:
msg: "You are not the owner of this resource."
resourceNotExist:
code: "-1007"
msg: "This resource does not exist."
msg: "This resource does not exist."
forbiddenWord:
code: "-1008"
msg: "forbidden words ({0}) are included in the input."

View File

@@ -24,4 +24,7 @@ notOwner:
msg: "해당 자원의 소유자가 아닙니다."
resourceNotExist:
code: "-1007"
msg: "요청한 자원이 존재 하지 않습니다."
msg: "요청한 자원이 존재 하지 않습니다."
forbiddenWord:
code: "-1008"
msg: "입력한 내용에 금칙어({0})가 포함되어 있습니다."