From 417bf8d5bcc80c88122539e767ae509feacd9e53 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 17:39:13 +0900 Subject: [PATCH 01/23] =?UTF-8?q?[refactor]=20=ED=8C=A8=ED=82=A4=EC=A7=80?= =?UTF-8?q?=20=EC=9D=B4=EB=A6=84=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ALGo/ALGo_server/message/service/MessageService.java | 4 +--- .../papago/{controller => Controller}/PapagoController.java | 4 ++-- .../papago/{service => Service}/NaverTransService.java | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) rename src/main/java/com/ALGo/ALGo_server/papago/{controller => Controller}/PapagoController.java (86%) rename src/main/java/com/ALGo/ALGo_server/papago/{service => Service}/NaverTransService.java (98%) diff --git a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java index 33977b6..5ac3a74 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java +++ b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java @@ -1,7 +1,7 @@ package com.ALGo.ALGo_server.message.service; import com.ALGo.ALGo_server.message.dto.MessageResponse; -import com.ALGo.ALGo_server.papago.service.NaverTransService; +import com.ALGo.ALGo_server.papago.Service.NaverTransService; import lombok.RequiredArgsConstructor; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @@ -12,12 +12,10 @@ import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/com/ALGo/ALGo_server/papago/controller/PapagoController.java b/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java similarity index 86% rename from src/main/java/com/ALGo/ALGo_server/papago/controller/PapagoController.java rename to src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java index 9a928fa..9d04000 100644 --- a/src/main/java/com/ALGo/ALGo_server/papago/controller/PapagoController.java +++ b/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java @@ -1,6 +1,6 @@ -package com.ALGo.ALGo_server.papago.controller; +package com.ALGo.ALGo_server.papago.Controller; -import com.ALGo.ALGo_server.papago.service.NaverTransService; +import com.ALGo.ALGo_server.papago.Service.NaverTransService; import lombok.RequiredArgsConstructor; import org.json.simple.parser.ParseException; import org.springframework.web.bind.annotation.PostMapping; diff --git a/src/main/java/com/ALGo/ALGo_server/papago/service/NaverTransService.java b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java similarity index 98% rename from src/main/java/com/ALGo/ALGo_server/papago/service/NaverTransService.java rename to src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java index 1f65956..52b5fb5 100644 --- a/src/main/java/com/ALGo/ALGo_server/papago/service/NaverTransService.java +++ b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java @@ -1,4 +1,4 @@ -package com.ALGo.ALGo_server.papago.service; +package com.ALGo.ALGo_server.papago.Service; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; From e6d04d022f831528762e4467c0d4948f86d6eb47 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 17:42:01 +0900 Subject: [PATCH 02/23] =?UTF-8?q?[refactor]=20url=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ALGo_server/message/controller/MessageController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java index 6851490..0453026 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java +++ b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java @@ -11,7 +11,7 @@ import java.io.IOException; @RestController -@RequestMapping("/api") +@RequestMapping("/disaster") public class MessageController { private final MessageService messageService; @@ -21,7 +21,7 @@ public MessageController(MessageService messageService) { this.messageService = messageService; } - @GetMapping("/testMessage") + @GetMapping("/message") public MessageResponse getMessage() throws IOException, ParseException { // try { // messageService.message(); From 171ace3116eb1eca18ff72dc44d7289b280b555e Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 17:42:44 +0900 Subject: [PATCH 03/23] =?UTF-8?q?[refactor]=20println=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ALGo/ALGo_server/papago/Service/NaverTransService.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java index 52b5fb5..7a580f6 100644 --- a/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java +++ b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java @@ -38,16 +38,16 @@ public String getTransSentence(String s) throws ParseException { requestHeaders.put("X-Naver-Client-Secret", clientSecret); String responseBody = post(apiURL, requestHeaders, text); - System.out.println("responseBody = " + responseBody); +// System.out.println("responseBody = " + responseBody); //응답 파싱하기 JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(responseBody); JSONObject messageObj = (JSONObject) jsonObject.get("message"); - System.out.println("messageObj = " + messageObj); +// System.out.println("messageObj = " + messageObj); JSONObject resultObj = (JSONObject) messageObj.get("result"); - System.out.println("resultObj = " + resultObj); +// System.out.println("resultObj = " + resultObj); String transText = resultObj.get("translatedText").toString(); return transText; From c2074497a82343268be98d9273129434d2862b64 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 17:51:00 +0900 Subject: [PATCH 04/23] =?UTF-8?q?[feat]=20jwt,=20security=20=EC=9D=98?= =?UTF-8?q?=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 614a5f8..20a7106 100644 --- a/build.gradle +++ b/build.gradle @@ -22,11 +22,20 @@ repositories { } dependencies { + // Spring Security + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.security:spring-security-test' + + // JWT Token + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + //JSON parser implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' -// implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.mysql:mysql-connector-j' From 21a0899a436de0bb09d38bd274dce1109557c741 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 18:05:33 +0900 Subject: [PATCH 05/23] =?UTF-8?q?[feat]=20user=20entity=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controller/UserController.java | 2 ++ .../authentication/Service/UserService.java | 2 ++ .../ALGo_server/config/SecurityConfig.java | 2 ++ .../com/ALGo/ALGo_server/entity/Role.java | 5 ++++ .../com/ALGo/ALGo_server/entity/User.java | 29 +++++++++++++++++++ 5 files changed, 40 insertions(+) create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java create mode 100644 src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java create mode 100644 src/main/java/com/ALGo/ALGo_server/entity/Role.java create mode 100644 src/main/java/com/ALGo/ALGo_server/entity/User.java diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java new file mode 100644 index 0000000..c9665e9 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java @@ -0,0 +1,2 @@ +package com.ALGo.ALGo_server.authentication.Controller;public class UserController { +} diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java new file mode 100644 index 0000000..b7aa2ae --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -0,0 +1,2 @@ +package com.ALGo.ALGo_server.authentication.Service;public class UserService { +} diff --git a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java new file mode 100644 index 0000000..951da56 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java @@ -0,0 +1,2 @@ +package com.ALGo.ALGo_server.config;public class SecurityConfig { +} diff --git a/src/main/java/com/ALGo/ALGo_server/entity/Role.java b/src/main/java/com/ALGo/ALGo_server/entity/Role.java new file mode 100644 index 0000000..a26b0e6 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/entity/Role.java @@ -0,0 +1,5 @@ +package com.ALGo.ALGo_server.entity; + +public enum Role { + ROLE_USER, ROLE_ADMIN; +} diff --git a/src/main/java/com/ALGo/ALGo_server/entity/User.java b/src/main/java/com/ALGo/ALGo_server/entity/User.java new file mode 100644 index 0000000..923783e --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/entity/User.java @@ -0,0 +1,29 @@ +package com.ALGo.ALGo_server.entity; + +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id") + private Long id; + + private String email; + private String password; + + @Enumerated(EnumType.STRING) + private Role role; + + @Builder + private User(String email, String password, Role role){ + this.email = email; + this.password = password; + this.role = role; + } +} From 3aa4760578fd6638160563774fa81c9d1f46f3d7 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 18:28:22 +0900 Subject: [PATCH 06/23] =?UTF-8?q?[feat]email=EB=A1=9C=20user=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/Jwt/JwtTokenProvider.java | 2 ++ .../Service/CustomUserDetailsService.java | 2 ++ .../ALGo/ALGo_server/repository/UserRepository.java | 10 ++++++++++ 3 files changed, 14 insertions(+) create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java create mode 100644 src/main/java/com/ALGo/ALGo_server/repository/UserRepository.java diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java new file mode 100644 index 0000000..f1f5413 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java @@ -0,0 +1,2 @@ +package com.ALGo.ALGo_server.authentication.Jwt;public class JwtTokenProvider { +} diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java new file mode 100644 index 0000000..0ef9975 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java @@ -0,0 +1,2 @@ +package com.ALGo.ALGo_server.authentication.Service;public class CustomUserDetailsService { +} diff --git a/src/main/java/com/ALGo/ALGo_server/repository/UserRepository.java b/src/main/java/com/ALGo/ALGo_server/repository/UserRepository.java new file mode 100644 index 0000000..294b81a --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.ALGo.ALGo_server.repository; + +import com.ALGo.ALGo_server.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); +} From 09c3f8444dec6b7d18ded449a9bd70119f754091 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 18:28:58 +0900 Subject: [PATCH 07/23] =?UTF-8?q?[feat]=20CustomUserDetailService=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Service/CustomUserDetailsService.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java index 0ef9975..8cef2d6 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java @@ -1,2 +1,20 @@ -package com.ALGo.ALGo_server.authentication.Service;public class CustomUserDetailsService { +package com.ALGo.ALGo_server.authentication.Service; + +import com.ALGo.ALGo_server.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +public class CustomUserDetailsService implements UserDetailsService { + private final UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return (UserDetails) userRepository.findByEmail(username) + .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다.")); + } } From 8c2e56472a609a71c0f8ff789111e34784c84edf Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 18:46:02 +0900 Subject: [PATCH 08/23] [feat] JwtTokenProvider #9 --- .../authentication/Jwt/JwtTokenProvider.java | 111 +++++++++++++++++- 1 file changed, 110 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java index f1f5413..8e0e316 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java @@ -1,2 +1,111 @@ -package com.ALGo.ALGo_server.authentication.Jwt;public class JwtTokenProvider { +package com.ALGo.ALGo_server.authentication.Jwt; + +import com.ALGo.ALGo_server.authentication.Service.CustomUserDetailsService; +import io.jsonwebtoken.*; +import jakarta.annotation.PostConstruct; +import jakarta.servlet.http.HttpServletRequest; +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.stereotype.Component; + +import java.security.Key; +import java.util.Base64; +import java.util.Date; + +@Component +@RequiredArgsConstructor +public class JwtTokenProvider { + private static final String AUTHORITIES_KEY = "auth"; + private static final String BEARER_TYPE = "BEARER"; + private final Long ACCESS_TOKEN_EXPIRE_TIME = 1000L * 60L * 60L; //만료 1시간 + private final Long REFRESH_TOKEN_EXPIRE_TIME = 1000L * 60L * 60L * 24L * 7L; //만료 7일 + + private final CustomUserDetailsService customUserDetailsService; + + @Value("${jwt.secret}") + private String secretKey; + + //객체 초기화, secretKey를 Base64로 인코딩 + @PostConstruct + protected void init(){ + secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); + } + + //JWT AccessToken 생성 + public String createAccessToken(String email, String role){ + Claims claims = Jwts.claims().setSubject(email); //JWT payload에 저장되는 정보 단위 + claims.put("role", role); //정보는 key-value 쌍으로 저장 + Date now = new Date(); + + return Jwts.builder() + .setClaims(claims) //정보 저장 + .setIssuedAt(now) //토큰 발행 시간 정보 + .setExpiration(new Date(now.getTime() + ACCESS_TOKEN_EXPIRE_TIME)) //만료 시간 설정 + .signWith(SignatureAlgorithm.HS512, secretKey) //사용할 암호화 알고리즘, signature에 들어갈 secret 값 세팅 + .compact(); + } + + //Refresh Token 생성 + public String createRefreshToken(){ + Date now = new Date(); + return Jwts.builder() + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + REFRESH_TOKEN_EXPIRE_TIME)) + .signWith(SignatureAlgorithm.HS512, secretKey) + .compact(); + } + + + //토큰에서 회원 정보(이메일) 추출 + public String getUserEmail(String token){ + return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); + } + + //JWT 토큰에서 인증 정보 조회 - DB 조회 1번 일어남 + public Authentication getAuthentication(String token){ + UserDetails userDetails = customUserDetailsService.loadUserByUsername(this.getUserEmail(token)); + return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); + } + + //Request Header에서 token값 가져오기. "X-ACCESS-TOKEN" : "TOKEN 값" + public String resolveAccessToken(HttpServletRequest request){ + return request.getHeader("X-ACCESS-TOKEN"); + } + + public String resolveRefreshToken(HttpServletRequest request){ + return request.getHeader("X-REFRESH-TOKEN"); + } + + //Access Token의 만료일자 가져오기 + public Long getAccessTokenExpiration(String accessToken){ + Date expiration = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(accessToken).getBody().getExpiration(); + Long now = new Date().getTime(); + return (expiration.getTime() - now); + } + + //Access Token의 유효성 + 만료일자 확인 + public boolean validAccessToken(String accessToken){ + try { + Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(accessToken); + return !claims.getBody().getExpiration().before(new Date()); + }catch (Exception e){ + return false; + } + } + + //RefreshToken의 유효성 + 만료일자 확인 + public boolean validRefreshToken(String refreshToken){ + try { + Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(refreshToken); + return !claims.getBody().getExpiration().before(new Date()); + }catch (ExpiredJwtException e){ + return true; + }catch (Exception e){ + return false; + } + } + } From 0e76c731dd5fb75c1b542ea7863ecbb1c0fd865a Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 19:08:30 +0900 Subject: [PATCH 09/23] [feat] JwtAuthenticationFilter #9 --- .../Jwt/JwtAuthenticationFilter.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java new file mode 100644 index 0000000..329e769 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java @@ -0,0 +1,41 @@ +package com.ALGo.ALGo_server.authentication.Jwt; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +//token의 인증 정보를 검사한 후 security context에 저장 +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtTokenProvider jwtAuthenticationProvider; + + public JwtAuthenticationFilter(JwtTokenProvider provider){ + this.jwtAuthenticationProvider = provider; + } + + /** + * 요청이 들어올 때마다 실행되는 메서드로, + * 요청의 헤더에서 JWT 토큰을 추출하여 유효성을 검사하고, + * 유효한 토큰이면 인증 정보를 추출하여 현재 보안 컨텍스트에 설정 + */ + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String token = jwtAuthenticationProvider.resolveAccessToken(request); //request 헤더에서 토큰 가져옴 + + + if (token != null && jwtAuthenticationProvider.validAccessToken(token)){ + //유효한 토큰이면 jwtTokenProvider를 통해 Authentication 객체를 생성 + Authentication authentication = jwtAuthenticationProvider.getAuthentication(token); + + //현재 스레드의 security context에 인증 정보를 저장 -> 해당 요청을 처리하는 동안 인증된 사용자로서 권한이 부여 + SecurityContextHolder.getContext().setAuthentication(authentication); + } + filterChain.doFilter(request, response); + + } +} From 1d6b48143a88b5b3b36c44c9e8c6032d86f7eabb Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 19:14:33 +0900 Subject: [PATCH 10/23] [feat] SecurityConfig #9 --- .../ALGo_server/config/SecurityConfig.java | 77 ++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java index 951da56..df7fbf2 100644 --- a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java +++ b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java @@ -1,2 +1,77 @@ -package com.ALGo.ALGo_server.config;public class SecurityConfig { +package com.ALGo.ALGo_server.config; + +import com.ALGo.ALGo_server.authentication.Jwt.JwtAuthenticationFilter; +import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; +import jakarta.servlet.DispatcherType; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.time.Duration; + +@RequiredArgsConstructor +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + private final JwtTokenProvider jwtTokenProvider; + + //비밀번호 암호화 처리하는 메서디 제공 + @Bean + public PasswordEncoder passwordEncoder(){ + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .authorizeRequests() + .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() //prefilght request 허용 + .anyRequest().permitAll(); + + http + .csrf(csrf -> csrf.disable()) //token을 사용하는 방식이므로 csrf를 disable로 설정 + .formLogin(formLogin -> formLogin.disable()) //사용자 지정 로그인 로직 구현 + .httpBasic(httpBasic -> httpBasic.disable()); //http 기본 인증 비활성화 + + http.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); + + //세션을 사용하지 않으므로 Stateless로 설정 + http.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + //enable Mysql-console + http.headers(headers -> headers.frameOptions(options -> options.sameOrigin())); + + return http.build(); + + } + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.addAllowedOrigin("http://localhost:3001"); + configuration.addAllowedOrigin("http://localhost:3000"); + configuration.addAllowedMethod("*"); + configuration.addAllowedHeader("*"); + configuration.setAllowCredentials(true); + configuration.setMaxAge(Duration.ofSeconds(3600)); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + } From 2eaaa61120f46c1fd0687ad47ab7100a5e304146 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 19:45:54 +0900 Subject: [PATCH 11/23] =?UTF-8?q?[feat]=20=ED=9A=8C=EC=9B=90=EA=B0=80?= =?UTF-8?q?=EC=9E=85=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controller/UserController.java | 25 ++++++++- .../authentication/Dto/JoinRequestDto.java | 30 +++++++++++ .../authentication/Service/UserService.java | 35 ++++++++++++- .../com/ALGo/ALGo_server/entity/User.java | 52 ++++++++++++++++++- 4 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java index c9665e9..9b412a6 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java @@ -1,2 +1,25 @@ -package com.ALGo.ALGo_server.authentication.Controller;public class UserController { +package com.ALGo.ALGo_server.authentication.Controller; + +import com.ALGo.ALGo_server.authentication.Dto.JoinRequestDto; +import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; +import com.ALGo.ALGo_server.authentication.Service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/users") +@RequiredArgsConstructor +public class UserController { + private final UserService userService; + private final JwtTokenProvider jwtTokenProvider; + + @PostMapping("/join") + @ResponseStatus(HttpStatus.OK) + public ResponseEntity join(@RequestBody JoinRequestDto requestDto){ + userService.join(requestDto); + return new ResponseEntity(HttpStatus.OK); + } + } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java new file mode 100644 index 0000000..5672c24 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java @@ -0,0 +1,30 @@ +package com.ALGo.ALGo_server.authentication.Dto; + +import com.ALGo.ALGo_server.entity.Role; +import com.ALGo.ALGo_server.entity.User; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class JoinRequestDto { + + private String email; + private String password; + private String language; + private String area; + private Role role; + + @Builder + public User toEntity(){ + return User.builder() + .email(email) + .password(password) + .role(Role.ROLE_USER) + .build(); + } +} diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java index b7aa2ae..da02000 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -1,2 +1,35 @@ -package com.ALGo.ALGo_server.authentication.Service;public class UserService { +package com.ALGo.ALGo_server.authentication.Service; + +import com.ALGo.ALGo_server.authentication.Dto.JoinRequestDto; +import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; +import com.ALGo.ALGo_server.entity.User; +import com.ALGo.ALGo_server.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +@Service +@Transactional +@RequiredArgsConstructor +@Slf4j +public class UserService { + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final JwtTokenProvider jwtTokenProvider; + + public Long join(JoinRequestDto requestDto) { + //이메일 중복 검사 + if (userRepository.findByEmail(requestDto.getEmail()).isPresent()){ + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "중복된 이메일입니다"); + } + User user = userRepository.save(requestDto.toEntity()); + user.encodePassword(passwordEncoder); //비밀번호 암호화 + + return user.getId(); + } } diff --git a/src/main/java/com/ALGo/ALGo_server/entity/User.java b/src/main/java/com/ALGo/ALGo_server/entity/User.java index 923783e..dea5745 100644 --- a/src/main/java/com/ALGo/ALGo_server/entity/User.java +++ b/src/main/java/com/ALGo/ALGo_server/entity/User.java @@ -4,11 +4,19 @@ 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; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; @Entity @Getter @NoArgsConstructor -public class User { +public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") @@ -16,14 +24,56 @@ public class User { private String email; private String password; + private String refreshToken; @Enumerated(EnumType.STRING) private Role role; + public void encodePassword(PasswordEncoder passwordEncoder){ + this.password = passwordEncoder.encode(password); + } + + public void updateRefreshToken(String refreshToken){ + this.refreshToken = refreshToken; + } + @Builder private User(String email, String password, Role role){ this.email = email; this.password = password; this.role = role; } + + //UserDetail implement한 내용 + @Override + public Collection getAuthorities() { + List auth = new ArrayList<>(); + auth.add(new SimpleGrantedAuthority(role.name())); + return auth; + } + + @Override + public String getUsername() { + return null; + } + + @Override + public boolean isAccountNonExpired() { + return false; + } + + @Override + public boolean isAccountNonLocked() { + return false; + } + + @Override + public boolean isCredentialsNonExpired() { + return false; + } + + @Override + public boolean isEnabled() { + return false; + } } From e1ebd180e68c3da7fc0a6fe65358f1a581dde9f6 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 20:00:15 +0900 Subject: [PATCH 12/23] =?UTF-8?q?[feat]=20join=20=EA=B5=AC=ED=98=84=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/Dto/LoginRequestDto.java | 15 ++++++ .../authentication/Dto/TokenResponseDto.java | 15 ++++++ .../authentication/Service/UserService.java | 46 +++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Dto/LoginRequestDto.java create mode 100644 src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/LoginRequestDto.java b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/LoginRequestDto.java new file mode 100644 index 0000000..04a7314 --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/LoginRequestDto.java @@ -0,0 +1,15 @@ +package com.ALGo.ALGo_server.authentication.Dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class LoginRequestDto { + private String email; + private String password; +} diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java new file mode 100644 index 0000000..f54c47f --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java @@ -0,0 +1,15 @@ +package com.ALGo.ALGo_server.authentication.Dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class TokenResponseDto { + private String jwtAccessToken; + private String jwtRefreshToken; +} diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java index da02000..e5caf25 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -1,9 +1,12 @@ package com.ALGo.ALGo_server.authentication.Service; import com.ALGo.ALGo_server.authentication.Dto.JoinRequestDto; +import com.ALGo.ALGo_server.authentication.Dto.LoginRequestDto; +import com.ALGo.ALGo_server.authentication.Dto.TokenResponseDto; import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; import com.ALGo.ALGo_server.entity.User; import com.ALGo.ALGo_server.repository.UserRepository; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; @@ -32,4 +35,47 @@ public Long join(JoinRequestDto requestDto) { return user.getId(); } + + public TokenResponseDto login(LoginRequestDto requestDto){ + User user = userRepository.findByEmail(requestDto.getEmail()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST,"잘못된 이메일입니다")); + + if (!passwordEncoder.matches(requestDto.getPassword(), user.getPassword())){ + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 비밀번호입니다"); + } + + String accessToken = jwtTokenProvider.createAccessToken(user.getUsername(), user.getRole().name()); + String refreshToken = jwtTokenProvider.createRefreshToken(); + + user.updateRefreshToken(refreshToken); + } + + public TokenResponseDto issueAccessToken(HttpServletRequest request){ + String accessToken = jwtTokenProvider.resolveAccessToken(request); + String refreshToken = jwtTokenProvider.resolveRefreshToken(request); + + if (!jwtTokenProvider.validAccessToken(accessToken)){ + log.info("access token 만료"); + + if (jwtTokenProvider.validRefreshToken(refreshToken)){ + log.info("refresh token 유효"); + + User user = userRepository.findByEmail(jwtTokenProvider.getUserEmail(refreshToken)) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 이메일입니다")); + + //refresh token 값이 같다면 + if (refreshToken.equals(user.getRefreshToken())){ + accessToken = jwtTokenProvider.createAccessToken(user.getEmail(), user.getRole().name()); + }else { + log.info("refresh token 변조"); + } + }else{ + log.info("refresh token 유효하지 않음"); + } + } + return TokenResponseDto.builder() + .jwtAccessToken(accessToken) + .jwtRefreshToken(refreshToken) + .build(); + } } From 3b77179a2e151b9d6e68354a0ec05b4beccc2672 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 20:08:00 +0900 Subject: [PATCH 13/23] =?UTF-8?q?[feat]=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/Controller/UserController.java | 8 ++++++++ .../authentication/Dto/TokenResponseDto.java | 1 + .../authentication/Service/UserService.java | 10 +++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java index 9b412a6..e47fcdd 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java @@ -1,8 +1,10 @@ package com.ALGo.ALGo_server.authentication.Controller; import com.ALGo.ALGo_server.authentication.Dto.JoinRequestDto; +import com.ALGo.ALGo_server.authentication.Dto.LoginRequestDto; import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; import com.ALGo.ALGo_server.authentication.Service.UserService; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -22,4 +24,10 @@ public ResponseEntity join(@RequestBody JoinRequestDto requestDto){ return new ResponseEntity(HttpStatus.OK); } + @PostMapping("/login") + @ResponseStatus(HttpStatus.OK) + public ResponseEntity login(@RequestBody LoginRequestDto requestDto){ + return new ResponseEntity(userService.login(requestDto), HttpStatus.OK); + } + } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java index f54c47f..3d0c2ca 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/TokenResponseDto.java @@ -10,6 +10,7 @@ @AllArgsConstructor @Builder public class TokenResponseDto { + private String grantType; private String jwtAccessToken; private String jwtRefreshToken; } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java index e5caf25..df9beac 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -47,7 +47,15 @@ public TokenResponseDto login(LoginRequestDto requestDto){ String accessToken = jwtTokenProvider.createAccessToken(user.getUsername(), user.getRole().name()); String refreshToken = jwtTokenProvider.createRefreshToken(); - user.updateRefreshToken(refreshToken); + user.updateRefreshToken(refreshToken); //refresh token 저장 + userRepository.save(user); + + return TokenResponseDto.builder() + .grantType("Bearer") + .jwtAccessToken(accessToken) + .jwtRefreshToken(refreshToken) + .build(); + } public TokenResponseDto issueAccessToken(HttpServletRequest request){ From 4d4d1878c46063f2dbcd8a16285c18016c7912fa Mon Sep 17 00:00:00 2001 From: yunji118 Date: Wed, 10 Jan 2024 20:09:11 +0900 Subject: [PATCH 14/23] =?UTF-8?q?[feat]=20=EB=A1=9C=EA=B7=B8=EC=9D=B8/?= =?UTF-8?q?=ED=9A=8C=EC=9B=90=EA=B0=80=EC=9E=85=20=EA=B5=AC=ED=98=84=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ALGo_server/authentication/Controller/UserController.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java index e47fcdd..3f6db14 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Controller/UserController.java @@ -4,7 +4,6 @@ import com.ALGo.ALGo_server.authentication.Dto.LoginRequestDto; import com.ALGo.ALGo_server.authentication.Jwt.JwtTokenProvider; import com.ALGo.ALGo_server.authentication.Service.UserService; -import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -15,7 +14,6 @@ @RequiredArgsConstructor public class UserController { private final UserService userService; - private final JwtTokenProvider jwtTokenProvider; @PostMapping("/join") @ResponseStatus(HttpStatus.OK) From 12184ad16882a92b751c54c0765fb27d8450e24f Mon Sep 17 00:00:00 2001 From: yunji118 Date: Thu, 11 Jan 2024 01:14:44 +0900 Subject: [PATCH 15/23] =?UTF-8?q?[fix]=20=ED=9A=8C=EC=9B=90=EA=B0=80?= =?UTF-8?q?=EC=9E=85=20=EC=8B=9C=20=EC=A0=95=EB=B3=B4=20=EB=8D=94=20?= =?UTF-8?q?=EB=B0=9B=EC=95=84=EC=98=A4=EA=B8=B0=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/Dto/JoinRequestDto.java | 2 ++ .../Jwt/JwtAuthenticationFilter.java | 1 - .../authentication/Jwt/JwtTokenProvider.java | 4 ++-- .../Service/CustomUserDetailsService.java | 5 +++++ .../authentication/Service/UserService.java | 2 +- .../ALGo/ALGo_server/config/SecurityConfig.java | 1 + .../java/com/ALGo/ALGo_server/entity/User.java | 16 ++++++++++------ 7 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java index 5672c24..570597b 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Dto/JoinRequestDto.java @@ -24,6 +24,8 @@ public User toEntity(){ return User.builder() .email(email) .password(password) + .language(language) + .area(area) .role(Role.ROLE_USER) .build(); } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java index 329e769..ebb6ba2 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtAuthenticationFilter.java @@ -27,7 +27,6 @@ public JwtAuthenticationFilter(JwtTokenProvider provider){ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = jwtAuthenticationProvider.resolveAccessToken(request); //request 헤더에서 토큰 가져옴 - if (token != null && jwtAuthenticationProvider.validAccessToken(token)){ //유효한 토큰이면 jwtTokenProvider를 통해 Authentication 객체를 생성 Authentication authentication = jwtAuthenticationProvider.getAuthentication(token); diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java index 8e0e316..666b1f6 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Jwt/JwtTokenProvider.java @@ -20,8 +20,8 @@ public class JwtTokenProvider { private static final String AUTHORITIES_KEY = "auth"; private static final String BEARER_TYPE = "BEARER"; - private final Long ACCESS_TOKEN_EXPIRE_TIME = 1000L * 60L * 60L; //만료 1시간 - private final Long REFRESH_TOKEN_EXPIRE_TIME = 1000L * 60L * 60L * 24L * 7L; //만료 7일 + private final Long ACCESS_TOKEN_EXPIRE_TIME = 10000L * 60 * 60; + private final Long REFRESH_TOKEN_EXPIRE_TIME = 10000L * 60 * 60 * 24 * 7; private final CustomUserDetailsService customUserDetailsService; diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java index 8cef2d6..7884949 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java @@ -1,5 +1,6 @@ package com.ALGo.ALGo_server.authentication.Service; +import com.ALGo.ALGo_server.entity.User; import com.ALGo.ALGo_server.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; @@ -7,6 +8,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; +import java.util.List; + @RequiredArgsConstructor @Service public class CustomUserDetailsService implements UserDetailsService { @@ -14,6 +17,8 @@ public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + List users = userRepository.findAll(); + System.out.println("users = "+users.size()); return (UserDetails) userRepository.findByEmail(username) .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다.")); } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java index df9beac..b5ff920 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -44,7 +44,7 @@ public TokenResponseDto login(LoginRequestDto requestDto){ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 비밀번호입니다"); } - String accessToken = jwtTokenProvider.createAccessToken(user.getUsername(), user.getRole().name()); + String accessToken = jwtTokenProvider.createAccessToken(user.getEmail(), user.getRole().name()); String refreshToken = jwtTokenProvider.createRefreshToken(); user.updateRefreshToken(refreshToken); //refresh token 저장 diff --git a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java index df7fbf2..c01ca2c 100644 --- a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java +++ b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java @@ -39,6 +39,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(cors -> cors.configurationSource(corsConfigurationSource())) .authorizeRequests() +// .requestMatchers("/disaster/**").authenticated() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() //prefilght request 허용 .anyRequest().permitAll(); diff --git a/src/main/java/com/ALGo/ALGo_server/entity/User.java b/src/main/java/com/ALGo/ALGo_server/entity/User.java index dea5745..f75c0a9 100644 --- a/src/main/java/com/ALGo/ALGo_server/entity/User.java +++ b/src/main/java/com/ALGo/ALGo_server/entity/User.java @@ -25,6 +25,8 @@ public class User implements UserDetails { private String email; private String password; private String refreshToken; + private String area; + private String language; @Enumerated(EnumType.STRING) private Role role; @@ -37,12 +39,6 @@ public void updateRefreshToken(String refreshToken){ this.refreshToken = refreshToken; } - @Builder - private User(String email, String password, Role role){ - this.email = email; - this.password = password; - this.role = role; - } //UserDetail implement한 내용 @Override @@ -52,6 +48,14 @@ public Collection getAuthorities() { return auth; } + @Builder + public User(String email, String password, String area, String language, Role role){ + this.email = email; + this.password = password; + this.area = area; + this.language = language; + this.role = role; + } @Override public String getUsername() { return null; From 62e15a83d6c0ff2af22663cd9e868809b9c0fc52 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Thu, 11 Jan 2024 01:19:55 +0900 Subject: [PATCH 16/23] =?UTF-8?q?[fix]=20=EC=9C=A0=EC=A0=80=20=EB=AA=BB=20?= =?UTF-8?q?=EC=B0=BE=EB=8A=94=20=EB=AC=B8=EC=A0=9C=20=ED=95=B4=EA=B2=B0=20?= =?UTF-8?q?#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Service/CustomUserDetailsService.java | 2 -- .../authentication/Service/UserService.java | 2 +- src/main/java/com/ALGo/ALGo_server/entity/User.java | 10 +++++----- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java index 7884949..9d80ba7 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/CustomUserDetailsService.java @@ -17,8 +17,6 @@ public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - List users = userRepository.findAll(); - System.out.println("users = "+users.size()); return (UserDetails) userRepository.findByEmail(username) .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다.")); } diff --git a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java index b5ff920..e6378c2 100644 --- a/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java +++ b/src/main/java/com/ALGo/ALGo_server/authentication/Service/UserService.java @@ -44,7 +44,7 @@ public TokenResponseDto login(LoginRequestDto requestDto){ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 비밀번호입니다"); } - String accessToken = jwtTokenProvider.createAccessToken(user.getEmail(), user.getRole().name()); + String accessToken = jwtTokenProvider.createAccessToken(user.getUsername(), user.getRole().name()); //여기가 문제인가? String refreshToken = jwtTokenProvider.createRefreshToken(); user.updateRefreshToken(refreshToken); //refresh token 저장 diff --git a/src/main/java/com/ALGo/ALGo_server/entity/User.java b/src/main/java/com/ALGo/ALGo_server/entity/User.java index f75c0a9..ff0aec3 100644 --- a/src/main/java/com/ALGo/ALGo_server/entity/User.java +++ b/src/main/java/com/ALGo/ALGo_server/entity/User.java @@ -58,26 +58,26 @@ public User(String email, String password, String area, String language, Role ro } @Override public String getUsername() { - return null; + return email; } @Override public boolean isAccountNonExpired() { - return false; + return true; } @Override public boolean isAccountNonLocked() { - return false; + return true; } @Override public boolean isCredentialsNonExpired() { - return false; + return true; } @Override public boolean isEnabled() { - return false; + return true; } } From dc74fc027dc8a15806ab16a7f94d044c6fe8c2c7 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Thu, 11 Jan 2024 01:23:11 +0900 Subject: [PATCH 17/23] =?UTF-8?q?[feat]=20=ED=97=A4=EB=8D=94=EC=97=90=20?= =?UTF-8?q?=ED=86=A0=ED=81=B0=20=EC=9E=88=EC=96=B4=EC=95=BC=EB=A7=8C=20?= =?UTF-8?q?=EC=A0=91=EA=B7=BC=20=EA=B0=80=EB=8A=A5=ED=95=98=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EB=B3=80=EA=B2=BD=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java index c01ca2c..c117873 100644 --- a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java +++ b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java @@ -39,7 +39,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(cors -> cors.configurationSource(corsConfigurationSource())) .authorizeRequests() -// .requestMatchers("/disaster/**").authenticated() + .requestMatchers("/disaster/**").authenticated() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() //prefilght request 허용 .anyRequest().permitAll(); From 87837d60f7c5b0f746b53ffc1f35b769c4c367a8 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Thu, 11 Jan 2024 01:28:04 +0900 Subject: [PATCH 18/23] =?UTF-8?q?[feat]=20=EC=9C=A0=EC=A0=80=EA=B0=80=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=ED=95=9C=20=EC=96=B8=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EB=B2=88=EC=97=AD=20#9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../message/controller/MessageController.java | 8 +++++--- .../ALGo/ALGo_server/message/service/MessageService.java | 5 +++-- .../ALGo_server/papago/Controller/PapagoController.java | 6 ++++-- .../ALGo_server/papago/Service/NaverTransService.java | 9 +++++---- 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java index 0453026..2f1d070 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java +++ b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java @@ -1,10 +1,12 @@ package com.ALGo.ALGo_server.message.controller; +import com.ALGo.ALGo_server.entity.User; import com.ALGo.ALGo_server.message.dto.MessageResponse; import com.ALGo.ALGo_server.message.service.MessageService; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -22,7 +24,7 @@ public MessageController(MessageService messageService) { } @GetMapping("/message") - public MessageResponse getMessage() throws IOException, ParseException { + public MessageResponse getMessage(@AuthenticationPrincipal User user) throws IOException, ParseException { // try { // messageService.message(); // } catch (IOException e) { @@ -30,6 +32,6 @@ public MessageResponse getMessage() throws IOException, ParseException { // } catch (ParseException e) { // throw new RuntimeException(e); // } - return messageService.message(); + return messageService.message(user); } } diff --git a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java index 5ac3a74..db8bdb9 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java +++ b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java @@ -1,5 +1,6 @@ package com.ALGo.ALGo_server.message.service; +import com.ALGo.ALGo_server.entity.User; import com.ALGo.ALGo_server.message.dto.MessageResponse; import com.ALGo.ALGo_server.papago.Service.NaverTransService; import lombok.RequiredArgsConstructor; @@ -28,7 +29,7 @@ public class MessageService { private final NaverTransService naverTransService; - public MessageResponse message() throws IOException, ParseException { + public MessageResponse message(User user) throws IOException, ParseException { StringBuilder urlBuilder = new StringBuilder("https://www.safetydata.go.kr/openApi"); urlBuilder.append("/" + URLEncoder.encode("행정안전부_긴급재난문자","UTF-8")); @@ -83,7 +84,7 @@ public MessageResponse message() throws IOException, ParseException { String a = areaArr.get(i); } - String translatedMSG = naverTransService.getTransSentence(MSG_CN); + String translatedMSG = naverTransService.getTransSentence(MSG_CN, user); MessageResponse response = new MessageResponse(translatedMSG, CREAT_DT, areaArr, EMRGNCY_STEP_ID, DSSTR_SE_ID); return response; } diff --git a/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java b/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java index 9d04000..d6056be 100644 --- a/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java +++ b/src/main/java/com/ALGo/ALGo_server/papago/Controller/PapagoController.java @@ -1,8 +1,10 @@ package com.ALGo.ALGo_server.papago.Controller; +import com.ALGo.ALGo_server.entity.User; import com.ALGo.ALGo_server.papago.Service.NaverTransService; import lombok.RequiredArgsConstructor; import org.json.simple.parser.ParseException; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -16,7 +18,7 @@ public class PapagoController { //Only BE test용도 @PostMapping("/translate") - public String translate(@RequestBody String prompt) throws ParseException { - return naverTransService.getTransSentence(prompt); + public String translate(@RequestBody String prompt, @AuthenticationPrincipal User user) throws ParseException { + return naverTransService.getTransSentence(prompt, user); } } diff --git a/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java index 7a580f6..df9ffe5 100644 --- a/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java +++ b/src/main/java/com/ALGo/ALGo_server/papago/Service/NaverTransService.java @@ -1,5 +1,6 @@ package com.ALGo.ALGo_server.papago.Service; +import com.ALGo.ALGo_server.entity.User; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @@ -22,7 +23,7 @@ public class NaverTransService { @Value("${papago-client-secret}") private String clientSecret; //papago 애플리케이션 클라이언트 시크릿값; - public String getTransSentence(String s) throws ParseException { + public String getTransSentence(String s, User user) throws ParseException { String apiURL = "https://openapi.naver.com/v1/papago/n2mt"; String text; @@ -37,7 +38,7 @@ public String getTransSentence(String s) throws ParseException { requestHeaders.put("X-Naver-Client-Id", clientId); requestHeaders.put("X-Naver-Client-Secret", clientSecret); - String responseBody = post(apiURL, requestHeaders, text); + String responseBody = post(apiURL, requestHeaders, text, user); // System.out.println("responseBody = " + responseBody); //응답 파싱하기 @@ -54,9 +55,9 @@ public String getTransSentence(String s) throws ParseException { } - private String post(String apiUrl, Map requestHeaders, String text){ + private String post(String apiUrl, Map requestHeaders, String text, User user){ HttpURLConnection con = connect(apiUrl); - String postParams = "source=ko&target=en&text=" + text; //나중에 목적 언어는 사용자 데이터로 바꾸기!! ko(원본언어) -> 목적언어 + String postParams = "source=ko&target="+user.getLanguage()+"&text=" + text; //나중에 목적 언어는 사용자 데이터로 바꾸기!! ko(원본언어) -> 목적언어 try { con.setRequestMethod("POST"); From 3815d52f9c42807151a5c88d3b9757a40b167e2a Mon Sep 17 00:00:00 2001 From: Yunji Ha Date: Thu, 11 Jan 2024 01:50:33 +0900 Subject: [PATCH 19/23] =?UTF-8?q?[CI/CD]=20github=20action=20=EC=97=B0?= =?UTF-8?q?=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/main.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..2a85c60 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,22 @@ +name: AL-Go server CI/CD + +on: + push: + branches: [ main ] + +jobs: + SSH: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: ssh to ec2 + uses: appleboy/ssh-action@master + with: + key: ${{ secrets.SSH_PRIVATE_KEY }} + host: ${{ secrets.HOST }} + username: ${{ secrets.USER }} + script: | + cd /home/ec2-user/apps/step1 + sh deploy.sh + nohup java -jar wow_server-0.0.1-SNAPSHOT.jar > nohup.out 2> nohup.err < /dev/null & From 559eb27b968aa5e20871dfc618b1f3481c26d2e5 Mon Sep 17 00:00:00 2001 From: ri-naa Date: Thu, 11 Jan 2024 01:52:54 +0900 Subject: [PATCH 20/23] =?UTF-8?q?[feat]=20shelter=20entity=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ALGo/ALGo_server/entity/Shelter.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/java/com/ALGo/ALGo_server/entity/Shelter.java diff --git a/src/main/java/com/ALGo/ALGo_server/entity/Shelter.java b/src/main/java/com/ALGo/ALGo_server/entity/Shelter.java new file mode 100644 index 0000000..2bfa2af --- /dev/null +++ b/src/main/java/com/ALGo/ALGo_server/entity/Shelter.java @@ -0,0 +1,25 @@ +package com.ALGo.ALGo_server.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor +public class Shelter { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long shelter_id; + + @Column(nullable = false) + private String region; + + @Column(nullable = false) + private String address; + + @Column(nullable = false) + private String description; + +} From 70ef88e2572b31896937a74357112445f2f99ea9 Mon Sep 17 00:00:00 2001 From: yunji118 Date: Thu, 11 Jan 2024 03:30:16 +0900 Subject: [PATCH 21/23] =?UTF-8?q?[fix]=205173=20port=20=EC=97=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java index c117873..d8edbe2 100644 --- a/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java +++ b/src/main/java/com/ALGo/ALGo_server/config/SecurityConfig.java @@ -63,8 +63,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); - configuration.addAllowedOrigin("http://localhost:3001"); - configuration.addAllowedOrigin("http://localhost:3000"); + configuration.addAllowedOrigin("http://localhost:5173"); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); From d6fd07772d3387e6243eda289f77540d120fbf19 Mon Sep 17 00:00:00 2001 From: ri-naa Date: Thu, 11 Jan 2024 03:36:23 +0900 Subject: [PATCH 22/23] =?UTF-8?q?[fix]=20=EC=88=98=EC=8B=A0=EC=A7=80?= =?UTF-8?q?=EC=97=AD=EB=AA=85,=20=EC=9E=AC=ED=95=B4=EA=B5=AC=EB=B6=84=20?= =?UTF-8?q?=EB=AA=85=20=EC=B6=94=EA=B0=80=20#3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../message/controller/MessageController.java | 14 ++++--------- .../message/dto/MessageResponse.java | 6 +++++- .../message/service/MessageService.java | 20 +++++++++++++------ 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java index 2f1d070..bea7743 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java +++ b/src/main/java/com/ALGo/ALGo_server/message/controller/MessageController.java @@ -7,10 +7,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.GetMapping; - import org.springframework.web.bind.annotation.RequestMapping; - import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; - import java.io.IOException; +import java.io.IOException; @RestController @RequestMapping("/disaster") @@ -25,13 +25,7 @@ public MessageController(MessageService messageService) { @GetMapping("/message") public MessageResponse getMessage(@AuthenticationPrincipal User user) throws IOException, ParseException { -// try { -// messageService.message(); -// } catch (IOException e) { -// e.printStackTrace(); -// } catch (ParseException e) { -// throw new RuntimeException(e); -// } + return messageService.message(user); } } diff --git a/src/main/java/com/ALGo/ALGo_server/message/dto/MessageResponse.java b/src/main/java/com/ALGo/ALGo_server/message/dto/MessageResponse.java index e7d384f..935a067 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/dto/MessageResponse.java +++ b/src/main/java/com/ALGo/ALGo_server/message/dto/MessageResponse.java @@ -9,15 +9,19 @@ public class MessageResponse { private String MSG_CN; //메세지 내용 private String CREAT_DT; //생성일 private List RCV_AREA_ID; //수신지역 id + private List RCV_AREA_NM; //수신지역명 private String EMRGNCY_STEP_ID; //긴급단계 id private String DSSTR_SE_ID; //재해구분 id + private String DSSTR_SE_NM; //재해구분 명 - public MessageResponse(String MSG_CN, String CREAT_DT, List RCV_AREA_ID, String EMRGNCY_STEP_ID, String DSSTR_SE_ID){ + public MessageResponse(String MSG_CN, String CREAT_DT, List RCV_AREA_ID, List RCV_AREA_NM, String EMRGNCY_STEP_ID, String DSSTR_SE_ID, String DSSTR_SE_NM){ this.MSG_CN = MSG_CN; this.CREAT_DT = CREAT_DT; this.RCV_AREA_ID = RCV_AREA_ID; + this.RCV_AREA_NM = RCV_AREA_NM; this.EMRGNCY_STEP_ID = EMRGNCY_STEP_ID; this.DSSTR_SE_ID = DSSTR_SE_ID; + this.DSSTR_SE_NM = DSSTR_SE_NM; } } diff --git a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java index db8bdb9..9cc7ed4 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java +++ b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java @@ -42,7 +42,7 @@ public MessageResponse message(User user) throws IOException, ParseException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); -// System.out.println("Response code: " + conn.getResponseCode()); + System.out.println("Response code: " + conn.getResponseCode()); BufferedReader rd; @@ -62,7 +62,7 @@ public MessageResponse message(User user) throws IOException, ParseException { // HTTP 연결 닫기 conn.disconnect(); String responseBody = sb.toString(); -// System.out.println(responseBody); + System.out.println(responseBody); //파싱 JSONParser jsonParser = new JSONParser(); @@ -75,17 +75,25 @@ public MessageResponse message(User user) throws IOException, ParseException { String CREAT_DT = dataObject.get("CREAT_DT").toString(); String DSSTR_SE_ID = dataObject.get("DSSTR_SE_ID").toString(); + String DSSTR_SE_NM = dataObject.get("DSSTR_SE_NM").toString(); String EMRGNCY_STEP_ID = dataObject.get("EMRGNCY_STEP_ID").toString(); String MSG_CN = dataObject.get("MSG_CN").toString(); String RCV_AREA_ID = dataObject.get("RCV_AREA_ID").toString(); + String RCV_AREA_NM = dataObject.get("RCV_AREA_NM").toString(); - List areaArr = Arrays.stream(RCV_AREA_ID.split(",")).toList(); - for(int i=0;i areaIdArr = Arrays.stream(RCV_AREA_ID.split(",")).toList(); + for(int i=0;i areaNmArr = Arrays.stream(RCV_AREA_NM.split(",")).toList(); + for(int i=0;i Date: Thu, 11 Jan 2024 03:41:48 +0900 Subject: [PATCH 23/23] =?UTF-8?q?[fix]=20=EC=9E=AC=EB=82=9C=EB=AC=B8?= =?UTF-8?q?=EC=9E=90=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?#3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ALGo/ALGo_server/message/service/MessageService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java index 9cc7ed4..25d1446 100644 --- a/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java +++ b/src/main/java/com/ALGo/ALGo_server/message/service/MessageService.java @@ -42,7 +42,7 @@ public MessageResponse message(User user) throws IOException, ParseException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); - System.out.println("Response code: " + conn.getResponseCode()); +// System.out.println("Response code: " + conn.getResponseCode()); BufferedReader rd; @@ -62,7 +62,7 @@ public MessageResponse message(User user) throws IOException, ParseException { // HTTP 연결 닫기 conn.disconnect(); String responseBody = sb.toString(); - System.out.println(responseBody); +// System.out.println(responseBody); //파싱 JSONParser jsonParser = new JSONParser();