From 35bcf420f6bf542ba1d5bb774345e03af7758fe3 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Mon, 23 Sep 2024 19:59:52 +0900 Subject: [PATCH 01/13] style:[#22]-format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주석 추가,플러그인 버전 분리,중복되는 모듈 삭제 --- build.gradle | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 483de16..83f3fe2 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,18 @@ +buildscript { + ext { + spring_boot_version = '3.3.3' + spring_dependency_management = '1.1.6' + } + + repositories { + mavenCentral() + } +} + plugins { id 'java' - id 'org.springframework.boot' version '3.3.3' - id 'io.spring.dependency-management' version '1.1.6' + id 'org.springframework.boot' version "${spring_boot_version}" + id 'io.spring.dependency-management' version "${spring_dependency_management}" } group = 'com.helpmeCookies' @@ -24,14 +35,19 @@ repositories { } dependencies { + + // Spring implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + // Lombok compileOnly 'org.projectlombok:lombok' - runtimeOnly 'com.mysql:mysql-connector-j' annotationProcessor 'org.projectlombok:lombok' + + // DB + runtimeOnly 'com.mysql:mysql-connector-j' runtimeOnly 'com.h2database:h2' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher' // Spring docs implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' From 233084a886305068658ebdd5e0310096df729722 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Mon, 23 Sep 2024 20:01:01 +0900 Subject: [PATCH 02/13] style:[#22]-Add MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JWT관련 의존성 추가 --- build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build.gradle b/build.gradle index 83f3fe2..cb1381a 100644 --- a/build.gradle +++ b/build.gradle @@ -51,6 +51,11 @@ dependencies { // Spring docs implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' + + // JWT + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' + implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' } tasks.named('test') { From adcd15e405d0cc2ee66d72467f11f9fc5b0d6220 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Mon, 23 Sep 2024 20:02:24 +0900 Subject: [PATCH 03/13] style:[#22]-Add MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spring Security 관련 의존성 추가 --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index cb1381a..e58b589 100644 --- a/build.gradle +++ b/build.gradle @@ -40,6 +40,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springframework.boot:spring-boot-starter-security' // Lombok compileOnly 'org.projectlombok:lombok' From 60d69c0b385b4d5e4030323b2e8a4613e9b321c7 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 00:52:28 +0900 Subject: [PATCH 04/13] feat:[#22]-Add JWT Token --- .../java/com/helpmeCookies/global/jwt/JwtToken.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/global/jwt/JwtToken.java diff --git a/src/main/java/com/helpmeCookies/global/jwt/JwtToken.java b/src/main/java/com/helpmeCookies/global/jwt/JwtToken.java new file mode 100644 index 0000000..ca5c80e --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/jwt/JwtToken.java @@ -0,0 +1,11 @@ +package com.helpmeCookies.global.jwt; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class JwtToken { + private String accessToken; + private String refreshToken; +} \ No newline at end of file From 75bbfea33c201a90f92278f5785c843c8c65f86a Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 00:53:56 +0900 Subject: [PATCH 05/13] feat:[#22]-Add JwtProvider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JwtProvider 구현. reissueAccessToken에 TODO가 존재한다. --- .../helpmeCookies/global/jwt/JwtProvider.java | 125 ++++++++++++++++++ .../com/helpmeCookies/global/jwt/JwtUser.java | 57 ++++++++ 2 files changed, 182 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/global/jwt/JwtProvider.java create mode 100644 src/main/java/com/helpmeCookies/global/jwt/JwtUser.java diff --git a/src/main/java/com/helpmeCookies/global/jwt/JwtProvider.java b/src/main/java/com/helpmeCookies/global/jwt/JwtProvider.java new file mode 100644 index 0000000..7a1e9c2 --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/jwt/JwtProvider.java @@ -0,0 +1,125 @@ +package com.helpmeCookies.global.jwt; + +import java.security.Key; +import java.util.Date; + +import javax.crypto.spec.SecretKeySpec; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +@Component +public class JwtProvider implements InitializingBean { + @Value("${jwt.secret}") + private String secret; + @Value("${jwt.access-token-expire-time}") + private long accessTokenExpireTime; + @Value("${jwt.refresh-token-expire-time}") + private long refreshTokenExpireTime; + private Key secretKey; + private static final String ROLE = "role"; + private static final String IS_ACCESS_TOKEN = "isAccessToken"; + private static final String HEADER_PREFIX = "Bearer "; + + public String parseHeader(String header) { + if (header == null || header.isEmpty()) { + throw new IllegalArgumentException("Authorization 헤더가 없습니다."); + } else if (!header.startsWith(HEADER_PREFIX)) { + throw new IllegalArgumentException("Authorization 올바르지 않습니다."); + } else if (header.split(" ").length != 2) { + throw new IllegalArgumentException("Authorization 올바르지 않습니다."); + } + + return header.split(" ")[1]; + } + + public JwtToken createToken(JwtUser jwtUser) { + String accessToken = generateToken(jwtUser, true); + String refreshToken = generateToken(jwtUser, false); + return JwtToken.builder() + .accessToken(accessToken) + .refreshToken(refreshToken) + .build(); + } + + // 유요한 토큰인지 확인 + public boolean validateToken(String rawToken, boolean isAccessToken) { + try { + // 엑세스 토큰인지 확인 + Claims claims = extractClaims(rawToken); + if (claims.get(IS_ACCESS_TOKEN, Boolean.class) != isAccessToken) { + return false; + } + // 만료시간 확인 + return !claims.getExpiration().before(new Date()); + } catch (Exception e) { + return false; + } + } + + /** + * refreshToken을 통해, accessToken을 재발급하는 메서드. + * refreshToken의 유효성을 검사하고, isAccessToken이 true일때만 accessToken을 재발급한다. + * TODO: refreshToken을 저장하고, 저장된 refreshToken과 비교하는 로직 필요 + */ + public String reissueAccessToken(String refreshToken) { + Claims claims = extractClaims(refreshToken); + if (claims.get(IS_ACCESS_TOKEN, Boolean.class)) { + throw new IllegalArgumentException("리프레시 토큰이 아닙니다."); + } + JwtUser jwtUser = claimsToJwtUser(claims); + return generateToken(jwtUser, true); + } + + /** + * [validateToken] 이후 호출하는 메서드. + * rawToken을 통해 JwtUser를 추출한다. + * [jwtUser]는 userId와 role을 가지고 있다. 즉 JWT에 저장된 정보를 추출한다. + */ + public JwtUser getJwtUser(String rawToken) { + Claims claims = extractClaims(rawToken); + return claimsToJwtUser(claims); + } + + private JwtUser claimsToJwtUser(Claims claims) { + String userId = claims.getSubject(); + return JwtUser.of(Long.parseLong(userId)); + } + + /** + * Jwt 토큰생성 + * accessToken과 refreshToken의 다른점은 만료시간과, isAccessToken이다. + */ + private String generateToken(JwtUser jwtUser, boolean isAccessToken) { + long expireTime = isAccessToken ? accessTokenExpireTime : refreshTokenExpireTime; + Date expireDate = new Date(System.currentTimeMillis() + expireTime); + return Jwts.builder() + .signWith(secretKey) + .claim(IS_ACCESS_TOKEN, isAccessToken) + .setSubject(jwtUser.getId().toString()) + .setExpiration(expireDate) + .compact(); + } + + + private Claims extractClaims(String rawToken) { + return Jwts.parserBuilder() + .setSigningKey(secretKey) + .build() + .parseClaimsJws(rawToken) + .getBody(); + } + + /** + * HS256방식의 키를 생성한다. + */ + @Override + public void afterPropertiesSet() { + secretKey = new SecretKeySpec(secret.getBytes(), SignatureAlgorithm.HS256.getJcaName()); + } +} diff --git a/src/main/java/com/helpmeCookies/global/jwt/JwtUser.java b/src/main/java/com/helpmeCookies/global/jwt/JwtUser.java new file mode 100644 index 0000000..bc60b98 --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/jwt/JwtUser.java @@ -0,0 +1,57 @@ +package com.helpmeCookies.global.jwt; + +import java.util.Collection; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import lombok.Builder; +import lombok.Getter; + +@Builder +@Getter +public class JwtUser implements UserDetails { + private Long id; + + public static JwtUser of(Long id) { + return JwtUser.builder() + .id(id) + .build(); + } + + @Override + public Collection getAuthorities() { + return null; + } + + @Override + public String getPassword() { + return null; + } + + @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; + } + +} \ No newline at end of file From 817e4eff0ef3f179dfd5eba971ebf0e08cf4dd2f Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 00:57:00 +0900 Subject: [PATCH 06/13] feat:[#22]-Add Error Handler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JWT 토큰 관련 예외처리시 사용할 핸들러. Error 메시지에 대한 추가 구현이 남아있음. --- .../security/JwtAccessDeniedHandler.java | 32 +++++++++++++++++++ .../security/JwtAuthenticationEntryPoint.java | 29 +++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/global/security/JwtAccessDeniedHandler.java create mode 100644 src/main/java/com/helpmeCookies/global/security/JwtAuthenticationEntryPoint.java diff --git a/src/main/java/com/helpmeCookies/global/security/JwtAccessDeniedHandler.java b/src/main/java/com/helpmeCookies/global/security/JwtAccessDeniedHandler.java new file mode 100644 index 0000000..f6dde1c --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/security/JwtAccessDeniedHandler.java @@ -0,0 +1,32 @@ +package com.helpmeCookies.global.security; + +import java.io.IOException; +import java.io.PrintWriter; + +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAccessDeniedHandler implements AccessDeniedHandler { + private final ObjectMapper objectMapper; + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, + AccessDeniedException accessDeniedException) { + log.error("Token : {}", request.getHeader("Authorization")); + // TODO: 에러코드 추가 + response.setStatus(403); + } +} \ No newline at end of file diff --git a/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationEntryPoint.java b/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationEntryPoint.java new file mode 100644 index 0000000..2072bb2 --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationEntryPoint.java @@ -0,0 +1,29 @@ +package com.helpmeCookies.global.security; + +import java.io.IOException; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper objectMapper; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException, ServletException { + log.debug("Token : {}", request.getHeader("Authorization")); + response.setStatus(401); + } +} From 203326b2f23e45aa2d0249ab3c6c91baf93b360b Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 00:58:12 +0900 Subject: [PATCH 07/13] feat:[#22]-Add JwtFilter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JWT 로직을 처리할 서블릿 필터 구현. UserDetailsService 부분이 추가 구현사항으로 남아있다. --- .../security/JwtAuthenticationFilter.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/global/security/JwtAuthenticationFilter.java diff --git a/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationFilter.java b/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000..1e70986 --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/security/JwtAuthenticationFilter.java @@ -0,0 +1,54 @@ +package com.helpmeCookies.global.security; + +import java.io.IOException; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.helpmeCookies.global.jwt.JwtProvider; +import com.helpmeCookies.global.jwt.JwtUser; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@RequiredArgsConstructor +@Slf4j +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + + private static final String AUTHORIZATION_HEADER = "Authorization"; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + log.info("JwtAuthenticationFilter"); + String rawToken; + + // 토큰 추출 + try { + rawToken = jwtProvider.parseHeader(request.getHeader(AUTHORIZATION_HEADER)); + } catch (Exception e) { + filterChain.doFilter(request, response); + return; + } + + // TODO: UserDetailsService를 통해 사용자 정보를 가져와 인증을 진행한다. + if (jwtProvider.validateToken(rawToken, true)) { + JwtUser jwtUser = jwtProvider.getJwtUser(rawToken); + Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, + jwtUser.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } +} \ No newline at end of file From d12f48149a093de761bc9def9cc161b98c39ec69 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 00:59:35 +0900 Subject: [PATCH 08/13] fix:[#22]- ChangeTableName MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 주문 도메인과 테이블명이 중복. 추후 협의후 최종 수정 예정. --- src/main/java/com/helpmeCookies/user/entity/User.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/helpmeCookies/user/entity/User.java b/src/main/java/com/helpmeCookies/user/entity/User.java index 08604fb..fe51ef9 100644 --- a/src/main/java/com/helpmeCookies/user/entity/User.java +++ b/src/main/java/com/helpmeCookies/user/entity/User.java @@ -49,7 +49,7 @@ public class User { // 별도의 테이블 생성. 문자열로 저장 @ElementCollection(targetClass = HashTag.class) - @CollectionTable(name = "user_hashtags") + @CollectionTable(name = "user_hashtag") @Enumerated(EnumType.STRING) private List hashTags; } From 69122c9164bf4b1767aa94fb2a53b2500896aadd Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 01:00:12 +0900 Subject: [PATCH 09/13] feat:[#22]- add UserRepository MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JPA유저레포지토리 구현. --- .../helpmeCookies/user/repository/UserRepository.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/user/repository/UserRepository.java diff --git a/src/main/java/com/helpmeCookies/user/repository/UserRepository.java b/src/main/java/com/helpmeCookies/user/repository/UserRepository.java new file mode 100644 index 0000000..f17d2a6 --- /dev/null +++ b/src/main/java/com/helpmeCookies/user/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.helpmeCookies.user.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.helpmeCookies.user.entity.User; + +@Repository +public interface UserRepository extends JpaRepository { + +} From 4ec64194d9b7ea2afbceda84c61ca442c7a99639 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 01:00:41 +0900 Subject: [PATCH 10/13] feat:[#22]- add WebSecurityConfig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebSecurityConfig 구현. --- .../global/security/WebSecurityConfig.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/global/security/WebSecurityConfig.java diff --git a/src/main/java/com/helpmeCookies/global/security/WebSecurityConfig.java b/src/main/java/com/helpmeCookies/global/security/WebSecurityConfig.java new file mode 100644 index 0000000..1703aa0 --- /dev/null +++ b/src/main/java/com/helpmeCookies/global/security/WebSecurityConfig.java @@ -0,0 +1,68 @@ +package com.helpmeCookies.global.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +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; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.stereotype.Controller; + +import lombok.RequiredArgsConstructor; + +@EnableMethodSecurity +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor + + +@Controller +public class WebSecurityConfig { + private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; + private final JwtAccessDeniedHandler jwtAccessDeniedHandler; + private final JwtAuthenticationFilter jwtAuthenticationFilter; + + @Bean + public WebSecurityCustomizer configure() { + return (web) -> web.ignoring() + .requestMatchers("/static/**") + .requestMatchers("/test/**"); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf(AbstractHttpConfigurer::disable); + http.sessionManagement((session) -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + http.authorizeHttpRequests((authorize) -> + authorize + .requestMatchers( + "/login", "/signup", "/", "/user", + "/api/auth/**", + "/swagger-ui/**" + ).permitAll() + .anyRequest().authenticated() + ); + + http.exceptionHandling((exception) -> exception + .authenticationEntryPoint(jwtAuthenticationEntryPoint) + .accessDeniedHandler(jwtAccessDeniedHandler) + ); + + http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file From 7b2c5755193d19043fd2994cd39dd61fba4a21b6 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 01:02:25 +0900 Subject: [PATCH 11/13] feat:[#22]- add LoginController MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 임시 컨트롤러. 서비스 로직 완성후 의존성 변경이 필요하며, 이후 data.sql를 통해 진행한다. --- .../user/controller/LoginController.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/com/helpmeCookies/user/controller/LoginController.java diff --git a/src/main/java/com/helpmeCookies/user/controller/LoginController.java b/src/main/java/com/helpmeCookies/user/controller/LoginController.java new file mode 100644 index 0000000..393dba7 --- /dev/null +++ b/src/main/java/com/helpmeCookies/user/controller/LoginController.java @@ -0,0 +1,48 @@ +package com.helpmeCookies.user.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.helpmeCookies.global.jwt.JwtProvider; +import com.helpmeCookies.global.jwt.JwtToken; +import com.helpmeCookies.global.jwt.JwtUser; +import com.helpmeCookies.product.entity.HashTag; +import com.helpmeCookies.user.entity.User; +import com.helpmeCookies.user.repository.UserRepository; + +import lombok.RequiredArgsConstructor; + +@RestController +@RequiredArgsConstructor +//Todo: Swagger 추가 +public class LoginController { + private final UserRepository userRepository; + private final JwtProvider jwtProvider; + + // 임시 회원가입 url. 유저를 생성하고 jwt 토큰을 반환한다. + @GetMapping("/test/signup") + public JwtToken signup() { + User user = User.builder() + .nickname("test") + .email("test@test") + .birthdate("1999-01-01") + .address("서울시 강남구") + .phone("010-1234-5678") + .hashTags(List.of(HashTag.autumn, HashTag.winter)) + .build(); + userRepository.save(user); + return jwtProvider.createToken(JwtUser.of(user.getId())); + } + + // 임시 로그인 url. 로그인한 유저의 정보의 일부를 반환한다. + @GetMapping("/test/login") + public String login(@AuthenticationPrincipal JwtUser jwtUser) { + User user = userRepository.findById(jwtUser.getId()).get(); + return user.getEmail(); + } +} From 96fbb003e6ae3c2a157fc58c55d606cb2412de78 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 01:05:25 +0900 Subject: [PATCH 12/13] establish:[#22]- change gitignore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit yaml 파일 gitignore에 추가. --- src/main/resources/application.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 8c37f1b..2e7bc5b 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -15,4 +15,8 @@ spring: # test profile logging.level: org.hibernate: orm.jdbc.bind: trace - SQL: debug \ No newline at end of file + SQL: debug +jwt: + secret: 4099a46b-39db-4860-a61b-2ae76ea24c43 + access-token-expire-time: 1800000 # 30 minutes + refresh-token-expire-time: 2592000000 # 30 days \ No newline at end of file From 5cc28b6812c89c7f9059fa59607c090c9774d6d2 Mon Sep 17 00:00:00 2001 From: yooonwodyd Date: Tue, 24 Sep 2024 01:06:03 +0900 Subject: [PATCH 13/13] establish:[#22]- change gitignore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit yaml 파일 gitignore에 추가. --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c2065bc..546e78e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,9 @@ -HELP.md .gradle + build/ !gradle/wrapper/gradle-wrapper.jar !**/src/main/**/build/ +!**/src/main/resource/application.yaml !**/src/test/**/build/ ### STS ###