diff --git "a/.github/ISSUE_TEMPLATE/\342\231\273\357\270\217--refactor-.md" "b/.github/ISSUE_TEMPLATE/\342\231\273\357\270\217--refactor-.md" new file mode 100644 index 0000000..b60e558 --- /dev/null +++ "b/.github/ISSUE_TEMPLATE/\342\231\273\357\270\217--refactor-.md" @@ -0,0 +1,17 @@ +--- +name: "♻️ [REFACTOR]" +about: 리팩토링 이슈 템플릿입니다. +title: "♻️ [REFACTOR]" +labels: "♻️ refactor" +assignees: '' + +--- + +# Title +- tmp + +# Content +- tmp + +# TODO +- [ ] tmp diff --git "a/.github/ISSUE_TEMPLATE/\342\234\250--feat--.md" "b/.github/ISSUE_TEMPLATE/\342\234\250--feat--.md" new file mode 100644 index 0000000..ac1270e --- /dev/null +++ "b/.github/ISSUE_TEMPLATE/\342\234\250--feat--.md" @@ -0,0 +1,17 @@ +--- +name: "✨ [FEAT] " +about: 기능 개발 이슈 템플릿입니다. +title: "✨ [FEAT] " +labels: "✨ feature" +assignees: '' + +--- + +# Title +- tmp + +# Content +- tmp + +# TODO +- [ ] tmp diff --git "a/.github/ISSUE_TEMPLATE/\360\237\220\233--bug-.md" "b/.github/ISSUE_TEMPLATE/\360\237\220\233--bug-.md" new file mode 100644 index 0000000..614897c --- /dev/null +++ "b/.github/ISSUE_TEMPLATE/\360\237\220\233--bug-.md" @@ -0,0 +1,17 @@ +--- +name: "\U0001F41B [BUG]" +about: 버그 이슈 템플릿입니다. +title: "\U0001F41B [BUG]" +labels: "\U0001F41B bug" +assignees: '' + +--- + +# Title +- tmp + +# Content +- tmp + +# TODO +- [ ] tmp diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..2e57273 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,8 @@ +# 🔎 Resolved Issue +- tmp + +# ✅ Title +- tmp + +# 📄 Content +- tmp diff --git a/src/main/java/com/soongsil/CoffeeChat/config/SecurityConfig.java b/src/main/java/com/soongsil/CoffeeChat/config/SecurityConfig.java index a01196d..ff85354 100644 --- a/src/main/java/com/soongsil/CoffeeChat/config/SecurityConfig.java +++ b/src/main/java/com/soongsil/CoffeeChat/config/SecurityConfig.java @@ -1,15 +1,9 @@ package com.soongsil.CoffeeChat.config; -import com.soongsil.CoffeeChat.config.jwt.CustomLogoutFilter; -import com.soongsil.CoffeeChat.config.jwt.JWTFilter; -import com.soongsil.CoffeeChat.config.jwt.JWTUtil; -import com.soongsil.CoffeeChat.config.oauth2.CustomSuccessHandler; -import com.soongsil.CoffeeChat.repository.RefreshRepository; -import com.soongsil.CoffeeChat.service.CustomOAuth2UserService; -import jakarta.servlet.http.HttpServletRequest; +import java.util.Collections; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; @@ -20,7 +14,14 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; -import java.util.Collections; +import com.soongsil.CoffeeChat.config.jwt.CustomLogoutFilter; +import com.soongsil.CoffeeChat.config.jwt.JWTFilter; +import com.soongsil.CoffeeChat.config.jwt.JWTUtil; +import com.soongsil.CoffeeChat.config.oauth2.CustomSuccessHandler; +import com.soongsil.CoffeeChat.repository.RefreshRepository; +import com.soongsil.CoffeeChat.service.CustomOAuth2UserService; + +import jakarta.servlet.http.HttpServletRequest; @Configuration @EnableWebSecurity diff --git a/src/main/java/com/soongsil/CoffeeChat/config/jwt/CustomLogoutFilter.java b/src/main/java/com/soongsil/CoffeeChat/config/jwt/CustomLogoutFilter.java index f056144..41165a7 100644 --- a/src/main/java/com/soongsil/CoffeeChat/config/jwt/CustomLogoutFilter.java +++ b/src/main/java/com/soongsil/CoffeeChat/config/jwt/CustomLogoutFilter.java @@ -1,6 +1,11 @@ package com.soongsil.CoffeeChat.config.jwt; +import java.io.IOException; + +import org.springframework.web.filter.GenericFilterBean; + import com.soongsil.CoffeeChat.repository.RefreshRepository; + import io.jsonwebtoken.ExpiredJwtException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -9,95 +14,98 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.springframework.web.filter.GenericFilterBean; - -import java.io.IOException; public class CustomLogoutFilter extends GenericFilterBean { - private final JWTUtil jwtUtil; - private final RefreshRepository refreshRepository; - - public CustomLogoutFilter(JWTUtil jwtUtil, RefreshRepository refreshRepository) { - - this.jwtUtil = jwtUtil; - this.refreshRepository = refreshRepository; - } - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); - } - private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { - - //path and method verify - String requestUri = request.getRequestURI(); //요청의 path값을 꺼내고 - if (!requestUri.matches("^\\/logout$")) { //logout경로인지 확인 후 - - filterChain.doFilter(request, response); - return; - } - String requestMethod = request.getMethod(); - if (!requestMethod.equals("POST")) { //POST요청인지 확인 - - filterChain.doFilter(request, response); - return; - } - - //get refresh token - String refresh = null; - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { - - if (cookie.getName().equals("refresh")) { - - refresh = cookie.getValue(); - } - } - - //refresh null check 400 (refresh토큰이 null상태) - if (refresh == null) { - - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - //expired check - try { - jwtUtil.isExpired(refresh); - } catch (ExpiredJwtException e) { - - //response status code 400 (만료된 토큰) - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) - String category = jwtUtil.getCategory(refresh); - if (!category.equals("refresh")) { - - //response status code 400 (refresh토큰이 아님) - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - //DB에 저장되어 있는지 확인 - Boolean isExist = refreshRepository.existsByRefresh(refresh); - if (!isExist) { - - //response status code 400 (DB에 저장된 refresh 토큰이 아님) - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - //로그아웃 진행 - //Refresh 토큰 DB에서 제거 (앞으로 해당 refresh토큰으로 reissue불가능) - refreshRepository.deleteByRefresh(refresh); - - //Refresh 토큰 Cookie 값 0 (null인 refresh토큰 반환) - Cookie cookie = new Cookie("refresh", null); - cookie.setMaxAge(0); - cookie.setPath("/"); - - response.addCookie(cookie); - response.setStatus(HttpServletResponse.SC_OK); - } + private final JWTUtil jwtUtil; + private final RefreshRepository refreshRepository; + + public CustomLogoutFilter(JWTUtil jwtUtil, RefreshRepository refreshRepository) { + + this.jwtUtil = jwtUtil; + this.refreshRepository = refreshRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws + IOException, + ServletException { + doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); + } + + private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws + IOException, + ServletException { + + //path and method verify + String requestUri = request.getRequestURI(); //요청의 path값을 꺼내고 + if (!requestUri.matches("^\\/logout$")) { //logout경로인지 확인 후 + + filterChain.doFilter(request, response); + return; + } + String requestMethod = request.getMethod(); + if (!requestMethod.equals("POST")) { //POST요청인지 확인 + + filterChain.doFilter(request, response); + return; + } + + //get refresh token + String refresh = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + + if (cookie.getName().equals("refresh")) { + + refresh = cookie.getValue(); + } + } + + //refresh null check 400 (refresh토큰이 null상태) + if (refresh == null) { + + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + //expired check + try { + jwtUtil.isExpired(refresh); + } catch (ExpiredJwtException e) { + + //response status code 400 (만료된 토큰) + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) + String category = jwtUtil.getCategory(refresh); + if (!category.equals("refresh")) { + + //response status code 400 (refresh토큰이 아님) + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + //DB에 저장되어 있는지 확인 + Boolean isExist = refreshRepository.existsByRefresh(refresh); + if (!isExist) { + + //response status code 400 (DB에 저장된 refresh 토큰이 아님) + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + //로그아웃 진행 + //Refresh 토큰 DB에서 제거 (앞으로 해당 refresh토큰으로 reissue불가능) + refreshRepository.deleteByRefresh(refresh); + + //Refresh 토큰 Cookie 값 0 (null인 refresh토큰 반환) + Cookie cookie = new Cookie("refresh", null); + cookie.setMaxAge(0); + cookie.setPath("/"); + + response.addCookie(cookie); + response.setStatus(HttpServletResponse.SC_OK); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTFilter.java b/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTFilter.java index 6a8fc96..39ad1ea 100644 --- a/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTFilter.java +++ b/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTFilter.java @@ -1,13 +1,21 @@ package com.soongsil.CoffeeChat.config.jwt; + +import java.io.IOException; +import java.io.PrintWriter; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + import com.soongsil.CoffeeChat.dto.CustomOAuth2User; import com.soongsil.CoffeeChat.dto.UserDTO; -import com.soongsil.CoffeeChat.entity.User; + import io.jsonwebtoken.ExpiredJwtException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; -import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -16,8 +24,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; -import java.io.PrintWriter; public class JWTFilter extends OncePerRequestFilter { //요청당 한번만 실행되면 됨 private final JWTUtil jwtUtil; //JWT검증 위하여 주입 @@ -26,6 +32,15 @@ public JWTFilter(JWTUtil jwtUtil) { this.jwtUtil = jwtUtil; } + +public class JWTFilter extends OncePerRequestFilter { //요청당 한번만 실행되면 됨 + private final JWTUtil jwtUtil; //JWT검증 위하여 주입 + + public JWTFilter(JWTUtil jwtUtil) { + this.jwtUtil = jwtUtil; + } + + @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { diff --git a/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTUtil.java b/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTUtil.java index 8fde295..a0f75ae 100644 --- a/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTUtil.java +++ b/src/main/java/com/soongsil/CoffeeChat/config/jwt/JWTUtil.java @@ -1,49 +1,72 @@ package com.soongsil.CoffeeChat.config.jwt; -import io.jsonwebtoken.Jwts; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; +import java.nio.charset.StandardCharsets; +import java.util.Date; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; -import java.util.Date; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Jwts; //JWT : username, role, 생성일, 만료일 포함, 0.12.3 버전 사용 //username확인, role확인, 만료일 확인 @Component public class JWTUtil { - private SecretKey secretKey; - - public JWTUtil(@Value("${spring.jwt.secret}")String secret) { - secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); - } - - public String getUsername(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); - } - - public String getRole(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); - } - - public Boolean isExpired(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); - } - - public String getCategory(String token){ //토큰의 카테고리 꺼내는 로직 추가 - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("category", String.class); - } - - - public String createJwt(String category, String username, String role, Long expiredMs) { //토큰생성 - return Jwts.builder() - .claim("category", category) - .claim("username", username) - .claim("role", role) - .issuedAt(new Date(System.currentTimeMillis())) - .expiration(new Date(System.currentTimeMillis() + expiredMs)) - .signWith(secretKey) - .compact(); - } + private SecretKey secretKey; + + public JWTUtil(@Value("${spring.jwt.secret}") String secret) { + secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), + Jwts.SIG.HS256.key().build().getAlgorithm()); + } + + public String getUsername(String token) { + return Jwts.parser() + .verifyWith(secretKey) + .build() + .parseSignedClaims(token) + .getPayload() + .get("username", String.class); + } + + public String getRole(String token) { + return Jwts.parser() + .verifyWith(secretKey) + .build() + .parseSignedClaims(token) + .getPayload() + .get("role", String.class); + } + + public Boolean isExpired(String token) { + return Jwts.parser() + .verifyWith(secretKey) + .build() + .parseSignedClaims(token) + .getPayload() + .getExpiration() + .before(new Date()); + } + + public String getCategory(String token) { //토큰의 카테고리 꺼내는 로직 추가 + return Jwts.parser() + .verifyWith(secretKey) + .build() + .parseSignedClaims(token) + .getPayload() + .get("category", String.class); + } + + public String createJwt(String category, String username, String role, Long expiredMs) { //토큰생성 + return Jwts.builder() + .claim("category", category) + .claim("username", username) + .claim("role", role) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + expiredMs)) + .signWith(secretKey) + .compact(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/config/oauth2/CustomSuccessHandler.java b/src/main/java/com/soongsil/CoffeeChat/config/oauth2/CustomSuccessHandler.java index 3aa8689..8e1193c 100644 --- a/src/main/java/com/soongsil/CoffeeChat/config/oauth2/CustomSuccessHandler.java +++ b/src/main/java/com/soongsil/CoffeeChat/config/oauth2/CustomSuccessHandler.java @@ -1,5 +1,16 @@ package com.soongsil.CoffeeChat.config.oauth2; +import java.io.IOException; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; + +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.stereotype.Component; + import com.soongsil.CoffeeChat.config.jwt.JWTUtil; import com.soongsil.CoffeeChat.dto.CustomOAuth2User; import com.soongsil.CoffeeChat.entity.Refresh; @@ -21,6 +32,7 @@ import java.util.Date; import java.util.Iterator; + //로그인이 성공했을 때 받은 데이터들을 바탕으로 JWT발급을 위한 핸들러 @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/MainController.java b/src/main/java/com/soongsil/CoffeeChat/controller/MainController.java index 685f718..8378ec6 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/MainController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/MainController.java @@ -6,9 +6,9 @@ @Controller public class MainController { - @GetMapping("/") - @ResponseBody - public String mainAPI(){ - return "main route"; - } + @GetMapping("/") + @ResponseBody + public String mainAPI() { + return "main route"; + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/MentorController.java b/src/main/java/com/soongsil/CoffeeChat/controller/MentorController.java index e3a2cfc..d84f8dd 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/MentorController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/MentorController.java @@ -1,16 +1,19 @@ package com.soongsil.CoffeeChat.controller; -import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; -import com.soongsil.CoffeeChat.dto.ResponseMentorListInfo; -import com.soongsil.CoffeeChat.entity.Mentor; -import com.soongsil.CoffeeChat.service.MentorService; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.*; +import static com.soongsil.CoffeeChat.enums.RequestUri.*; import java.util.List; -import static com.soongsil.CoffeeChat.enums.RequestUri.MENTOR_URI; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; +import com.soongsil.CoffeeChat.dto.ResponseMentorListInfo; +import com.soongsil.CoffeeChat.service.MentorService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/MyController.java b/src/main/java/com/soongsil/CoffeeChat/controller/MyController.java index 2c3a31b..e257dbd 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/MyController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/MyController.java @@ -6,9 +6,9 @@ @Controller public class MyController { - @GetMapping("/my") - @ResponseBody - public String myAPI(){ - return "my route"; - } + @GetMapping("/my") + @ResponseBody + public String myAPI() { + return "my route"; + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/PossibleDateController.java b/src/main/java/com/soongsil/CoffeeChat/controller/PossibleDateController.java index 0480cdf..5f3cedf 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/PossibleDateController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/PossibleDateController.java @@ -1,5 +1,6 @@ package com.soongsil.CoffeeChat.controller; + import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; import com.soongsil.CoffeeChat.entity.PossibleDate; import com.soongsil.CoffeeChat.service.PossibleDateService; @@ -16,14 +17,17 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static com.soongsil.CoffeeChat.enums.RequestUri.POSSIBLEDATE_URI; +import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; +import com.soongsil.CoffeeChat.service.PossibleDateService; + +import lombok.RequiredArgsConstructor; @RestController @RequestMapping(POSSIBLEDATE_URI) @RequiredArgsConstructor @Tag(name="POSSIBLEDATE", description = "커피챗 시간 관련 api") public class PossibleDateController { - private final PossibleDateService possibleDateService; + private final PossibleDateService possibleDateService; @PostMapping() @Operation(summary="멘토가 직접 커피챗 가능시간 추가하기") diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/RefreshTokenController.java b/src/main/java/com/soongsil/CoffeeChat/controller/RefreshTokenController.java index b7f7b1f..78ef7ae 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/RefreshTokenController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/RefreshTokenController.java @@ -1,26 +1,31 @@ package com.soongsil.CoffeeChat.controller; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + import com.soongsil.CoffeeChat.config.jwt.JWTUtil; import com.soongsil.CoffeeChat.service.RefreshTokenService; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; + import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; @RestController //RestController=Controller+ResponseBody @Tag(name="REFRESHTOKEN", description = "리프레쉬 토큰 관련 api") public class RefreshTokenController { //Refresh토큰으로 Access토큰 발급 및 2차회원가입 컨트롤러 - private final JWTUtil jwtUtil; - private final RefreshTokenService refreshTokenService; - public RefreshTokenController(JWTUtil jwtUtil, RefreshTokenService refreshTokenService){ - this.jwtUtil=jwtUtil; - this.refreshTokenService = refreshTokenService; - } + private final JWTUtil jwtUtil; + private final RefreshTokenService refreshTokenService; + + public RefreshTokenController(JWTUtil jwtUtil, RefreshTokenService refreshTokenService) { + this.jwtUtil = jwtUtil; + this.refreshTokenService = refreshTokenService; + } + @PostMapping("/reissue") @Operation(summary="리프레쉬 토큰으로 액세스 토큰 reissue") diff --git a/src/main/java/com/soongsil/CoffeeChat/controller/UserController.java b/src/main/java/com/soongsil/CoffeeChat/controller/UserController.java index 24d6e15..727ac59 100644 --- a/src/main/java/com/soongsil/CoffeeChat/controller/UserController.java +++ b/src/main/java/com/soongsil/CoffeeChat/controller/UserController.java @@ -1,10 +1,19 @@ package com.soongsil.CoffeeChat.controller; +import static com.soongsil.CoffeeChat.enums.RequestUri.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + import com.soongsil.CoffeeChat.dto.CreateMenteeRequest; import com.soongsil.CoffeeChat.dto.CreateMentorRequest; import com.soongsil.CoffeeChat.entity.Mentee; import com.soongsil.CoffeeChat.entity.Mentor; -import com.soongsil.CoffeeChat.repository.UserRepository; import com.soongsil.CoffeeChat.service.UserService; import io.swagger.v3.oas.annotations.Operation; @@ -16,7 +25,8 @@ import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; -import static com.soongsil.CoffeeChat.enums.RequestUri.USER_URI; + +import lombok.RequiredArgsConstructor; @RestController @RequestMapping(USER_URI) diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/CreateMenteeRequest.java b/src/main/java/com/soongsil/CoffeeChat/dto/CreateMenteeRequest.java index 4fd4bc3..d790e75 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/CreateMenteeRequest.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/CreateMenteeRequest.java @@ -1,13 +1,12 @@ package com.soongsil.CoffeeChat.dto; -import jakarta.persistence.Column; import lombok.Getter; @Getter public class CreateMenteeRequest { - private String phoneNum; - private String birth; - private int grade; - private String major; - private String memo; + private String phoneNum; + private String birth; + private int grade; + private String major; + private String memo; } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/CreateMentorRequest.java b/src/main/java/com/soongsil/CoffeeChat/dto/CreateMentorRequest.java index d96fcab..9e3f5e7 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/CreateMentorRequest.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/CreateMentorRequest.java @@ -1,14 +1,11 @@ package com.soongsil.CoffeeChat.dto; -import com.soongsil.CoffeeChat.entity.User; -import lombok.Builder; import lombok.Getter; @Getter public class CreateMentorRequest { - private String phoneNum; - private String birth; - private String part; - + private String phoneNum; + private String birth; + private String part; } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/CustomOAuth2User.java b/src/main/java/com/soongsil/CoffeeChat/dto/CustomOAuth2User.java index d4516de..46bf907 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/CustomOAuth2User.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/CustomOAuth2User.java @@ -1,46 +1,46 @@ package com.soongsil.CoffeeChat.dto; -import com.soongsil.CoffeeChat.dto.UserDTO; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.oauth2.core.user.OAuth2User; - import java.util.ArrayList; import java.util.Collection; import java.util.Map; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.user.OAuth2User; + public class CustomOAuth2User implements OAuth2User { - private final UserDTO userDTO; - public CustomOAuth2User(UserDTO userDTO){ - this.userDTO=userDTO; - } - - @Override - public Map getAttributes() { //받은 데이터값 리턴 - //여러 소셜 로그인을 진행하면 받는 Attribute 형식이 다르므로 사용 X - return null; - } - - @Override - public Collection getAuthorities() { //Role값리턴 - Collection collection = new ArrayList<>(); - collection.add(new GrantedAuthority() { - - @Override - public String getAuthority() { - - return userDTO.getRole(); - } - }); - return collection; - } - - @Override - public String getName() { - return userDTO.getName(); - } - - public String getUsername() { //스프링애플리케이션 서버 ID반환 메소드 - - return userDTO.getUsername(); - } + private final UserDTO userDTO; + + public CustomOAuth2User(UserDTO userDTO) { + this.userDTO = userDTO; + } + + @Override + public Map getAttributes() { //받은 데이터값 리턴 + //여러 소셜 로그인을 진행하면 받는 Attribute 형식이 다르므로 사용 X + return null; + } + + @Override + public Collection getAuthorities() { //Role값리턴 + Collection collection = new ArrayList<>(); + collection.add(new GrantedAuthority() { + + @Override + public String getAuthority() { + + return userDTO.getRole(); + } + }); + return collection; + } + + @Override + public String getName() { + return userDTO.getName(); + } + + public String getUsername() { //스프링애플리케이션 서버 ID반환 메소드 + + return userDTO.getUsername(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/GoogleResponse.java b/src/main/java/com/soongsil/CoffeeChat/dto/GoogleResponse.java index 2b2fdf2..c8bf261 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/GoogleResponse.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/GoogleResponse.java @@ -2,35 +2,35 @@ import java.util.Map; -public class GoogleResponse implements OAuth2Response{ - private final Map attribute; +public class GoogleResponse implements OAuth2Response { + private final Map attribute; - public GoogleResponse(Map attribute) { + public GoogleResponse(Map attribute) { - this.attribute = attribute; - } + this.attribute = attribute; + } - @Override - public String getProvider() { + @Override + public String getProvider() { - return "google"; - } + return "google"; + } - @Override - public String getProviderId() { + @Override + public String getProviderId() { - return attribute.get("sub").toString(); - } + return attribute.get("sub").toString(); + } - @Override - public String getEmail() { + @Override + public String getEmail() { - return attribute.get("email").toString(); - } + return attribute.get("email").toString(); + } - @Override - public String getName() { + @Override + public String getName() { - return attribute.get("name").toString(); - } + return attribute.get("name").toString(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/NaverResponse.java b/src/main/java/com/soongsil/CoffeeChat/dto/NaverResponse.java index af2feef..a08c46b 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/NaverResponse.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/NaverResponse.java @@ -2,35 +2,35 @@ import java.util.Map; -public class NaverResponse implements OAuth2Response{ - private final Map attribute; //데이터 받을 Map +public class NaverResponse implements OAuth2Response { + private final Map attribute; //데이터 받을 Map - public NaverResponse(Map attribute) { + public NaverResponse(Map attribute) { - this.attribute = (Map) attribute.get("response"); - } + this.attribute = (Map)attribute.get("response"); + } - @Override - public String getProvider() { + @Override + public String getProvider() { - return "naver"; - } + return "naver"; + } - @Override - public String getProviderId() { + @Override + public String getProviderId() { - return attribute.get("id").toString(); - } + return attribute.get("id").toString(); + } - @Override - public String getEmail() { + @Override + public String getEmail() { - return attribute.get("email").toString(); - } + return attribute.get("email").toString(); + } - @Override - public String getName() { + @Override + public String getName() { - return attribute.get("name").toString(); - } + return attribute.get("name").toString(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/OAuth2Response.java b/src/main/java/com/soongsil/CoffeeChat/dto/OAuth2Response.java index e9a7981..3012a26 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/OAuth2Response.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/OAuth2Response.java @@ -1,12 +1,15 @@ package com.soongsil.CoffeeChat.dto; public interface OAuth2Response { - //제공자 (Ex. naver, google, ...) - String getProvider(); - //제공자에서 발급해주는 아이디(번호) - String getProviderId(); - //이메일 - String getEmail(); - //사용자 실명 (설정한 이름) - String getName(); + //제공자 (Ex. naver, google, ...) + String getProvider(); + + //제공자에서 발급해주는 아이디(번호) + String getProviderId(); + + //이메일 + String getEmail(); + + //사용자 실명 (설정한 이름) + String getName(); } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/PossibleDateRequestDto.java b/src/main/java/com/soongsil/CoffeeChat/dto/PossibleDateRequestDto.java index 1bed9d5..6b55b55 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/PossibleDateRequestDto.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/PossibleDateRequestDto.java @@ -1,30 +1,31 @@ package com.soongsil.CoffeeChat.dto; +import java.time.LocalDate; +import java.time.LocalTime; + import com.fasterxml.jackson.annotation.JsonFormat; import com.soongsil.CoffeeChat.entity.PossibleDate; + import lombok.Builder; import lombok.Getter; -import java.time.LocalDate; -import java.time.LocalTime; - @Getter @Builder public class PossibleDateRequestDto { - @JsonFormat(pattern = "yyyy-MM-dd") - private LocalDate date; + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate date; - @JsonFormat(pattern = "HH:mm") - private LocalTime startTime; + @JsonFormat(pattern = "HH:mm") + private LocalTime startTime; - @JsonFormat(pattern = "HH:mm") - private LocalTime endTime; + @JsonFormat(pattern = "HH:mm") + private LocalTime endTime; - public static PossibleDateRequestDto toDto(PossibleDate possibleDate){ - return PossibleDateRequestDto.builder() - .date(possibleDate.getDate()) - .startTime(possibleDate.getStartTime()) - .endTime(possibleDate.getEndTime()) - .build(); - } + public static PossibleDateRequestDto toDto(PossibleDate possibleDate) { + return PossibleDateRequestDto.builder() + .date(possibleDate.getDate()) + .startTime(possibleDate.getStartTime()) + .endTime(possibleDate.getEndTime()) + .build(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/ResponseMentorListInfo.java b/src/main/java/com/soongsil/CoffeeChat/dto/ResponseMentorListInfo.java index 0ba588b..a406aea 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/ResponseMentorListInfo.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/ResponseMentorListInfo.java @@ -1,33 +1,34 @@ package com.soongsil.CoffeeChat.dto; +import java.util.ArrayList; +import java.util.List; + import com.soongsil.CoffeeChat.entity.Club; import com.soongsil.CoffeeChat.entity.Mentor; import com.soongsil.CoffeeChat.entity.User; -import lombok.Builder; -import java.util.ArrayList; -import java.util.List; +import lombok.Builder; @Builder public class ResponseMentorListInfo { - private String picture; - private String mentorName; - private List clubName; - private String field; - private String username; + private String picture; + private String mentorName; + private List clubName; + private String field; + private String username; - public static ResponseMentorListInfo toDto(Mentor mentor, User user){ - List clubList=mentor.getClubs(); - List clubNameList=new ArrayList<>(); - for(Club club:clubList){ - clubNameList.add(club.getName()); - } - return ResponseMentorListInfo.builder() - .picture(mentor.getPicture()) - .mentorName(user.getName()) - .clubName(clubNameList) - .field(mentor.getField()) - .username(user.getUsername()) - .build(); - } + public static ResponseMentorListInfo toDto(Mentor mentor, User user) { + List clubList = mentor.getClubs(); + List clubNameList = new ArrayList<>(); + for (Club club : clubList) { + clubNameList.add(club.getName()); + } + return ResponseMentorListInfo.builder() + .picture(mentor.getPicture()) + .mentorName(user.getName()) + .clubName(clubNameList) + .field(mentor.getField()) + .username(user.getUsername()) + .build(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/dto/UserDTO.java b/src/main/java/com/soongsil/CoffeeChat/dto/UserDTO.java index 7b58e51..3f8df13 100644 --- a/src/main/java/com/soongsil/CoffeeChat/dto/UserDTO.java +++ b/src/main/java/com/soongsil/CoffeeChat/dto/UserDTO.java @@ -6,7 +6,7 @@ @Getter @Setter public class UserDTO { - private String role; - private String name; - private String username; //스프링 서버 내의 유저 아이디 + private String role; + private String name; + private String username; //스프링 서버 내의 유저 아이디 } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/Application.java b/src/main/java/com/soongsil/CoffeeChat/entity/Application.java index d6fa080..ad0d14d 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/Application.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/Application.java @@ -1,6 +1,12 @@ package com.soongsil.CoffeeChat.entity; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; import lombok.Getter; import lombok.Setter; @@ -8,28 +14,28 @@ @Getter @Setter public class Application { - @Column(name = "application_id") - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Column(name = "application_id") + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @ManyToOne - @JoinColumn(name = "mentor_id") - private Mentor mentor; + @ManyToOne + @JoinColumn(name = "mentor_id") + private Mentor mentor; - @ManyToOne - @JoinColumn(name = "mentee_id") - private Mentee mentee; + @ManyToOne + @JoinColumn(name = "mentee_id") + private Mentee mentee; - @Column - private String date; + @Column + private String date; - @Column - private String time; + @Column + private String time; - @Column - private String question; + @Column + private String question; - @Column - private boolean accept; + @Column + private boolean accept; } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/Club.java b/src/main/java/com/soongsil/CoffeeChat/entity/Club.java index 2a7bdbb..8431c4f 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/Club.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/Club.java @@ -1,6 +1,12 @@ package com.soongsil.CoffeeChat.entity; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; import lombok.Getter; import lombok.Setter; @@ -8,18 +14,18 @@ @Getter @Setter public class Club { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name="club_id") - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "club_id") + private Long id; - @ManyToOne - @JoinColumn(name = "mentor_id") - private Mentor mentor; + @ManyToOne + @JoinColumn(name = "mentor_id") + private Mentor mentor; - @Column - private String name; + @Column + private String name; - @Column - private String position; + @Column + private String position; } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/Mentee.java b/src/main/java/com/soongsil/CoffeeChat/entity/Mentee.java index 9afa7c9..39038f2 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/Mentee.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/Mentee.java @@ -1,62 +1,71 @@ package com.soongsil.CoffeeChat.entity; -import com.soongsil.CoffeeChat.dto.CreateMenteeRequest; -import jakarta.persistence.*; -import lombok.*; - import java.util.HashSet; import java.util.Set; +import com.soongsil.CoffeeChat.dto.CreateMenteeRequest; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.NoArgsConstructor; + @Entity @NoArgsConstructor @AllArgsConstructor @Builder public class Mentee { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "mentee_id") - private Long id; - - @Column - private String picture; - //TODO: aws파지면 사진처리 해줘야됨 - - @Column(name = "phone_num") - private String phoneNum; - - @Column - private String birth; - - @Column - private int grade; - - @Column - private String major; - - @Column - private String memo; - - @OneToMany(mappedBy = "mentee", cascade = CascadeType.ALL, orphanRemoval = true) - @Builder.Default - private Set applications = new HashSet<>(); - - @Builder - public Mentee(String phoneNum, String birth, int grade, String major, String memo){ - this.phoneNum=phoneNum; - this.birth=birth; - this.grade=grade; - this.major=major; - this.memo=memo; - } - - public static Mentee from(CreateMenteeRequest dto){ - return Mentee.builder() - .phoneNum(dto.getPhoneNum()) - .birth(dto.getBirth()) - .grade(dto.getGrade()) - .major(dto.getMajor()) - .memo(dto.getMemo()) - .build(); - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "mentee_id") + private Long id; + + @Column + private String picture; + //TODO: aws파지면 사진처리 해줘야됨 + + @Column(name = "phone_num") + private String phoneNum; + + @Column + private String birth; + + @Column + private int grade; + + @Column + private String major; + + @Column + private String memo; + + @OneToMany(mappedBy = "mentee", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private Set applications = new HashSet<>(); + + @Builder + public Mentee(String phoneNum, String birth, int grade, String major, String memo) { + this.phoneNum = phoneNum; + this.birth = birth; + this.grade = grade; + this.major = major; + this.memo = memo; + } + + public static Mentee from(CreateMenteeRequest dto) { + return Mentee.builder() + .phoneNum(dto.getPhoneNum()) + .birth(dto.getBirth()) + .grade(dto.getGrade()) + .major(dto.getMajor()) + .memo(dto.getMemo()) + .build(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/Mentor.java b/src/main/java/com/soongsil/CoffeeChat/entity/Mentor.java index b8ba2a1..cdb5944 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/Mentor.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/Mentor.java @@ -1,14 +1,24 @@ package com.soongsil.CoffeeChat.entity; -import com.soongsil.CoffeeChat.dto.CreateMentorRequest; -import jakarta.persistence.*; -import lombok.*; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; +import com.soongsil.CoffeeChat.dto.CreateMentorRequest; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + @Entity @NoArgsConstructor @AllArgsConstructor @@ -16,56 +26,56 @@ @Getter //@DiscriminatorValue("mentor") //@PrimaryKeyJoinColumn(name = "mentor_id") -public class Mentor{ - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name = "mentor_id") - private Long id; +public class Mentor { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "mentor_id") + private Long id; - @Column - private String picture; - //TODO: aws파지면 사진처리 해줘야됨 + @Column + private String picture; + //TODO: aws파지면 사진처리 해줘야됨 - @Column(name = "phone_num") - private String phoneNum; + @Column(name = "phone_num") + private String phoneNum; - @Column - private String birth; + @Column + private String birth; - @Column - private String part; + @Column + private String part; - @Column - private String field; + @Column + private String field; - @Builder.Default - @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) - private Set applications = new HashSet<>(); + @Builder.Default + @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) + private Set applications = new HashSet<>(); - @Builder.Default - @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) - private List clubs = new ArrayList<>(); + @Builder.Default + @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) + private List clubs = new ArrayList<>(); - @Builder.Default - @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) - private Set possibleDates = new HashSet<>(); + @Builder.Default + @OneToMany(mappedBy = "mentor", cascade = CascadeType.ALL, orphanRemoval = true) + private Set possibleDates = new HashSet<>(); + @Builder + public Mentor(String phoneNum, String birth, String part) { + this.phoneNum = phoneNum; + this.birth = birth; + this.part = part; + } - @Builder - public Mentor(String phoneNum, String birth, String part){ - this.phoneNum=phoneNum; - this.birth=birth; - this.part=part; - } - public static Mentor from(CreateMentorRequest dto){ - return Mentor.builder() - .phoneNum(dto.getPhoneNum()) - .birth(dto.getBirth()) - .part(dto.getPart()) - .build(); - } + public static Mentor from(CreateMentorRequest dto) { + return Mentor.builder() + .phoneNum(dto.getPhoneNum()) + .birth(dto.getBirth()) + .part(dto.getPart()) + .build(); + } - public void addPossibleDate(PossibleDate possibleDate){ - this.possibleDates.add(possibleDate); - } + public void addPossibleDate(PossibleDate possibleDate) { + this.possibleDates.add(possibleDate); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/PossibleDate.java b/src/main/java/com/soongsil/CoffeeChat/entity/PossibleDate.java index 736c558..2ff3825 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/PossibleDate.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/PossibleDate.java @@ -1,12 +1,23 @@ package com.soongsil.CoffeeChat.entity; +import java.time.LocalDate; +import java.time.LocalTime; + import com.fasterxml.jackson.annotation.JsonFormat; import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; -import jakarta.persistence.*; -import lombok.*; -import java.time.LocalDate; -import java.time.LocalTime; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; @Entity @Builder @@ -14,34 +25,34 @@ @AllArgsConstructor @Getter public class PossibleDate { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "possible_date_id") - private Long id; - - @Setter - @ManyToOne - @JoinColumn(name = "mentor_id") - private Mentor mentor; - - @JsonFormat(pattern = "yyyy-MM-dd") - LocalDate date; - - @JsonFormat(pattern = "HH:mm") //datetimeformat은 ss까지 전부 다 받아야 오류안남 - LocalTime startTime; - - @JsonFormat(pattern = "HH:mm") - LocalTime endTime; - - @Column - private boolean apply; - - public static PossibleDate from(PossibleDateRequestDto dto){ - return PossibleDate.builder() - .date(dto.getDate()) - .startTime(dto.getStartTime()) - .endTime(dto.getEndTime()) - .apply(false) - .build(); - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "possible_date_id") + private Long id; + + @Setter + @ManyToOne + @JoinColumn(name = "mentor_id") + private Mentor mentor; + + @JsonFormat(pattern = "yyyy-MM-dd") + LocalDate date; + + @JsonFormat(pattern = "HH:mm") //datetimeformat은 ss까지 전부 다 받아야 오류안남 + LocalTime startTime; + + @JsonFormat(pattern = "HH:mm") + LocalTime endTime; + + @Column + private boolean apply; + + public static PossibleDate from(PossibleDateRequestDto dto) { + return PossibleDate.builder() + .date(dto.getDate()) + .startTime(dto.getStartTime()) + .endTime(dto.getEndTime()) + .apply(false) + .build(); + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/Refresh.java b/src/main/java/com/soongsil/CoffeeChat/entity/Refresh.java index d01f06e..4223d2c 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/Refresh.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/Refresh.java @@ -11,11 +11,11 @@ @Getter @Setter public class Refresh { //사용 가능 Refresh토큰 DB저장용 - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - private String username; //어떤 유저의 토큰인지 구분자 - private String refresh; //토큰 - private String expiration; //만료시간 + private String username; //어떤 유저의 토큰인지 구분자 + private String refresh; //토큰 + private String expiration; //만료시간 } diff --git a/src/main/java/com/soongsil/CoffeeChat/entity/User.java b/src/main/java/com/soongsil/CoffeeChat/entity/User.java index 1ce158d..88f9de8 100644 --- a/src/main/java/com/soongsil/CoffeeChat/entity/User.java +++ b/src/main/java/com/soongsil/CoffeeChat/entity/User.java @@ -1,9 +1,15 @@ package com.soongsil.CoffeeChat.entity; -import jakarta.persistence.*; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; import lombok.Getter; import lombok.Setter; -import lombok.experimental.SuperBuilder; @Entity @Getter @@ -11,31 +17,31 @@ //@Inheritance(strategy = InheritanceType.JOINED) //자식 : Mentor, Mentee //@DiscriminatorColumn // 하위 테이블의 구분 컬럼 생성(default = DTYPE) public class User { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "user_id") - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id") + private Long id; - @Column - private String username; + @Column + private String username; - @Column - private String name; + @Column + private String name; - @Column - private String email; + @Column + private String email; - @Column - private String role; + @Column + private String role; -// @Column -// private String picture; + // @Column + // private String picture; - @OneToOne(cascade = CascadeType.ALL) - @JoinColumn(name="user_mentor", referencedColumnName = "mentor_id") - private Mentor mentor; + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "user_mentor", referencedColumnName = "mentor_id") + private Mentor mentor; - @OneToOne(cascade = CascadeType.ALL) - @JoinColumn(name="user_mentee", referencedColumnName = "mentee_id") - private Mentee mentee; + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "user_mentee", referencedColumnName = "mentee_id") + private Mentee mentee; } diff --git a/src/main/java/com/soongsil/CoffeeChat/enums/RequestUri.java b/src/main/java/com/soongsil/CoffeeChat/enums/RequestUri.java index 4b894f0..4667172 100644 --- a/src/main/java/com/soongsil/CoffeeChat/enums/RequestUri.java +++ b/src/main/java/com/soongsil/CoffeeChat/enums/RequestUri.java @@ -1,12 +1,12 @@ package com.soongsil.CoffeeChat.enums; public class RequestUri { - private static final String prefix = "/api/v1"; - public static final String APPLICATION_URI = prefix + "/application"; - public static final String CLUB_URI = prefix + "/club"; - public static final String MENTEE_URI = prefix + "/mentee"; - public static final String MENTOR_URI = prefix + "/mentor"; - public static final String POSSIBLEDATE_URI = prefix + "/possibleDate"; - public static final String REFRESH_URI=prefix+"/refresh"; - public static final String USER_URI=prefix+"/user"; -} \ No newline at end of file + private static final String prefix = "/api/v1"; + public static final String APPLICATION_URI = prefix + "/application"; + public static final String CLUB_URI = prefix + "/club"; + public static final String MENTEE_URI = prefix + "/mentee"; + public static final String MENTOR_URI = prefix + "/mentor"; + public static final String POSSIBLEDATE_URI = prefix + "/possibleDate"; + public static final String REFRESH_URI = prefix + "/refresh"; + public static final String USER_URI = prefix + "/user"; +} diff --git a/src/main/java/com/soongsil/CoffeeChat/repository/MenteeRepository.java b/src/main/java/com/soongsil/CoffeeChat/repository/MenteeRepository.java index 0dff445..5156845 100644 --- a/src/main/java/com/soongsil/CoffeeChat/repository/MenteeRepository.java +++ b/src/main/java/com/soongsil/CoffeeChat/repository/MenteeRepository.java @@ -1,8 +1,9 @@ package com.soongsil.CoffeeChat.repository; -import com.soongsil.CoffeeChat.entity.Mentee; import org.springframework.data.jpa.repository.JpaRepository; +import com.soongsil.CoffeeChat.entity.Mentee; + public interface MenteeRepository extends JpaRepository { } diff --git a/src/main/java/com/soongsil/CoffeeChat/repository/MentorRepository.java b/src/main/java/com/soongsil/CoffeeChat/repository/MentorRepository.java index ece81ad..66790c0 100644 --- a/src/main/java/com/soongsil/CoffeeChat/repository/MentorRepository.java +++ b/src/main/java/com/soongsil/CoffeeChat/repository/MentorRepository.java @@ -1,12 +1,13 @@ package com.soongsil.CoffeeChat.repository; -import com.soongsil.CoffeeChat.entity.Mentor; +import java.util.List; + import org.springframework.data.jpa.repository.JpaRepository; -import java.util.List; +import com.soongsil.CoffeeChat.entity.Mentor; public interface MentorRepository extends JpaRepository { - //Mentor findByUsername(String username); 상속시 사용가능 + //Mentor findByUsername(String username); 상속시 사용가능 - List findAllByPart(String part); + List findAllByPart(String part); } diff --git a/src/main/java/com/soongsil/CoffeeChat/repository/PossibleDateRepository.java b/src/main/java/com/soongsil/CoffeeChat/repository/PossibleDateRepository.java index 659cb2c..ed8ded8 100644 --- a/src/main/java/com/soongsil/CoffeeChat/repository/PossibleDateRepository.java +++ b/src/main/java/com/soongsil/CoffeeChat/repository/PossibleDateRepository.java @@ -1,7 +1,8 @@ package com.soongsil.CoffeeChat.repository; -import com.soongsil.CoffeeChat.entity.PossibleDate; import org.springframework.data.jpa.repository.JpaRepository; +import com.soongsil.CoffeeChat.entity.PossibleDate; + public interface PossibleDateRepository extends JpaRepository { } diff --git a/src/main/java/com/soongsil/CoffeeChat/repository/RefreshRepository.java b/src/main/java/com/soongsil/CoffeeChat/repository/RefreshRepository.java index 76c47a6..467bc65 100644 --- a/src/main/java/com/soongsil/CoffeeChat/repository/RefreshRepository.java +++ b/src/main/java/com/soongsil/CoffeeChat/repository/RefreshRepository.java @@ -1,12 +1,14 @@ package com.soongsil.CoffeeChat.repository; +import org.springframework.data.jpa.repository.JpaRepository; + import com.soongsil.CoffeeChat.entity.Refresh; + import jakarta.transaction.Transactional; -import org.springframework.data.jpa.repository.JpaRepository; public interface RefreshRepository extends JpaRepository { - Boolean existsByRefresh(String refresh); + Boolean existsByRefresh(String refresh); - @Transactional - void deleteByRefresh(String refresh); + @Transactional + void deleteByRefresh(String refresh); } diff --git a/src/main/java/com/soongsil/CoffeeChat/repository/UserRepository.java b/src/main/java/com/soongsil/CoffeeChat/repository/UserRepository.java index d85412f..2143cd8 100644 --- a/src/main/java/com/soongsil/CoffeeChat/repository/UserRepository.java +++ b/src/main/java/com/soongsil/CoffeeChat/repository/UserRepository.java @@ -1,13 +1,12 @@ package com.soongsil.CoffeeChat.repository; -import com.soongsil.CoffeeChat.entity.Mentor; -import com.soongsil.CoffeeChat.entity.User; import org.springframework.data.jpa.repository.JpaRepository; -import java.util.Optional; +import com.soongsil.CoffeeChat.entity.Mentor; +import com.soongsil.CoffeeChat.entity.User; public interface UserRepository extends JpaRepository { - User findByUsername(String username); + User findByUsername(String username); - User findByMentor(Mentor mentor); + User findByMentor(Mentor mentor); } diff --git a/src/main/java/com/soongsil/CoffeeChat/service/CustomOAuth2UserService.java b/src/main/java/com/soongsil/CoffeeChat/service/CustomOAuth2UserService.java index e938722..b6c5445 100644 --- a/src/main/java/com/soongsil/CoffeeChat/service/CustomOAuth2UserService.java +++ b/src/main/java/com/soongsil/CoffeeChat/service/CustomOAuth2UserService.java @@ -1,80 +1,81 @@ package com.soongsil.CoffeeChat.service; +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.stereotype.Service; + +import com.soongsil.CoffeeChat.dto.CustomOAuth2User; import com.soongsil.CoffeeChat.dto.GoogleResponse; import com.soongsil.CoffeeChat.dto.NaverResponse; import com.soongsil.CoffeeChat.dto.OAuth2Response; import com.soongsil.CoffeeChat.dto.UserDTO; -import com.soongsil.CoffeeChat.dto.CustomOAuth2User; import com.soongsil.CoffeeChat.entity.User; import com.soongsil.CoffeeChat.repository.UserRepository; + import jakarta.transaction.Transactional; -import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; -import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; -import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.stereotype.Service; @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { - private final UserRepository userRepository; - public CustomOAuth2UserService(UserRepository userRepository){ - this.userRepository=userRepository; - } - - - //리소스 서버에서 제공되는 유저정보 가져오기 - @Override - @Transactional - public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { - //리소스서버로부터 유저 데이터를 받아 소셜 형식에 맞게 데이터 전처리(DTO로) - OAuth2User oAuth2User = super.loadUser(userRequest); - System.out.println("oAuth2User = " + oAuth2User); - String registrationId = userRequest.getClientRegistration().getRegistrationId(); - OAuth2Response oAuth2Response = null; - if (registrationId.equals("naver")) { - - oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); - } else if (registrationId.equals("google")) { - - oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); - } else { - - return null; - } - - //리소스 서버에서 발급 받은 정보로 사용자를 특정할 아이디값을 만듬 - String username = oAuth2Response.getProvider()+" "+oAuth2Response.getProviderId(); - - //유저가 DB에 있는지 확인 후 없으면 새로 저장 - User existData=userRepository.findByUsername(username); - if(existData==null){ - User user=new User(); - user.setUsername(username); - user.setEmail(oAuth2Response.getEmail()); - user.setName(oAuth2Response.getName()); - user.setRole("ROLE_USER"); - - userRepository.save(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setUsername(username); - userDTO.setName(oAuth2Response.getName()); - userDTO.setRole("ROLE_USER"); - - return new CustomOAuth2User(userDTO); - } - else{ //데이터가 이미 존재하면 업데이트 후 OAuth2User객체로 반환 - //소셜에서 로그인마다 업데이트를 선호하므로 로그인마다 DB 업데이트 진행 - existData.setEmail(oAuth2Response.getEmail()); - existData.setName(oAuth2Response.getName()); - userRepository.save(existData); - - UserDTO userDTO=new UserDTO(); - userDTO.setUsername(existData.getUsername()); - userDTO.setName(oAuth2Response.getName()); - userDTO.setRole(existData.getRole()); - return new CustomOAuth2User(userDTO); - } - - } + private final UserRepository userRepository; + + public CustomOAuth2UserService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + //리소스 서버에서 제공되는 유저정보 가져오기 + @Override + @Transactional + public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { + //리소스서버로부터 유저 데이터를 받아 소셜 형식에 맞게 데이터 전처리(DTO로) + OAuth2User oAuth2User = super.loadUser(userRequest); + System.out.println("oAuth2User = " + oAuth2User); + String registrationId = userRequest.getClientRegistration().getRegistrationId(); + OAuth2Response oAuth2Response = null; + if (registrationId.equals("naver")) { + + oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); + } else if (registrationId.equals("google")) { + + oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); + } else { + + return null; + } + + //리소스 서버에서 발급 받은 정보로 사용자를 특정할 아이디값을 만듬 + String username = oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId(); + + //유저가 DB에 있는지 확인 후 없으면 새로 저장 + User existData = userRepository.findByUsername(username); + if (existData == null) { + User user = new User(); + user.setUsername(username); + user.setEmail(oAuth2Response.getEmail()); + user.setName(oAuth2Response.getName()); + user.setRole("ROLE_USER"); + + userRepository.save(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setUsername(username); + userDTO.setName(oAuth2Response.getName()); + userDTO.setRole("ROLE_USER"); + + return new CustomOAuth2User(userDTO); + } else { //데이터가 이미 존재하면 업데이트 후 OAuth2User객체로 반환 + //소셜에서 로그인마다 업데이트를 선호하므로 로그인마다 DB 업데이트 진행 + existData.setEmail(oAuth2Response.getEmail()); + existData.setName(oAuth2Response.getName()); + userRepository.save(existData); + + UserDTO userDTO = new UserDTO(); + userDTO.setUsername(existData.getUsername()); + userDTO.setName(oAuth2Response.getName()); + userDTO.setRole(existData.getRole()); + return new CustomOAuth2User(userDTO); + } + + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/service/MentorService.java b/src/main/java/com/soongsil/CoffeeChat/service/MentorService.java index 072ccb5..c6d714b 100644 --- a/src/main/java/com/soongsil/CoffeeChat/service/MentorService.java +++ b/src/main/java/com/soongsil/CoffeeChat/service/MentorService.java @@ -1,5 +1,12 @@ package com.soongsil.CoffeeChat.service; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.springframework.stereotype.Service; + import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; import com.soongsil.CoffeeChat.dto.ResponseMentorListInfo; import com.soongsil.CoffeeChat.entity.Mentor; @@ -7,44 +14,42 @@ import com.soongsil.CoffeeChat.entity.User; import com.soongsil.CoffeeChat.repository.MentorRepository; import com.soongsil.CoffeeChat.repository.UserRepository; -import org.springframework.stereotype.Service; - -import java.util.*; @Service public class MentorService { - private final MentorRepository mentorRepository; - private final UserRepository userRepository; - public MentorService(MentorRepository mentorRepository, - UserRepository userRepository){ - this.mentorRepository=mentorRepository; - this.userRepository=userRepository; - } - //사용되는 공통 private method - private List findMentorListByPart(String part){ - return mentorRepository.findAllByPart(part); - } - - - public List getMentorDtoListByPart(String part){ - List mentorList=findMentorListByPart(part); - List dtoList=new ArrayList<>(); - for(Mentor mentor : mentorList){ - User user=userRepository.findByMentor(mentor); - dtoList.add(ResponseMentorListInfo.toDto(mentor,user)); - } - return dtoList; - } - - public List findPossibleDateListByMentor(String username) { - User user= userRepository.findByUsername(username); - Mentor mentor=user.getMentor(); - Set possibleDateSet=mentor.getPossibleDates(); - Iterator iter= possibleDateSet.iterator(); - List dtoList=new ArrayList<>(); - while(iter.hasNext()){ - dtoList.add(PossibleDateRequestDto.toDto(iter.next())); - } - return dtoList; - } + private final MentorRepository mentorRepository; + private final UserRepository userRepository; + + public MentorService(MentorRepository mentorRepository, + UserRepository userRepository) { + this.mentorRepository = mentorRepository; + this.userRepository = userRepository; + } + + //사용되는 공통 private method + private List findMentorListByPart(String part) { + return mentorRepository.findAllByPart(part); + } + + public List getMentorDtoListByPart(String part) { + List mentorList = findMentorListByPart(part); + List dtoList = new ArrayList<>(); + for (Mentor mentor : mentorList) { + User user = userRepository.findByMentor(mentor); + dtoList.add(ResponseMentorListInfo.toDto(mentor, user)); + } + return dtoList; + } + + public List findPossibleDateListByMentor(String username) { + User user = userRepository.findByUsername(username); + Mentor mentor = user.getMentor(); + Set possibleDateSet = mentor.getPossibleDates(); + Iterator iter = possibleDateSet.iterator(); + List dtoList = new ArrayList<>(); + while (iter.hasNext()) { + dtoList.add(PossibleDateRequestDto.toDto(iter.next())); + } + return dtoList; + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/service/PossibleDateService.java b/src/main/java/com/soongsil/CoffeeChat/service/PossibleDateService.java index aa19aba..8457ba7 100644 --- a/src/main/java/com/soongsil/CoffeeChat/service/PossibleDateService.java +++ b/src/main/java/com/soongsil/CoffeeChat/service/PossibleDateService.java @@ -1,27 +1,30 @@ package com.soongsil.CoffeeChat.service; +import org.springframework.stereotype.Service; + import com.soongsil.CoffeeChat.dto.PossibleDateRequestDto; import com.soongsil.CoffeeChat.entity.Mentor; import com.soongsil.CoffeeChat.entity.PossibleDate; import com.soongsil.CoffeeChat.entity.User; import com.soongsil.CoffeeChat.repository.PossibleDateRepository; import com.soongsil.CoffeeChat.repository.UserRepository; + import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class PossibleDateService { - private final PossibleDateRepository possibleDateRepository; - private final UserRepository userRepository; - public PossibleDate createPossibleDate(PossibleDateRequestDto dto, - String username){ - User user=userRepository.findByUsername(username); - Mentor mentor=user.getMentor(); - PossibleDate possibleDate=PossibleDate.from(dto); - possibleDate.setMentor(mentor); - mentor.addPossibleDate(possibleDate); - possibleDateRepository.save(possibleDate); - return possibleDate; - } + private final PossibleDateRepository possibleDateRepository; + private final UserRepository userRepository; + + public PossibleDate createPossibleDate(PossibleDateRequestDto dto, + String username) { + User user = userRepository.findByUsername(username); + Mentor mentor = user.getMentor(); + PossibleDate possibleDate = PossibleDate.from(dto); + possibleDate.setMentor(mentor); + mentor.addPossibleDate(possibleDate); + possibleDateRepository.save(possibleDate); + return possibleDate; + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/service/RefreshTokenService.java b/src/main/java/com/soongsil/CoffeeChat/service/RefreshTokenService.java index d645d92..dca4a0b 100644 --- a/src/main/java/com/soongsil/CoffeeChat/service/RefreshTokenService.java +++ b/src/main/java/com/soongsil/CoffeeChat/service/RefreshTokenService.java @@ -1,111 +1,114 @@ package com.soongsil.CoffeeChat.service; +import java.util.Date; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + import com.soongsil.CoffeeChat.config.jwt.JWTUtil; import com.soongsil.CoffeeChat.entity.Refresh; import com.soongsil.CoffeeChat.repository.RefreshRepository; + import io.jsonwebtoken.ExpiredJwtException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -import java.util.Date; @Service public class RefreshTokenService { - private final JWTUtil jwtUtil; - private final RefreshRepository refreshRepository; - public RefreshTokenService(JWTUtil jwtUtil, RefreshRepository refreshRepository){ - this.jwtUtil=jwtUtil; - this.refreshRepository=refreshRepository; - } + private final JWTUtil jwtUtil; + private final RefreshRepository refreshRepository; + + public RefreshTokenService(JWTUtil jwtUtil, RefreshRepository refreshRepository) { + this.jwtUtil = jwtUtil; + this.refreshRepository = refreshRepository; + } - private Cookie createCookie(String key, String value) { + private Cookie createCookie(String key, String value) { - Cookie cookie = new Cookie(key, value); - cookie.setMaxAge(24*60*60); - //cookie.setSecure(true); - //cookie.setPath("/"); - cookie.setHttpOnly(true); + Cookie cookie = new Cookie(key, value); + cookie.setMaxAge(24 * 60 * 60); + //cookie.setSecure(true); + //cookie.setPath("/"); + cookie.setHttpOnly(true); - return cookie; - } + return cookie; + } - private void addRefreshEntity(String username, String refresh, Long expiredMs) { //Refresh객체를 DB에 저장(블랙리스트관리) + private void addRefreshEntity(String username, String refresh, Long expiredMs) { //Refresh객체를 DB에 저장(블랙리스트관리) - Date date = new Date(System.currentTimeMillis() + expiredMs); + Date date = new Date(System.currentTimeMillis() + expiredMs); - Refresh refreshEntity = new Refresh(); - refreshEntity.setUsername(username); - refreshEntity.setRefresh(refresh); - refreshEntity.setExpiration(date.toString()); + Refresh refreshEntity = new Refresh(); + refreshEntity.setUsername(username); + refreshEntity.setRefresh(refresh); + refreshEntity.setExpiration(date.toString()); - refreshRepository.save(refreshEntity); - } + refreshRepository.save(refreshEntity); + } - public ResponseEntity reissueByRefreshToken(HttpServletRequest request, HttpServletResponse response){ - //get refresh token - String refresh = null; - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { + public ResponseEntity reissueByRefreshToken(HttpServletRequest request, HttpServletResponse response) { + //get refresh token + String refresh = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { - if (cookie.getName().equals("refresh")) { + if (cookie.getName().equals("refresh")) { - refresh = cookie.getValue(); - } - } + refresh = cookie.getValue(); + } + } - if (refresh == null) { + if (refresh == null) { - //response status code 400 (refresh토큰이 들어오지 않음) - return new ResponseEntity<>("refresh token null", HttpStatus.BAD_REQUEST); - } + //response status code 400 (refresh토큰이 들어오지 않음) + return new ResponseEntity<>("refresh token null", HttpStatus.BAD_REQUEST); + } - //expired check - JWTUtil jwtUtil = null; - try { - jwtUtil.isExpired(refresh); - } catch (ExpiredJwtException e) { + //expired check + JWTUtil jwtUtil = null; + try { + jwtUtil.isExpired(refresh); + } catch (ExpiredJwtException e) { - //response status code 400 (refresh 토큰이 만료됨) - return new ResponseEntity<>("refresh token expired", HttpStatus.BAD_REQUEST); - } + //response status code 400 (refresh 토큰이 만료됨) + return new ResponseEntity<>("refresh token expired", HttpStatus.BAD_REQUEST); + } - // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) - String category = jwtUtil.getCategory(refresh); + // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) + String category = jwtUtil.getCategory(refresh); - if (!category.equals("refresh")) { + if (!category.equals("refresh")) { - //response status code 400 (들어온 토큰이 refresh토큰이 아님) - return new ResponseEntity<>("invalid refresh token", HttpStatus.BAD_REQUEST); - } + //response status code 400 (들어온 토큰이 refresh토큰이 아님) + return new ResponseEntity<>("invalid refresh token", HttpStatus.BAD_REQUEST); + } - //DB에 저장되어 있는지 확인 - Boolean isExist = refreshRepository.existsByRefresh(refresh); - if (!isExist) { + //DB에 저장되어 있는지 확인 + Boolean isExist = refreshRepository.existsByRefresh(refresh); + if (!isExist) { - //response body status code 400 (들어올 refresh토큰이 내 DB에 저장된 목록에 없음) - return new ResponseEntity<>("invalid refresh token", HttpStatus.BAD_REQUEST); - } + //response body status code 400 (들어올 refresh토큰이 내 DB에 저장된 목록에 없음) + return new ResponseEntity<>("invalid refresh token", HttpStatus.BAD_REQUEST); + } - String username = jwtUtil.getUsername(refresh); - String role = jwtUtil.getRole(refresh); + String username = jwtUtil.getUsername(refresh); + String role = jwtUtil.getRole(refresh); - //make new JWT - String newAccess = jwtUtil.createJwt("access", username, role, 600000L); - String newRefresh = jwtUtil.createJwt("refresh", username, role, 86400000L); + //make new JWT + String newAccess = jwtUtil.createJwt("access", username, role, 600000L); + String newRefresh = jwtUtil.createJwt("refresh", username, role, 86400000L); - //Refresh 토큰 저장 DB에 기존의 Refresh 토큰 삭제 후 새 Refresh 토큰 저장 - refreshRepository.deleteByRefresh(refresh); - addRefreshEntity(username, newRefresh, 86400000L); + //Refresh 토큰 저장 DB에 기존의 Refresh 토큰 삭제 후 새 Refresh 토큰 저장 + refreshRepository.deleteByRefresh(refresh); + addRefreshEntity(username, newRefresh, 86400000L); - //response - response.setHeader("access", newAccess); - response.addCookie(createCookie("refresh", newRefresh)); + //response + response.setHeader("access", newAccess); + response.addCookie(createCookie("refresh", newRefresh)); - return new ResponseEntity<>(HttpStatus.OK); + return new ResponseEntity<>(HttpStatus.OK); - } + } } diff --git a/src/main/java/com/soongsil/CoffeeChat/service/UserService.java b/src/main/java/com/soongsil/CoffeeChat/service/UserService.java index 2d1b453..c1fe9ab 100644 --- a/src/main/java/com/soongsil/CoffeeChat/service/UserService.java +++ b/src/main/java/com/soongsil/CoffeeChat/service/UserService.java @@ -1,5 +1,7 @@ package com.soongsil.CoffeeChat.service; +import org.springframework.stereotype.Service; + import com.soongsil.CoffeeChat.dto.CreateMenteeRequest; import com.soongsil.CoffeeChat.dto.CreateMentorRequest; import com.soongsil.CoffeeChat.entity.Mentee; @@ -8,30 +10,30 @@ import com.soongsil.CoffeeChat.repository.MenteeRepository; import com.soongsil.CoffeeChat.repository.MentorRepository; import com.soongsil.CoffeeChat.repository.UserRepository; + import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class UserService { - private final MentorRepository mentorRepository; - private final MenteeRepository menteeRepository; - private final UserRepository userRepository; + private final MentorRepository mentorRepository; + private final MenteeRepository menteeRepository; + private final UserRepository userRepository; - @Transactional - public Mentor saveMentorInformation(String username, CreateMentorRequest dto){ - User user= userRepository.findByUsername(username); - user.setRole("ROLE_MENTEE"); - Mentor mentor=Mentor.from(dto); - return mentorRepository.save(mentor); - } + @Transactional + public Mentor saveMentorInformation(String username, CreateMentorRequest dto) { + User user = userRepository.findByUsername(username); + user.setRole("ROLE_MENTEE"); + Mentor mentor = Mentor.from(dto); + return mentorRepository.save(mentor); + } - @Transactional - public Mentee saveMenteeInformation(String username, CreateMenteeRequest dto){ - User user= userRepository.findByUsername(username); - user.setRole("ROLE_MENTOR"); - Mentee mentee=Mentee.from(dto); - return menteeRepository.save(mentee); - } + @Transactional + public Mentee saveMenteeInformation(String username, CreateMenteeRequest dto) { + User user = userRepository.findByUsername(username); + user.setRole("ROLE_MENTOR"); + Mentee mentee = Mentee.from(dto); + return menteeRepository.save(mentee); + } }