Compare commits
1 Commits
feature/se
...
feature/ju
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53da4ab810 |
38
README.md
38
README.md
@@ -25,32 +25,8 @@
|
||||
- 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. 목차
|
||||
### 3. 목차
|
||||
- SpringBoot2로 Rest api 만들기(1) – Intellij Community에서 프로젝트생성
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/19/spring-boot1-start-intellij/
|
||||
@@ -86,14 +62,4 @@ alter table user_roles
|
||||
- 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
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/security
|
||||
@@ -25,12 +25,10 @@ dependencies {
|
||||
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 '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'
|
||||
|
||||
66
deploy.sh
66
deploy.sh
@@ -1,66 +0,0 @@
|
||||
#!/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,14 +1,10 @@
|
||||
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.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringRestApiApplication {
|
||||
@@ -20,21 +16,4 @@ public class SpringRestApiApplication {
|
||||
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,6 +1,8 @@
|
||||
package com.rest.api.advice;
|
||||
|
||||
import com.rest.api.advice.exception.*;
|
||||
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
|
||||
import com.rest.api.advice.exception.CEmailSigninFailedException;
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -53,18 +55,6 @@ public class ExceptionAdvice {
|
||||
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"));
|
||||
}
|
||||
|
||||
// code정보에 해당하는 메시지를 조회합니다.
|
||||
private String getMessage(String code) {
|
||||
return getMessage(code, null);
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
@@ -14,7 +16,9 @@ import java.io.IOException;
|
||||
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException {
|
||||
response.sendRedirect("/exception/accessdenied");
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
|
||||
ServletException {
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/accessdenied");
|
||||
dispatcher.forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
|
||||
ServletException {
|
||||
response.sendRedirect("/exception/entrypoint");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/entrypoint");
|
||||
dispatcher.forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import java.util.List;
|
||||
@Component
|
||||
public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
|
||||
|
||||
@Value("${spring.jwt.secret}")
|
||||
@Value("spring.jwt.secret")
|
||||
private String secretKey;
|
||||
|
||||
private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효
|
||||
|
||||
@@ -31,9 +31,9 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
|
||||
.and()
|
||||
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
|
||||
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
|
||||
.antMatchers(HttpMethod.GET, "/exception/**","/helloworld/**", "/actuator/health").permitAll() // 등록된 GET요청 리소스는 누구나 접근가능
|
||||
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
||||
.antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
|
||||
.antMatchers(HttpMethod.GET, "/helloworld/**", "/favicon.ico").permitAll() // 등록한 GET요청 리소스는 누구나 접근가능
|
||||
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
||||
.and()
|
||||
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
|
||||
.and()
|
||||
|
||||
@@ -2,28 +2,24 @@ 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";
|
||||
private static final String HELLO = "helloworld";
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class Hello {
|
||||
private static class Hello {
|
||||
private String message;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/helloworld/string")
|
||||
@ResponseBody
|
||||
public String helloworldString() {
|
||||
log.debug("Helloworld");
|
||||
log.info("Helloworld");
|
||||
return HELLO;
|
||||
}
|
||||
|
||||
@@ -39,11 +35,4 @@ public class HelloController {
|
||||
public String helloworld() {
|
||||
return "helloworld";
|
||||
}
|
||||
|
||||
@GetMapping("/helloworld/long-process")
|
||||
@ResponseBody
|
||||
public String pause() throws InterruptedException {
|
||||
Thread.sleep(10000);
|
||||
return "Process finished";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,12 @@
|
||||
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.config.security.JwtTokenProvider;
|
||||
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;
|
||||
@@ -19,7 +15,6 @@ 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
|
||||
@@ -31,7 +26,6 @@ public class SignController {
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final ResponseService responseService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final KakaoService kakaoService;
|
||||
|
||||
@ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
|
||||
@PostMapping(value = "/signin")
|
||||
@@ -45,17 +39,6 @@ public class SignController {
|
||||
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,
|
||||
@@ -70,26 +53,4 @@ public class SignController {
|
||||
.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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package com.rest.api.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
@@ -25,12 +28,10 @@ public class User implements UserDetails {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String uid;
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Column(length = 100)
|
||||
@Column(nullable = false, 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
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -7,6 +7,4 @@ import java.util.Optional;
|
||||
public interface UserJpaRepo extends JpaRepository<User, Long> {
|
||||
|
||||
Optional<User> findByUid(String email);
|
||||
|
||||
Optional<User> findByUidAndProvider(String uid, String provider);
|
||||
}
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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
|
||||
@@ -1,20 +0,0 @@
|
||||
logging:
|
||||
level:
|
||||
root: warn
|
||||
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
|
||||
@@ -1,16 +1,17 @@
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
profiles:
|
||||
active: 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
|
||||
showSql: true
|
||||
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@$&
|
||||
secret: govlepel@$&
|
||||
@@ -12,10 +12,4 @@ entryPointException:
|
||||
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."
|
||||
msg: "A resource that can not be accessed with the privileges it has."
|
||||
@@ -12,10 +12,4 @@ entryPointException:
|
||||
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
|
||||
accessDenied:
|
||||
code: "-1003"
|
||||
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
|
||||
communicationError:
|
||||
code: "-1004"
|
||||
msg: "통신 중 오류가 발생하였습니다."
|
||||
existingUser:
|
||||
code: "-1005"
|
||||
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
|
||||
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
|
||||
@@ -1,6 +0,0 @@
|
||||
<button onclick="popupKakaoLogin()">KakaoLogin</button>
|
||||
<script>
|
||||
function popupKakaoLogin() {
|
||||
window.open('${loginUrl}', 'popupKakaoLogin', 'width=700,height=500,scrollbars=0,toolbar=0,menubar=no')
|
||||
}
|
||||
</script>
|
||||
@@ -1,5 +0,0 @@
|
||||
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,24 +1,22 @@
|
||||
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.autoconfigure.web.servlet.WebMvcTest;
|
||||
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.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
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;
|
||||
@@ -34,17 +32,6 @@ 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<>();
|
||||
@@ -99,39 +86,4 @@ public class SignControllerTest {
|
||||
.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());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
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;
|
||||
@@ -10,7 +7,6 @@ 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;
|
||||
@@ -20,10 +16,6 @@ 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.*;
|
||||
@@ -37,17 +29,10 @@ 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");
|
||||
@@ -65,10 +50,6 @@ public class UserControllerTest {
|
||||
token = jsonParser.parseMap(resultString).get("data").toString();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidToken() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders
|
||||
@@ -128,10 +109,8 @@ public class UserControllerTest {
|
||||
|
||||
@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())
|
||||
.delete("/v1/user/2")
|
||||
.header("X-AUTH-TOKEN", token))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
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