Compare commits
83 Commits
feature/me
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc5e033ee7 | ||
|
|
d51ed655cc | ||
|
|
a6a65b7250 | ||
|
|
9ee074ab57 | ||
|
|
54dd332b70 | ||
|
|
8effadb882 | ||
|
|
9e30c2ca80 | ||
|
|
e4f7f2da78 | ||
|
|
2ffb5d307e | ||
|
|
820cb20d27 | ||
|
|
37b4b9cd73 | ||
|
|
4173fc1225 | ||
|
|
200168c601 | ||
|
|
a51dce74ad | ||
|
|
d4e74d92c1 | ||
|
|
8cecd7edcf | ||
|
|
f7901cbd18 | ||
|
|
945b44fdc7 | ||
|
|
e729ff1504 | ||
|
|
bdd09eeaa9 | ||
|
|
458de9d927 | ||
|
|
a03a263adf | ||
|
|
c6110eb806 | ||
|
|
0bf89cc08b | ||
|
|
002ac18e4a | ||
|
|
c25984207b | ||
|
|
2a0a9721ed | ||
|
|
69f3053371 | ||
|
|
189e741ded | ||
|
|
2e5e6be283 | ||
|
|
0bcbc81775 | ||
|
|
951bd95faa | ||
|
|
b23ca762bf | ||
|
|
695908e2c7 | ||
|
|
dac4f282e3 | ||
|
|
5f1bd9fdcc | ||
|
|
8ad0baad33 | ||
|
|
b784ba6bdb | ||
|
|
c2a2ba9b46 | ||
|
|
b8b1f4c65f | ||
|
|
4fb92209e6 | ||
|
|
3f3ff162b1 | ||
|
|
19d23f1bdd | ||
|
|
49a244c970 | ||
|
|
1eb3fe7486 | ||
|
|
e390958e9a | ||
|
|
a63177676b | ||
|
|
b3da392b47 | ||
|
|
24192c2b72 | ||
|
|
46cacec275 | ||
|
|
2826699804 | ||
|
|
5b11d0e1b3 | ||
|
|
8d1765a280 | ||
|
|
cdc10997fc | ||
|
|
930ecb504f | ||
|
|
3b75ea18c0 | ||
|
|
0226f99edc | ||
|
|
ec7931d807 | ||
|
|
3acd2b66e0 | ||
|
|
79dea54b73 | ||
|
|
c2f1ea67e6 | ||
|
|
9fcd390cee | ||
|
|
03edf8a653 | ||
|
|
0b296131ff | ||
|
|
62c14bb3bc | ||
|
|
9da74a4d13 | ||
|
|
d2a6c9bc81 | ||
|
|
26b9321855 | ||
|
|
16ae0132d2 | ||
|
|
758c3a0799 | ||
|
|
4cb008c876 | ||
|
|
e4d5cf3a77 | ||
|
|
ad6ab44345 | ||
|
|
02a4b3b7ea | ||
|
|
e163695ef6 | ||
|
|
b5157aa381 | ||
|
|
ee20205692 | ||
|
|
e663724567 | ||
|
|
73804c1189 | ||
|
|
12e462f022 | ||
|
|
41e93d885c | ||
|
|
8a58b45279 | ||
|
|
a7e3feb3bf |
132
README.md
Normal file
132
README.md
Normal file
@@ -0,0 +1,132 @@
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
# Spring Rest Api 만들기 프로젝트
|
||||
|
||||
### 0. 개요
|
||||
- SpringBoot2 framework 기반에서 RESTful api 서비스를 Step by Step으로 만들어 나가는 프로젝트
|
||||
- daddyprogrammer.org에서 연재 및 소스 Github 등록
|
||||
- https://daddyprogrammer.org/post/series/springboot2-make-rest-api/
|
||||
|
||||
### 1. 개발환경
|
||||
- Java 8~11
|
||||
- SpringBoot 2.x
|
||||
- SpringSecurity 5.x
|
||||
- JPA, H2
|
||||
- Intellij Community
|
||||
|
||||
### 2. 프로젝트 실행
|
||||
- H2 database 설치
|
||||
- https://www.h2database.com/html/download.html
|
||||
- intellij lombok 플러그인 설치
|
||||
- Preferences -> Plugins -> Browse repositories... -> search lombok -> Install "IntelliJ Lombok plugin"
|
||||
- Enable annotation processing
|
||||
- Preferences - Annotation Procesors - Enable annotation processing 체크
|
||||
- build.gradle에 lombok 추가(Git을 받은경우 이미 추가되어있음)
|
||||
- compileOnly 'org.projectlombok:lombok:1.16.16'
|
||||
- 실행
|
||||
- Run -> SpringBootApiApplication
|
||||
- Swagger
|
||||
- http://localhost:8080/swagger-ui.html
|
||||
|
||||
### 3. DDL
|
||||
create table user (
|
||||
msrl bigint not null auto_increment,
|
||||
name varchar(100) not null,
|
||||
password varchar(100),
|
||||
provider varchar(100),
|
||||
uid varchar(50) not null,
|
||||
primary key (msrl)
|
||||
) engine=InnoDB;
|
||||
|
||||
create table user_roles (
|
||||
user_msrl bigint not null,
|
||||
roles varchar(255)
|
||||
) engine=InnoDB;
|
||||
|
||||
|
||||
alter table user
|
||||
add constraint UK_a7hlm8sj8kmijx6ucp7wfyt31 unique (uid);
|
||||
|
||||
alter table user_roles
|
||||
add constraint FKel3d4qj41g0sy1mtp4sh055g7
|
||||
foreign key (user_msrl)
|
||||
references user (msrl);
|
||||
|
||||
### 4. 목차
|
||||
- SpringBoot2로 Rest api 만들기(1) – Intellij Community에서 프로젝트생성
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/19/spring-boot1-start-intellij/
|
||||
- SpringBoot2로 Rest api 만들기(2) – HelloWorld
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/41/spring-boot2-helloworld/
|
||||
- SpringBoot2로 Rest api 만들기(3) – H2 Database 연동
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/152/spring-boot2-h2-database-intergrate/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/h2
|
||||
- SpringBoot2로 Rest api 만들기(4) – Swagger API 문서 자동화
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/313/swagger-api-doc/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/swagger
|
||||
- SpringBoot2로 Rest api 만들기(5) – API 인터페이스 및 결과 데이터 구조 설계
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/404/spring-boot2-5-design-api-interface-and-data-structure/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/api-structure
|
||||
- SpringBoot2로 Rest api 만들기(6) – ControllerAdvice를 이용한 Exception처리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/446/spring-boot2-5-exception-handling/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/controller-advice
|
||||
- SpringBoot2로 Rest api 만들기(7) – MessageSource를 이용한 Exception 처리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/499/springboot2-message-exception-handling-with-controlleradvice/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/messagesource
|
||||
- SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 인증 및 권한부여
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/security
|
||||
- SpringBoot2로 Rest api 만들기(9) – Unit Test
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/938/springboot2-restapi-unit-test/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/junit-test
|
||||
- SpringBoot2로 Rest api 만들기(10) – Social Login kakao
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/1012/springboot2-rest-api-social-login-kakao/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/social-kakao
|
||||
- SpringBoot2로 Rest api 만들기(11) – profile을 이용한 환경별 설정 분리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/2421/springboot2-seperate-environment-by-profile/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/seperate-profile
|
||||
- SpringBoot2로 Rest api 만들기(12) – Deploy & Nginx 연동 & 무중단 배포 하기
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/2445/springboot2-blue-green-deploy-nginx/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/gracefullyshutdown
|
||||
- SpringBoot2로 Rest api 만들기(13) – Jenkins 배포(Deploy) + Git Tag Rollback
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/2697/springboot2-jenkins-deploy-gittag-rollback/
|
||||
- SpringBoot2로 Rest api 만들기(14) – 간단한 JPA 게시판(board) 만들기
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/2695/springboot2-simple-jpa-board/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/board
|
||||
- SpringBoot2로 Rest api 만들기(15) – Redis로 api 결과 캐싱(Caching)처리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/3870/spring-rest-api-redis-caching/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/cache-data-redis
|
||||
- SpringBoot2로 Rest api 만들기(16) – AOP와 Custom Annotation을 이용한 금칙어(Forbidden Word) 처리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/11356/springboot2-forbidden-word-by-aop-annotation/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/block_fobidden_word
|
||||
@@ -1,6 +1,7 @@
|
||||
plugins {
|
||||
id 'org.springframework.boot' version '2.1.4.RELEASE'
|
||||
id 'java'
|
||||
id "org.sonarqube" version "2.7"
|
||||
}
|
||||
|
||||
apply plugin: 'io.spring.dependency-management'
|
||||
@@ -23,12 +24,20 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||
//embedded-redis
|
||||
implementation 'it.ozimov:embedded-redis:0.7.2'
|
||||
implementation 'io.jsonwebtoken:jjwt:0.9.1'
|
||||
implementation 'io.springfox:springfox-swagger2:2.6.1'
|
||||
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
|
||||
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
|
||||
implementation 'com.google.code.gson:gson'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
runtimeOnly 'com.h2database:h2'
|
||||
runtimeOnly 'mysql:mysql-connector-java'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
testImplementation 'org.springframework.security:spring-security-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
66
deploy.sh
Normal file
66
deploy.sh
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/bin/bash
|
||||
PROFILE=$1
|
||||
PROJECT=SpringRestApi
|
||||
PROJECT_HOME=/home/happydaddy/${PROJECT}
|
||||
JAR_PATH=${PROJECT_HOME}/build/libs/api-0.0.1-SNAPSHOT.jar
|
||||
SVR_LIST=server_${PROFILE}.list
|
||||
SERVERS=`cat $SVR_LIST`
|
||||
DEPLOY_PATH=/home/ec2-user/app
|
||||
AWS_ID=ec2-user
|
||||
DATE=`date +%Y-%m-%d-%H-%M-%S`
|
||||
JAVA_OPTS="-XX:MaxMetaspaceSize=128m -XX:+UseG1GC -Xss1024k -Xms128m -Xmx128m -Dfile.encoding=UTF-8"
|
||||
PEM=AwsFreetierKeyPair.pem
|
||||
PORT=8083
|
||||
|
||||
echo Deploy Start
|
||||
for server in $SERVERS; do
|
||||
echo Target server - $server
|
||||
# Target Server에 배포 디렉터리 생성
|
||||
ssh -i $PEM $AWS_ID@$server "mkdir -p $DEPLOY_PATH/dist"
|
||||
# Target Server에 jar 이동
|
||||
echo 'Executable Jar Copying...'
|
||||
scp -i $PEM $JAR_PATH $AWS_ID@$server:~/app/dist/$PROJECT-$DATE.jar
|
||||
# 이동한 jar파일의 바로가기(SymbolicLink)생성
|
||||
ssh -i $PEM $AWS_ID@$server "ln -Tfs $DEPLOY_PATH/dist/$PROJECT-$DATE.jar $DEPLOY_PATH/$PROJECT"
|
||||
# 현재 실행중인 서버 PID 조회
|
||||
runPid=$(ssh -i $PEM $AWS_ID@$server pgrep -f $PROJECT)
|
||||
if [ -z $runPid ]; then
|
||||
echo "No servers are running"
|
||||
fi
|
||||
# 현재 실행중인 서버의 포트를 조회. 추가로 실행할 서버의 포트 선정
|
||||
runPortCount=$(ssh -i $PEM $AWS_ID@$server ps -ef | grep $PROJECT | grep -v grep | grep $PORT | wc -l)
|
||||
if [ $runPortCount -gt 0 ]; then
|
||||
PORT=8084
|
||||
fi
|
||||
echo "Server $PORT Starting..."
|
||||
# 새로운 서버 실행
|
||||
ssh -i $PEM $AWS_ID@$server "nohup java -jar -Dserver.port=$PORT -Dspring.profiles.active=$PROFILE $JAVA_OPTS $DEPLOY_PATH/$PROJECT < /dev/null > std.out 2> std.err &"
|
||||
# 새롭게 실행한 서버의 health check
|
||||
echo "Health check $PORT"
|
||||
for retry in {1..10}
|
||||
do
|
||||
health=$(ssh -i $PEM $AWS_ID@$server curl -s http://localhost:$PORT/actuator/health)
|
||||
checkCount=$(echo $health | grep 'UP' | wc -l)
|
||||
if [ $checkCount -ge 1 ]; then
|
||||
echo "Server $PORT Started Normaly"
|
||||
# 기존 서버 Stop / Nginx 포트 변경 후 리스타트
|
||||
if [ $runPid -gt 0 ]; then
|
||||
echo "Server $runPid Stop"
|
||||
ssh -i $PEM $AWS_ID@$server "kill -TERM $runPid"
|
||||
sleep 5
|
||||
echo "Nginx Port Change"
|
||||
ssh -i $PEM $AWS_ID@$server "echo 'set \$service_addr http://127.0.0.1:$PORT;' | sudo tee /etc/nginx/conf.d/service_addr.inc"
|
||||
echo "Nginx reload"
|
||||
ssh -i $PEM $AWS_ID@$server "sudo service nginx reload"
|
||||
fi
|
||||
break;
|
||||
else
|
||||
echo "Check - false"
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
if [ $retry -eq 10 ]; then
|
||||
echo "Deploy Fail"
|
||||
fi
|
||||
done
|
||||
echo Deploy End
|
||||
@@ -1,11 +1,42 @@
|
||||
package com.rest.api;
|
||||
|
||||
import com.rest.api.config.GracefulShutdown;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@EnableJpaAuditing
|
||||
@SpringBootApplication
|
||||
public class SpringRestApiApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringRestApiApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate getRestTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GracefulShutdown gracefulShutdown() {
|
||||
return new GracefulShutdown();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
|
||||
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
|
||||
factory.addConnectorCustomizers(gracefulShutdown);
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package com.rest.api.advice;
|
||||
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.advice.exception.*;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
@@ -25,20 +26,68 @@ public class ExceptionAdvice {
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
|
||||
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg") + "(" + e.getMessage() + ")");
|
||||
}
|
||||
|
||||
@ExceptionHandler(CUserNotFoundException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
protected CommonResult userNotFoundException(HttpServletRequest request, CUserNotFoundException e) {
|
||||
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
|
||||
protected CommonResult userNotFound(HttpServletRequest request, CUserNotFoundException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CEmailSigninFailedException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
protected CommonResult emailSigninFailed(HttpServletRequest request, CEmailSigninFailedException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("emailSigninFailed.code")), getMessage("emailSigninFailed.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CAuthenticationEntryPointException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public CommonResult authenticationEntryPointException(HttpServletRequest request, CAuthenticationEntryPointException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("entryPointException.code")), getMessage("entryPointException.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CCommunicationException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public CommonResult communicationException(HttpServletRequest request, CCommunicationException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("communicationError.code")), getMessage("communicationError.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CUserExistException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public CommonResult communicationException(HttpServletRequest request, CUserExistException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("existingUser.code")), getMessage("existingUser.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CNotOwnerException.class)
|
||||
@ResponseStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION)
|
||||
public CommonResult notOwnerException(HttpServletRequest request, CNotOwnerException e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("notOwner.code")), getMessage("notOwner.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CResourceNotExistException.class)
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public CommonResult resourceNotExistException(HttpServletRequest request, CResourceNotExistException e) {
|
||||
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);
|
||||
}
|
||||
|
||||
// code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
|
||||
private String getMessage(String code, Object[] args) {
|
||||
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CAuthenticationEntryPointException extends RuntimeException {
|
||||
public CAuthenticationEntryPointException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CAuthenticationEntryPointException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CAuthenticationEntryPointException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CCommunicationException extends RuntimeException {
|
||||
public CCommunicationException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CCommunicationException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CCommunicationException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CEmailSigninFailedException extends RuntimeException {
|
||||
public CEmailSigninFailedException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CEmailSigninFailedException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CEmailSigninFailedException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CNotOwnerException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 2241549550934267615L;
|
||||
|
||||
public CNotOwnerException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CNotOwnerException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CNotOwnerException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CResourceNotExistException extends RuntimeException {
|
||||
public CResourceNotExistException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CResourceNotExistException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CResourceNotExistException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rest.api.advice.exception;
|
||||
|
||||
public class CUserExistException extends RuntimeException {
|
||||
public CUserExistException(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public CUserExistException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CUserExistException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
14
src/main/java/com/rest/api/common/CacheKey.java
Normal file
14
src/main/java/com/rest/api/common/CacheKey.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.rest.api.common;
|
||||
|
||||
public class CacheKey {
|
||||
|
||||
public static final int DEFAULT_EXPIRE_SEC = 60; // 1 minutes
|
||||
public static final String USER = "user";
|
||||
public static final int USER_EXPIRE_SEC = 60 * 5; // 5 minutes
|
||||
public static final String BOARD = "board";
|
||||
public static final int BOARD_EXPIRE_SEC = 60 * 10; // 10 minutes
|
||||
public static final String POST = "post";
|
||||
public static final String POSTS = "posts";
|
||||
public static final int POST_EXPIRE_SEC = 60 * 5; // 5 minutes
|
||||
|
||||
}
|
||||
35
src/main/java/com/rest/api/config/EmbeddedRedisConfig.java
Normal file
35
src/main/java/com/rest/api/config/EmbeddedRedisConfig.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import redis.embedded.RedisServer;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
/**
|
||||
* 로컬 환경일경우 내장 레디스가 실행된다.
|
||||
*/
|
||||
@Profile("local")
|
||||
@Configuration
|
||||
public class EmbeddedRedisConfig {
|
||||
|
||||
@Value("${spring.redis.port}")
|
||||
private int redisPort;
|
||||
|
||||
private RedisServer redisServer;
|
||||
|
||||
@PostConstruct
|
||||
public void redisServer() {
|
||||
redisServer = new RedisServer(redisPort);
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stopRedis() {
|
||||
if (redisServer != null) {
|
||||
redisServer.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
50
src/main/java/com/rest/api/config/GracefulShutdown.java
Normal file
50
src/main/java/com/rest/api/config/GracefulShutdown.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.catalina.connector.Connector;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
public class GracefulShutdown implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {
|
||||
|
||||
private static final int TIMEOUT = 30;
|
||||
|
||||
private volatile Connector connector;
|
||||
|
||||
@Override
|
||||
public void customize(Connector connector) {
|
||||
this.connector = connector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ContextClosedEvent event) {
|
||||
this.connector.pause();
|
||||
Executor executor = this.connector.getProtocolHandler().getExecutor();
|
||||
if (executor instanceof ThreadPoolExecutor) {
|
||||
try {
|
||||
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
|
||||
threadPoolExecutor.shutdown();
|
||||
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
|
||||
log.warn("Tomcat thread pool did not shut down gracefully within "
|
||||
+ TIMEOUT + " seconds. Proceeding with forceful shutdown");
|
||||
|
||||
threadPoolExecutor.shutdownNow();
|
||||
|
||||
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
|
||||
log.error("Tomcat thread pool did not terminate");
|
||||
}
|
||||
} else {
|
||||
log.info("Tomcat thread pool has been gracefully shutdown");
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rakugakibox.util.YamlResourceBundle;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.MessageSource;
|
||||
@@ -14,7 +13,6 @@ import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.MissingResourceException;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
@Configuration
|
||||
@@ -56,7 +54,7 @@ public class MessageConfiguration implements WebMvcConfigurer {
|
||||
// locale 정보에 따라 다른 yml 파일을 읽도록 처리
|
||||
private static class YamlMessageSource extends ResourceBundleMessageSource {
|
||||
@Override
|
||||
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
|
||||
protected ResourceBundle doGetBundle(String basename, Locale locale) {
|
||||
return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
|
||||
}
|
||||
}
|
||||
|
||||
47
src/main/java/com/rest/api/config/RedisConfig.java
Normal file
47
src/main/java/com/rest/api/config/RedisConfig.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import com.rest.api.common.CacheKey;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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.serializer.RedisSerializationContext;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@EnableCaching
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Bean(name = "cacheManager")
|
||||
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
|
||||
|
||||
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.disableCachingNullValues()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.DEFAULT_EXPIRE_SEC))
|
||||
.computePrefixWith(CacheKeyPrefix.simple())
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
|
||||
|
||||
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
|
||||
// 캐시 default 유효시간 설정
|
||||
cacheConfigurations.put(CacheKey.USER, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.USER_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.BOARD, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.BOARD_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.POST, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.POSTS, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
|
||||
|
||||
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration)
|
||||
.withInitialCacheConfigurations(cacheConfigurations).build();
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ public class SwaggerConfiguration {
|
||||
public Docket swaggerApi() {
|
||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(swaggerInfo()).select()
|
||||
.apis(RequestHandlerSelectors.basePackage("com.rest.api.controller"))
|
||||
.paths(PathSelectors.any())
|
||||
.paths(PathSelectors.ant("/v1/**"))
|
||||
.build()
|
||||
.useDefaultResponseMessages(false); // 기본으로 세팅되는 200,401,403,404 메시지를 표시 하지 않음
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException {
|
||||
response.sendRedirect("/exception/accessdenied");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
|
||||
response.sendRedirect("/exception/entrypoint");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
|
||||
public class JwtAuthenticationFilter extends GenericFilterBean {
|
||||
|
||||
private JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
// Jwt Provier 주입
|
||||
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
}
|
||||
|
||||
// Request로 들어오는 Jwt Token의 유효성을 검증(jwtTokenProvider.validateToken)하는 filter를 filterChain에 등록합니다.
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
|
||||
String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);
|
||||
if (token != null && jwtTokenProvider.validateToken(token)) {
|
||||
Authentication auth = jwtTokenProvider.getAuthentication(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
|
||||
|
||||
@Value("${spring.jwt.secret}")
|
||||
private String secretKey;
|
||||
|
||||
private long tokenValidMilisecond = 1000L * 60 * 60 * 24; // 24시간만 토큰 유효
|
||||
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
@PostConstruct
|
||||
protected void init() {
|
||||
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
|
||||
}
|
||||
|
||||
// Jwt 토큰 생성
|
||||
public String createToken(String userPk, List<String> roles) {
|
||||
Claims claims = Jwts.claims().setSubject(userPk);
|
||||
claims.put("roles", roles);
|
||||
Date now = new Date();
|
||||
return Jwts.builder()
|
||||
.setClaims(claims) // 데이터
|
||||
.setIssuedAt(now) // 토큰 발행일자
|
||||
.setExpiration(new Date(now.getTime() + tokenValidMilisecond)) // set Expire Time
|
||||
.signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘, secret값 세팅
|
||||
.compact();
|
||||
}
|
||||
|
||||
// Jwt 토큰으로 인증 정보를 조회
|
||||
public Authentication getAuthentication(String token) {
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
// Jwt 토큰에서 회원 구별 정보 추출
|
||||
public String getUserPk(String token) {
|
||||
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
|
||||
}
|
||||
|
||||
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"
|
||||
public String resolveToken(HttpServletRequest req) {
|
||||
return req.getHeader("X-AUTH-TOKEN");
|
||||
}
|
||||
|
||||
// Jwt 토큰의 유효성 + 만료일자 확인
|
||||
public boolean validateToken(String jwtToken) {
|
||||
try {
|
||||
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
|
||||
return !claims.getBody().getExpiration().before(new Date());
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Configuration
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
|
||||
.csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
|
||||
.and()
|
||||
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
|
||||
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
|
||||
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록된 GET요청 리소스는 누구나 접근가능
|
||||
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
||||
.and()
|
||||
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
|
||||
.and()
|
||||
.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
|
||||
.and()
|
||||
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
|
||||
|
||||
}
|
||||
|
||||
@Override // ignore swagger security config
|
||||
public void configure(WebSecurity web) {
|
||||
web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
|
||||
"/swagger-ui.html", "/webjars/**", "/swagger/**");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,17 @@ package com.rest.api.controller;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Slf4j
|
||||
@Controller
|
||||
public class HelloController {
|
||||
|
||||
private static final String HELLO = "helloworld-nice to meet you";
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class Hello {
|
||||
@@ -18,14 +22,16 @@ public class HelloController {
|
||||
@GetMapping(value = "/helloworld/string")
|
||||
@ResponseBody
|
||||
public String helloworldString() {
|
||||
return "helloworld";
|
||||
log.debug("Helloworld");
|
||||
log.info("Helloworld");
|
||||
return HELLO;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/helloworld/json")
|
||||
@ResponseBody
|
||||
public Hello helloworldJson() {
|
||||
Hello hello = new Hello();
|
||||
hello.message = "helloworld";
|
||||
hello.message = HELLO;
|
||||
return hello;
|
||||
}
|
||||
|
||||
@@ -33,4 +39,11 @@ public class HelloController {
|
||||
public String helloworld() {
|
||||
return "helloworld";
|
||||
}
|
||||
|
||||
@GetMapping("/helloworld/long-process")
|
||||
@ResponseBody
|
||||
public String pause() throws InterruptedException {
|
||||
Thread.sleep(10000);
|
||||
return "Process finished";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.rest.api.controller.common;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.rest.api.service.social.KakaoService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Controller
|
||||
@RequestMapping("/social/login")
|
||||
public class SocialController {
|
||||
|
||||
private final Environment env;
|
||||
private final RestTemplate restTemplate;
|
||||
private final Gson gson;
|
||||
private final KakaoService kakaoService;
|
||||
|
||||
@Value("${spring.url.base}")
|
||||
private String baseUrl;
|
||||
|
||||
@Value("${spring.social.kakao.client_id}")
|
||||
private String kakaoClientId;
|
||||
|
||||
@Value("${spring.social.kakao.redirect}")
|
||||
private String kakaoRedirect;
|
||||
|
||||
/**
|
||||
* 카카오 로그인 페이지
|
||||
*/
|
||||
@GetMapping
|
||||
public ModelAndView socialLogin(ModelAndView mav) {
|
||||
|
||||
StringBuilder loginUrl = new StringBuilder()
|
||||
.append(env.getProperty("spring.social.kakao.url.login"))
|
||||
.append("?client_id=").append(kakaoClientId)
|
||||
.append("&response_type=code")
|
||||
.append("&redirect_uri=").append(baseUrl).append(kakaoRedirect);
|
||||
|
||||
mav.addObject("loginUrl", loginUrl);
|
||||
mav.setViewName("social/login");
|
||||
return mav;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카카오 인증 완료 후 리다이렉트 화면
|
||||
*/
|
||||
@GetMapping(value = "/kakao")
|
||||
public ModelAndView redirectKakao(ModelAndView mav, @RequestParam String code) {
|
||||
mav.addObject("authInfo", kakaoService.getKakaoTokenInfo(code));
|
||||
mav.setViewName("social/redirectKakao");
|
||||
return mav;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.rest.api.controller.exception;
|
||||
|
||||
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping(value = "/exception")
|
||||
public class ExceptionController {
|
||||
|
||||
@GetMapping(value = "/entrypoint")
|
||||
public CommonResult entrypointException() {
|
||||
throw new CAuthenticationEntryPointException();
|
||||
}
|
||||
|
||||
@GetMapping(value = "/accessdenied")
|
||||
public CommonResult accessdeniedException() {
|
||||
throw new AccessDeniedException("");
|
||||
}
|
||||
}
|
||||
95
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
95
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
@@ -0,0 +1,95 @@
|
||||
package com.rest.api.controller.v1;
|
||||
|
||||
import com.rest.api.advice.exception.CEmailSigninFailedException;
|
||||
import com.rest.api.advice.exception.CUserExistException;
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.config.security.JwtTokenProvider;
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.model.response.SingleResult;
|
||||
import com.rest.api.model.social.KakaoProfile;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import com.rest.api.service.social.KakaoService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
@Api(tags = {"1. Sign"})
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping(value = "/v1")
|
||||
public class SignController {
|
||||
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final ResponseService responseService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final KakaoService kakaoService;
|
||||
|
||||
@ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
|
||||
@PostMapping(value = "/signin")
|
||||
public SingleResult<String> signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||
@ApiParam(value = "비밀번호", required = true) @RequestParam String password) {
|
||||
|
||||
User user = userJpaRepo.findByUid(id).orElseThrow(CEmailSigninFailedException::new);
|
||||
if (!passwordEncoder.matches(password, user.getPassword()))
|
||||
throw new CEmailSigninFailedException();
|
||||
|
||||
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "소셜 로그인", notes = "소셜 회원 로그인을 한다.")
|
||||
@PostMapping(value = "/signin/{provider}")
|
||||
public SingleResult<String> signinByProvider(
|
||||
@ApiParam(value = "서비스 제공자 provider", required = true, defaultValue = "kakao") @PathVariable String provider,
|
||||
@ApiParam(value = "소셜 access_token", required = true) @RequestParam String accessToken) {
|
||||
|
||||
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
|
||||
User user = userJpaRepo.findByUidAndProvider(String.valueOf(profile.getId()), provider).orElseThrow(CUserNotFoundException::new);
|
||||
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "가입", notes = "회원가입을 한다.")
|
||||
@PostMapping(value = "/signup")
|
||||
public CommonResult signup(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||
@ApiParam(value = "비밀번호", required = true) @RequestParam String password,
|
||||
@ApiParam(value = "이름", required = true) @RequestParam String name) {
|
||||
|
||||
userJpaRepo.save(User.builder()
|
||||
.uid(id)
|
||||
.password(passwordEncoder.encode(password))
|
||||
.name(name)
|
||||
.roles(Collections.singletonList("ROLE_USER"))
|
||||
.build());
|
||||
return responseService.getSuccessResult();
|
||||
}
|
||||
|
||||
@ApiOperation(value = "소셜 계정 가입", notes = "소셜 계정 회원가입을 한다.")
|
||||
@PostMapping(value = "/signup/{provider}")
|
||||
public CommonResult signupProvider(@ApiParam(value = "서비스 제공자 provider", required = true, defaultValue = "kakao") @PathVariable String provider,
|
||||
@ApiParam(value = "소셜 access_token", required = true) @RequestParam String accessToken,
|
||||
@ApiParam(value = "이름", required = true) @RequestParam String name) {
|
||||
|
||||
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
|
||||
Optional<User> user = userJpaRepo.findByUidAndProvider(String.valueOf(profile.getId()), provider);
|
||||
if (user.isPresent())
|
||||
throw new CUserExistException();
|
||||
|
||||
User inUser = User.builder()
|
||||
.uid(String.valueOf(profile.getId()))
|
||||
.provider(provider)
|
||||
.name(name)
|
||||
.roles(Collections.singletonList("ROLE_USER"))
|
||||
.build();
|
||||
|
||||
userJpaRepo.save(inUser);
|
||||
return responseService.getSuccessResult();
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,13 @@ import com.rest.api.model.response.ListResult;
|
||||
import com.rest.api.model.response.SingleResult;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Api(tags = {"1. User"})
|
||||
@Api(tags = {"2. User"})
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping(value = "/v1")
|
||||
@@ -22,6 +22,9 @@ public class UserController {
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
private final ResponseService responseService; // 결과를 처리할 Service
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
|
||||
@GetMapping(value = "/users")
|
||||
public ListResult<User> findAllUser() {
|
||||
@@ -29,40 +32,38 @@ public class UserController {
|
||||
return responseService.getListResult(userJpaRepo.findAll());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
|
||||
@GetMapping(value = "/user/{msrl}")
|
||||
public SingleResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @PathVariable long msrl,
|
||||
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
|
||||
// 결과데이터가 단일건인경우 getBasicResult를 이용해서 결과를 출력한다.
|
||||
return responseService.getSingleResult(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "회원 입력", notes = "회원을 입력한다")
|
||||
@PostMapping(value = "/user")
|
||||
public SingleResult<User> save(@ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
|
||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
||||
User user = User.builder()
|
||||
.uid(uid)
|
||||
.name(name)
|
||||
.build();
|
||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
|
||||
@GetMapping(value = "/user")
|
||||
public SingleResult<User> findUser() {
|
||||
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String id = authentication.getName();
|
||||
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
|
||||
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
|
||||
@PutMapping(value = "/user")
|
||||
public SingleResult<User> modify(
|
||||
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
|
||||
@ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
|
||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
||||
User user = User.builder()
|
||||
.msrl(msrl)
|
||||
.uid(uid)
|
||||
.name(name)
|
||||
.build();
|
||||
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String id = authentication.getName();
|
||||
User user = userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new);
|
||||
user.setName(name);
|
||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "회원 삭제", notes = "회원번호(msrl)로 회원정보를 삭제한다")
|
||||
@DeleteMapping(value = "/user/{msrl}")
|
||||
public CommonResult delete(
|
||||
@ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.rest.api.controller.v1.board;
|
||||
|
||||
import com.rest.api.entity.board.Board;
|
||||
import com.rest.api.entity.board.Post;
|
||||
import com.rest.api.model.board.ParamsPost;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.model.response.ListResult;
|
||||
import com.rest.api.model.response.SingleResult;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import com.rest.api.service.board.BoardService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Api(tags = {"3. Board"})
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping(value = "/v1/board")
|
||||
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) {
|
||||
return responseService.getSingleResult(boardService.findBoard(boardName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "게시글 리스트", notes = "게시글 리스트를 조회한다.")
|
||||
@GetMapping(value = "/{boardName}/posts")
|
||||
public ListResult<Post> posts(@PathVariable String boardName) {
|
||||
return responseService.getListResult(boardService.findPosts(boardName));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "게시글 작성", notes = "게시글을 작성한다.")
|
||||
@PostMapping(value = "/{boardName}/post")
|
||||
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String uid = authentication.getName();
|
||||
return responseService.getSingleResult(boardService.writePost(uid, boardName, post));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "게시글 상세", notes = "게시글 상세정보를 조회한다.")
|
||||
@GetMapping(value = "/post/{postId}")
|
||||
public SingleResult<Post> post(@PathVariable long postId) {
|
||||
return responseService.getSingleResult(boardService.getPost(postId));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "게시글 수정", notes = "게시판의 글을 수정한다.")
|
||||
@PutMapping(value = "/post/{postId}")
|
||||
public SingleResult<Post> post(@PathVariable long postId, @Valid @ModelAttribute ParamsPost post) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String uid = authentication.getName();
|
||||
return responseService.getSingleResult(boardService.updatePost(postId, uid, post));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "게시글 삭제", notes = "게시글을 삭제한다.")
|
||||
@DeleteMapping(value = "/post/{postId}")
|
||||
public CommonResult deletePost(@PathVariable long postId) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String uid = authentication.getName();
|
||||
boardService.deletePost(postId, uid);
|
||||
return responseService.getSuccessResult();
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,79 @@
|
||||
package com.rest.api.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.rest.api.entity.common.CommonDateEntity;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.Proxy;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Builder // builder를 사용할수 있게 합니다.
|
||||
@Entity // jpa entity임을 알립니다.
|
||||
@Getter // user 필드값의 getter를 자동으로 생성합니다.
|
||||
@Setter
|
||||
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
|
||||
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
||||
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
||||
public class User {
|
||||
@Id // primaryKey임을 알립니다.
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) // Post Entity에서 User와의 관계를 Json으로 변환시 오류 방지를 위한 코드
|
||||
@Proxy(lazy = false)
|
||||
public class User extends CommonDateEntity implements UserDetails {
|
||||
@Id // pk
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
// pk생성전략을 DB에 위임한다는 의미입니다. mysql로 보면 pk 필드를 auto_increment로 설정해 놓은 경우로 보면 됩니다.
|
||||
private long msrl;
|
||||
@Column(nullable = false, unique = true, length = 30) // uid column을 명시합니다. 필수이고 유니크한 필드이며 길이는 30입니다.
|
||||
private Long msrl;
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String uid;
|
||||
@Column(nullable = false, length = 100) // name column을 명시합니다. 필수이고 길이는 100입니다.
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Column(length = 100)
|
||||
private String password;
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
@Column(length = 100)
|
||||
private String provider;
|
||||
|
||||
@ElementCollection(fetch = FetchType.EAGER)
|
||||
@Builder.Default
|
||||
private List<String> roles = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return this.uid;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
23
src/main/java/com/rest/api/entity/board/Board.java
Normal file
23
src/main/java/com/rest/api/entity/board/Board.java
Normal file
@@ -0,0 +1,23 @@
|
||||
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)
|
||||
private Long boardId;
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
}
|
||||
59
src/main/java/com/rest/api/entity/board/Post.java
Normal file
59
src/main/java/com/rest/api/entity/board/Post.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package com.rest.api.entity.board;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.entity.common.CommonDateEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.Proxy;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Post extends CommonDateEntity implements Serializable {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long postId;
|
||||
@Column(nullable = false, length = 50)
|
||||
private String author;
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
@Column(length = 500)
|
||||
private String content;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "board_id")
|
||||
private Board board; // 게시글 - 게시판의 관계 - N:1
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "msrl")
|
||||
private User user; // 게시글 - 회원의 관계 - N:1
|
||||
|
||||
// Join 테이블이 Json결과에 표시되지 않도록 처리.
|
||||
@JsonIgnore
|
||||
public Board getBoard() {
|
||||
return board;
|
||||
}
|
||||
|
||||
// 생성자
|
||||
public Post(User user, Board board, String author, String title, String content) {
|
||||
this.user = user;
|
||||
this.board = board;
|
||||
this.author = author;
|
||||
this.title = title;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
// 수정시 데이터 처리
|
||||
public Post setUpdate(String author, String title, String content) {
|
||||
this.author = author;
|
||||
this.title = title;
|
||||
this.content = content;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.rest.api.entity.common;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
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 implements Serializable {
|
||||
@CreatedDate
|
||||
private LocalDateTime createdAt;
|
||||
@LastModifiedDate
|
||||
private LocalDateTime modifiedAt;
|
||||
}
|
||||
26
src/main/java/com/rest/api/model/board/ParamsPost.java
Normal file
26
src/main/java/com/rest/api/model/board/ParamsPost.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.rest.api.model.board;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class ParamsPost {
|
||||
@NotEmpty
|
||||
@Size(min = 2, max = 50)
|
||||
@ApiModelProperty(value = "작성자명", required = true)
|
||||
private String author;
|
||||
@NotEmpty
|
||||
@Size(min = 2, max = 100)
|
||||
@ApiModelProperty(value = "제목", required = true)
|
||||
private String title;
|
||||
@Size(min = 2, max = 500)
|
||||
@ApiModelProperty(value = "내용", required = true)
|
||||
private String content;
|
||||
}
|
||||
22
src/main/java/com/rest/api/model/social/KakaoProfile.java
Normal file
22
src/main/java/com/rest/api/model/social/KakaoProfile.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.rest.api.model.social;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
public class KakaoProfile {
|
||||
private Long id;
|
||||
private Properties properties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
private static class Properties {
|
||||
private String nickname;
|
||||
private String thumbnail_image;
|
||||
private String profile_image;
|
||||
}
|
||||
}
|
||||
14
src/main/java/com/rest/api/model/social/RetKakaoAuth.java
Normal file
14
src/main/java/com/rest/api/model/social/RetKakaoAuth.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.rest.api.model.social;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class RetKakaoAuth {
|
||||
private String access_token;
|
||||
private String token_type;
|
||||
private String refresh_token;
|
||||
private long expires_in;
|
||||
private String scope;
|
||||
}
|
||||
@@ -2,6 +2,11 @@ package com.rest.api.repo;
|
||||
|
||||
import com.rest.api.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserJpaRepo extends JpaRepository<User, Long> {
|
||||
|
||||
Optional<User> findByUid(String email);
|
||||
|
||||
Optional<User> findByUidAndProvider(String uid, String provider);
|
||||
}
|
||||
|
||||
8
src/main/java/com/rest/api/repo/board/BoardJpaRepo.java
Normal file
8
src/main/java/com/rest/api/repo/board/BoardJpaRepo.java
Normal file
@@ -0,0 +1,8 @@
|
||||
package com.rest.api.repo.board;
|
||||
|
||||
import com.rest.api.entity.board.Board;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface BoardJpaRepo extends JpaRepository<Board, Long> {
|
||||
Board findByName(String name);
|
||||
}
|
||||
11
src/main/java/com/rest/api/repo/board/PostJpaRepo.java
Normal file
11
src/main/java/com/rest/api/repo/board/PostJpaRepo.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.rest.api.repo.board;
|
||||
|
||||
import com.rest.api.entity.board.Board;
|
||||
import com.rest.api.entity.board.Post;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PostJpaRepo extends JpaRepository<Post, Long> {
|
||||
List<Post> findByBoardOrderByPostIdDesc(Board board);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ public class ResponseService {
|
||||
|
||||
// enum으로 api 요청 결과에 대한 code, message를 정의합니다.
|
||||
public enum CommonResponse {
|
||||
SUCCESS(0, "성공하였습니디.");
|
||||
SUCCESS(0, "성공하였습니다.");
|
||||
|
||||
int code;
|
||||
String msg;
|
||||
|
||||
96
src/main/java/com/rest/api/service/board/BoardService.java
Normal file
96
src/main/java/com/rest/api/service/board/BoardService.java
Normal file
@@ -0,0 +1,96 @@
|
||||
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;
|
||||
import com.rest.api.entity.board.Post;
|
||||
import com.rest.api.model.board.ParamsPost;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import com.rest.api.repo.board.BoardJpaRepo;
|
||||
import com.rest.api.repo.board.PostJpaRepo;
|
||||
import com.rest.api.service.cache.CacheSevice;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
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;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
@RequiredArgsConstructor
|
||||
public class BoardService {
|
||||
|
||||
private final BoardJpaRepo boardJpaRepo;
|
||||
private final PostJpaRepo postJpaRepo;
|
||||
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) {
|
||||
return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new);
|
||||
}
|
||||
|
||||
// 게시판 이름으로 게시글 리스트 조회.
|
||||
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
|
||||
public List<Post> findPosts(String boardName) {
|
||||
return postJpaRepo.findByBoardOrderByPostIdDesc(findBoard(boardName));
|
||||
}
|
||||
|
||||
// 게시글ID로 게시글 단건 조회. 없을경우 CResourceNotExistException 처리
|
||||
@Cacheable(value = CacheKey.POST, key = "#postId", unless = "#result == null")
|
||||
public Post getPost(long postId) {
|
||||
return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new);
|
||||
}
|
||||
|
||||
// 게시글을 등록합니다. 게시글의 회원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());
|
||||
return postJpaRepo.save(post);
|
||||
}
|
||||
|
||||
// 게시글을 수정합니다. 게시글 등록자와 로그인 회원정보가 틀리면 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();
|
||||
if (!uid.equals(user.getUid()))
|
||||
throw new CNotOwnerException();
|
||||
|
||||
// 영속성 컨텍스트의 변경감지(dirty checking) 기능에 의해 조회한 Post내용을 변경만 해도 Update쿼리가 실행됩니다.
|
||||
post.setUpdate(paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
|
||||
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
|
||||
return post;
|
||||
}
|
||||
|
||||
// 게시글을 삭제합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
|
||||
public boolean deletePost(long postId, String uid) {
|
||||
Post post = getPost(postId);
|
||||
User user = post.getUser();
|
||||
if (!uid.equals(user.getUid()))
|
||||
throw new CNotOwnerException();
|
||||
postJpaRepo.delete(post);
|
||||
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
21
src/main/java/com/rest/api/service/cache/CacheSevice.java
vendored
Normal file
21
src/main/java/com/rest/api/service/cache/CacheSevice.java
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.rest.api.service.cache;
|
||||
|
||||
import com.rest.api.common.CacheKey;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CacheSevice {
|
||||
|
||||
@Caching(evict = {
|
||||
@CacheEvict(value = CacheKey.POST, key = "#postId"),
|
||||
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
|
||||
})
|
||||
public boolean deleteBoardCache(long postId, String boardName) {
|
||||
log.debug("deleteBoardCache - postId {}, boardName {}", postId, boardName);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.rest.api.service.security;
|
||||
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.common.CacheKey;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class CustomUserDetailService implements UserDetailsService {
|
||||
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
|
||||
@Cacheable(value = CacheKey.USER, key = "#userPk", unless = "#result == null")
|
||||
public UserDetails loadUserByUsername(String userPk) {
|
||||
return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
|
||||
}
|
||||
}
|
||||
70
src/main/java/com/rest/api/service/social/KakaoService.java
Normal file
70
src/main/java/com/rest/api/service/social/KakaoService.java
Normal file
@@ -0,0 +1,70 @@
|
||||
package com.rest.api.service.social;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.rest.api.advice.exception.CCommunicationException;
|
||||
import com.rest.api.model.social.KakaoProfile;
|
||||
import com.rest.api.model.social.RetKakaoAuth;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class KakaoService {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final Environment env;
|
||||
private final Gson gson;
|
||||
|
||||
@Value("${spring.url.base}")
|
||||
private String baseUrl;
|
||||
|
||||
@Value("${spring.social.kakao.client_id}")
|
||||
private String kakaoClientId;
|
||||
|
||||
@Value("${spring.social.kakao.redirect}")
|
||||
private String kakaoRedirect;
|
||||
|
||||
public KakaoProfile getKakaoProfile(String accessToken) {
|
||||
// Set header : Content-type: application/x-www-form-urlencoded
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
headers.set("Authorization", "Bearer " + accessToken);
|
||||
|
||||
// Set http entity
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(null, headers);
|
||||
try {
|
||||
// Request profile
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(env.getProperty("spring.social.kakao.url.profile"), request, String.class);
|
||||
if (response.getStatusCode() == HttpStatus.OK)
|
||||
return gson.fromJson(response.getBody(), KakaoProfile.class);
|
||||
} catch (Exception e) {
|
||||
throw new CCommunicationException();
|
||||
}
|
||||
throw new CCommunicationException();
|
||||
}
|
||||
|
||||
public RetKakaoAuth getKakaoTokenInfo(String code) {
|
||||
// Set header : Content-type: application/x-www-form-urlencoded
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
// Set parameter
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("grant_type", "authorization_code");
|
||||
params.add("client_id", kakaoClientId);
|
||||
params.add("redirect_uri", baseUrl + kakaoRedirect);
|
||||
params.add("code", code);
|
||||
// Set http entity
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(env.getProperty("spring.social.kakao.url.token"), request, String.class);
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
return gson.fromJson(response.getBody(), RetKakaoAuth.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
27
src/main/resources/application-alpha.yml
Normal file
27
src/main/resources/application-alpha.yml
Normal file
@@ -0,0 +1,27 @@
|
||||
logging:
|
||||
level:
|
||||
root: warn
|
||||
com.rest.api: info
|
||||
path: /home/ec2-user/app/log
|
||||
file:
|
||||
max-history: 7
|
||||
|
||||
spring:
|
||||
profiles: alpha
|
||||
datasource:
|
||||
url: jdbc:mysql://127.0.0.1:33060/daddyprogrammer?useUnicode=true&autoReconnect=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
username: happydaddy
|
||||
password: daddy!@#1004
|
||||
jpa:
|
||||
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
|
||||
properties.hibernate:
|
||||
hbm2ddl.auto: none
|
||||
format_sql: true
|
||||
showSql: true
|
||||
generate-ddl: false
|
||||
url:
|
||||
base: http://dev-api.daddyprogrammer.org
|
||||
redis:
|
||||
host: Standalone Redis 호스트
|
||||
port: Standalone Redis 포트
|
||||
23
src/main/resources/application-local.yml
Normal file
23
src/main/resources/application-local.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
logging:
|
||||
level:
|
||||
root: info
|
||||
com.rest.api: debug
|
||||
|
||||
spring:
|
||||
profiles: local
|
||||
datasource:
|
||||
url: jdbc:h2:tcp://localhost/~/test
|
||||
driver-class-name: org.h2.Driver
|
||||
username: sa
|
||||
jpa:
|
||||
database-platform: org.hibernate.dialect.H2Dialect
|
||||
properties.hibernate:
|
||||
hbm2ddl.auto: update
|
||||
format_sql: true
|
||||
showSql: true
|
||||
generate-ddl: true
|
||||
url:
|
||||
base: http://localhost:8080
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
@@ -1,15 +1,16 @@
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:h2:tcp://localhost/~/test
|
||||
driver-class-name: org.h2.Driver
|
||||
username: sa
|
||||
jpa:
|
||||
database-platform: org.hibernate.dialect.H2Dialect
|
||||
properties.hibernate.hbm2ddl.auto: update
|
||||
showSql: true
|
||||
profiles:
|
||||
active: local # 디폴트 환경
|
||||
messages:
|
||||
basename: i18n/exception
|
||||
encoding: UTF-8
|
||||
social:
|
||||
kakao:
|
||||
client_id: XXXXXXXXXXXXXXXXXXXXXXXXXX # 앱생성시 받은 REST API 키
|
||||
redirect: /social/login/kakao
|
||||
url:
|
||||
login: https://kauth.kakao.com/oauth/authorize
|
||||
token: https://kauth.kakao.com/oauth/token
|
||||
profile: https://kapi.kakao.com/v2/user/me
|
||||
jwt:
|
||||
secret: govlepel@$&
|
||||
|
||||
@@ -4,3 +4,27 @@ unKnown:
|
||||
userNotFound:
|
||||
code: "-1000"
|
||||
msg: "This member not exist"
|
||||
emailSigninFailed:
|
||||
code: "-1001"
|
||||
msg: "Your account does not exist or your email or password is incorrect."
|
||||
entryPointException:
|
||||
code: "-1002"
|
||||
msg: "You do not have permission to access this resource."
|
||||
accessDenied:
|
||||
code: "-1003"
|
||||
msg: "A resource that can not be accessed with the privileges it has."
|
||||
communicationError:
|
||||
code: "-1004"
|
||||
msg: "An error occurred during communication."
|
||||
existingUser:
|
||||
code: "-1005"
|
||||
msg: "You are an existing member."
|
||||
notOwner:
|
||||
code: "-1006"
|
||||
msg: "You are not the owner of this resource."
|
||||
resourceNotExist:
|
||||
code: "-1007"
|
||||
msg: "This resource does not exist."
|
||||
forbiddenWord:
|
||||
code: "-1008"
|
||||
msg: "forbidden words ({0}) are included in the input."
|
||||
@@ -1,6 +1,30 @@
|
||||
unKnown:
|
||||
code: "-9999"
|
||||
msg: "알수 없는 오류가 발생하였습니다."
|
||||
msg: "알수없는 오류가 발생하였습니다."
|
||||
userNotFound:
|
||||
code: "-1000"
|
||||
msg: "존재하지 않는 회원입니다."
|
||||
emailSigninFailed:
|
||||
code: "-1001"
|
||||
msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."
|
||||
entryPointException:
|
||||
code: "-1002"
|
||||
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
|
||||
accessDenied:
|
||||
code: "-1003"
|
||||
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
|
||||
communicationError:
|
||||
code: "-1004"
|
||||
msg: "통신 중 오류가 발생하였습니다."
|
||||
existingUser:
|
||||
code: "-1005"
|
||||
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
|
||||
notOwner:
|
||||
code: "-1006"
|
||||
msg: "해당 자원의 소유자가 아닙니다."
|
||||
resourceNotExist:
|
||||
code: "-1007"
|
||||
msg: "요청한 자원이 존재 하지 않습니다."
|
||||
forbiddenWord:
|
||||
code: "-1008"
|
||||
msg: "입력한 내용에 금칙어({0})가 포함되어 있습니다."
|
||||
6
src/main/resources/templates/social/login.ftl
Normal file
6
src/main/resources/templates/social/login.ftl
Normal file
@@ -0,0 +1,6 @@
|
||||
<button onclick="popupKakaoLogin()">KakaoLogin</button>
|
||||
<script>
|
||||
function popupKakaoLogin() {
|
||||
window.open('${loginUrl}', 'popupKakaoLogin', 'width=700,height=500,scrollbars=0,toolbar=0,menubar=no')
|
||||
}
|
||||
</script>
|
||||
5
src/main/resources/templates/social/redirectKakao.ftl
Normal file
5
src/main/resources/templates/social/redirectKakao.ftl
Normal file
@@ -0,0 +1,5 @@
|
||||
access_token : ${authInfo.access_token}<br>
|
||||
token_type : ${authInfo.token_type}<br>
|
||||
refresh_token : ${authInfo.refresh_token}<br>
|
||||
expires_in : ${authInfo.expires_in}<br>
|
||||
scope : ${authInfo.scope}<br>
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.rest.api;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class SpringRestApiApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
67
src/test/java/com/rest/api/cache/CacheRepo.java
vendored
Normal file
67
src/test/java/com/rest/api/cache/CacheRepo.java
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
import com.rest.api.entity.board.Post;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CacheRepo {
|
||||
|
||||
private static final String CACHE_KEY = "CACHE_TEST";
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "#postId")
|
||||
public Post getPost(long postId) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@CachePut(value = CACHE_KEY, key = "#post.postId")
|
||||
public Post updatePost(Post post) {
|
||||
return post;
|
||||
}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "{#postId, #title}")
|
||||
public Post getPostMultiKey(long postId, String title) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@CachePut(value = CACHE_KEY, key = "{#post.postId, #post.title}")
|
||||
// @CachePut(value = CACHE_KEY, key = "{#post.postId, #post.getTitle()}")
|
||||
public Post updatePostMultiKey(Post post) {
|
||||
return post;
|
||||
}
|
||||
|
||||
@CacheEvict(cacheNames = {CACHE_KEY}, allEntries = true)
|
||||
public void clearCache(){}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "{#postId}", condition="#postId > 10")
|
||||
public Post getPostCondition(long postId) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "T(com.rest.api.cache.CustomKeyGenerator).create(#postId, #title)")
|
||||
public Post getPostKeyGenerator(long postId, String title) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
}
|
||||
67
src/test/java/com/rest/api/cache/CacheTest.java
vendored
Normal file
67
src/test/java/com/rest/api/cache/CacheTest.java
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
import com.rest.api.entity.board.Post;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class CacheTest {
|
||||
|
||||
@Autowired
|
||||
private CacheRepo cacheRepo;
|
||||
|
||||
@Test
|
||||
public void cacheTest() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPost(1L);
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
// update cache
|
||||
post.setTitle("title_modified");
|
||||
post.setContent("content_modified");
|
||||
cacheRepo.updatePost(post);
|
||||
// get cache
|
||||
Post postModified = cacheRepo.getPost(1L);
|
||||
assertEquals("title_modified", postModified.getTitle());
|
||||
assertEquals("content_modified", postModified.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cacheTestMultiKey() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPostMultiKey(1L, "title_1");
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
// update cache
|
||||
post.setTitle("title_modified");
|
||||
post.setContent("content_modified");
|
||||
cacheRepo.updatePostMultiKey(post);
|
||||
// get cache
|
||||
Post postModified = cacheRepo.getPostMultiKey(1L, "title_modified");
|
||||
assertEquals("title_modified", postModified.getTitle());
|
||||
assertEquals("content_modified", postModified.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cacheTestCustomKeyGenerator() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPostKeyGenerator(1L, "title_1");
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteAllCache() {
|
||||
cacheRepo.getPost(1L);
|
||||
cacheRepo.getPost(2L);
|
||||
cacheRepo.getPost(3L);
|
||||
cacheRepo.getPost(4L);
|
||||
cacheRepo.clearCache();
|
||||
}
|
||||
}
|
||||
7
src/test/java/com/rest/api/cache/CustomKeyGenerator.java
vendored
Normal file
7
src/test/java/com/rest/api/cache/CustomKeyGenerator.java
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
public class CustomKeyGenerator {
|
||||
public static Object create(Object o1, Object o2) {
|
||||
return "FRONT:" + o1 + ":" + o2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.rest.api.controller;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
public class HelloControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void helloworldString() throws Exception {
|
||||
mockMvc.perform(get("/helloworld/string"))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType("text/plain;charset=UTF-8"))
|
||||
.andExpect(content().string("helloworld"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void helloworldJson() throws Exception {
|
||||
mockMvc.perform(get("/helloworld/json"))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType("application/json;charset=utf-8"))
|
||||
.andExpect(jsonPath("$.message").value("helloworld"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void helloworldPage() throws Exception {
|
||||
mockMvc.perform(get("/helloworld/page"))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType("text/html;charset=UTF-8"))
|
||||
.andExpect(view().name("helloworld"))
|
||||
.andExpect(content().string("helloworld"));
|
||||
}
|
||||
}
|
||||
137
src/test/java/com/rest/api/controller/v1/SignControllerTest.java
Normal file
137
src/test/java/com/rest/api/controller/v1/SignControllerTest.java
Normal file
@@ -0,0 +1,137 @@
|
||||
package com.rest.api.controller.v1;
|
||||
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
public class SignControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private UserJpaRepo userJpaRepo;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
userJpaRepo.save(User.builder().uid("happydaddy@naver.com").name("happydaddy").password(passwordEncoder.encode("1234")).roles(Collections.singletonList("ROLE_USER")).build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signin() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("id", "happydaddy@naver.com");
|
||||
params.add("password", "1234");
|
||||
mockMvc.perform(post("/v1/signin").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.msg").exists())
|
||||
.andExpect(jsonPath("$.data").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signinFail() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("id", "happydaddy@naver.com");
|
||||
params.add("password", "12345");
|
||||
mockMvc.perform(post("/v1/signin").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().is5xxServerError())
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.code").value(-1001))
|
||||
.andExpect(jsonPath("$.msg").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signup() throws Exception {
|
||||
long epochTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("id", "happydaddy_" + epochTime + "@naver.com");
|
||||
params.add("password", "12345");
|
||||
params.add("name", "happydaddy_" + epochTime);
|
||||
mockMvc.perform(post("/v1/signup").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.msg").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signupFail() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("id", "happydaddy@naver.com");
|
||||
params.add("password", "12345");
|
||||
params.add("name", "happydaddy");
|
||||
mockMvc.perform(post("/v1/signup").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().is5xxServerError())
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.code").value(-9999));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signInProviderFail() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("accessToken", "XXXXXXXX");
|
||||
mockMvc.perform(post("/v1/signin/kakao").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().is5xxServerError())
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.code").value(-1004));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void signUpSocial() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("accessToken", "HizF3ir9522bMW3shkO0x0T9zBdXFCW1WsF56Qo9dVsAAAFqMwTqHw");
|
||||
params.add("name", "kakaoKing!");
|
||||
mockMvc.perform(post("/v1/signup/kakao").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void signInSocial() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("accessToken", "HizF3ir9522bMW3shkO0x0T9zBdXFCW1WsF56Qo9dVsAAAFqMwTqHw");
|
||||
mockMvc.perform(post("/v1/signin/kakao").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data").exists());
|
||||
}
|
||||
}
|
||||
141
src/test/java/com/rest/api/controller/v1/UserControllerTest.java
Normal file
141
src/test/java/com/rest/api/controller/v1/UserControllerTest.java
Normal file
@@ -0,0 +1,141 @@
|
||||
package com.rest.api.controller.v1;
|
||||
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.json.JacksonJsonParser;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
public class UserControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private UserJpaRepo userJpaRepo;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private String token;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
//userJpaRepo.save(User.builder().uid("happydaddy@naver.com").name("happydaddy").password(passwordEncoder.encode("1234")).roles(Collections.singletonList("ROLE_USER")).build());
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("id", "happydaddy@naver.com");
|
||||
params.add("password", "1234");
|
||||
MvcResult result = mockMvc.perform(post("/v1/signin").params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.msg").exists())
|
||||
.andExpect(jsonPath("$.data").exists())
|
||||
.andReturn();
|
||||
|
||||
String resultString = result.getResponse().getContentAsString();
|
||||
JacksonJsonParser jsonParser = new JacksonJsonParser();
|
||||
token = jsonParser.parseMap(resultString).get("data").toString();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidToken() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.get("/v1/users")
|
||||
.header("X-AUTH-TOKEN", "XXXXXXXXXX"))
|
||||
.andDo(print())
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(redirectedUrl("/exception/entrypoint"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "mockUser", roles = {"ADMIN"}) // 가상의 Mock 유저 대입
|
||||
public void accessdenied() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.get("/v1/users"))
|
||||
//.header("X-AUTH-TOKEN", token))
|
||||
.andDo(print())
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(redirectedUrl("/exception/accessdenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findAllUser() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.get("/v1/users")
|
||||
.header("X-AUTH-TOKEN", token))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.list").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findUser() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.get("/v1/user")
|
||||
.header("X-AUTH-TOKEN", token))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.data").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modify() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("uid", "happydaddy@naver.com");
|
||||
params.add("name", "행복전도사");
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.put("/v1/user")
|
||||
.header("X-AUTH-TOKEN", token)
|
||||
.params(params))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.data.name").value("행복전도사"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delete() throws Exception {
|
||||
Optional<User> user = userJpaRepo.findByUid("happydaddy@naver.com");
|
||||
assertTrue(user.isPresent());
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
.delete("/v1/user/" + user.get().getMsrl())
|
||||
.header("X-AUTH-TOKEN", token))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.rest.api.controller.v1.board;
|
||||
|
||||
public class BoardControllerTest {
|
||||
|
||||
}
|
||||
46
src/test/java/com/rest/api/repo/UserJpaRepoTest.java
Normal file
46
src/test/java/com/rest/api/repo/UserJpaRepoTest.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.rest.api.repo;
|
||||
|
||||
import com.rest.api.entity.User;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest
|
||||
public class UserJpaRepoTest {
|
||||
|
||||
@Autowired
|
||||
private UserJpaRepo userJpaRepo;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Test
|
||||
public void whenFindByUid_thenReturnUser() {
|
||||
String uid = "angrydaddy@gmail.com";
|
||||
String name = "angrydaddy";
|
||||
// given
|
||||
userJpaRepo.save(User.builder()
|
||||
.uid(uid)
|
||||
.password(passwordEncoder.encode("1234"))
|
||||
.name(name)
|
||||
.roles(Collections.singletonList("ROLE_USER"))
|
||||
.build());
|
||||
// when
|
||||
Optional<User> user = userJpaRepo.findByUid(uid);
|
||||
// then
|
||||
assertNotNull(user);// user객체가 null이 아닌지 체크
|
||||
assertTrue(user.isPresent()); // user객체가 존재여부 true/false 체크
|
||||
assertEquals(user.get().getName(), name); // user객체의 name과 name변수 값이 같은지 체크
|
||||
assertThat(user.get().getName(), is(name)); // user객체의 name과 name변수 값이 같은지 체크
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.rest.api.service.social;
|
||||
|
||||
import com.rest.api.model.social.KakaoProfile;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class KakaoServiceTest {
|
||||
|
||||
@Autowired
|
||||
private KakaoService kakaoService;
|
||||
|
||||
@Test @Ignore
|
||||
public void whenGetKakaoProfile_thenReturnProfile() {
|
||||
|
||||
String accessToken = "xjsMzpQtIr4w13FIQvL3R7BW7X4yvm1KmzXCTwopyWAAAAFqMxEcwA";
|
||||
// given
|
||||
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
|
||||
// then
|
||||
assertNotNull(profile);
|
||||
assertEquals(profile.getId(), Long.valueOf(1066788171));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user