diff --git a/src/main/java/com/zonebug/debugging/config/WebSecurityConfig.java b/src/main/java/com/zonebug/debugging/config/WebSecurityConfig.java index 5255009..016188f 100644 --- a/src/main/java/com/zonebug/debugging/config/WebSecurityConfig.java +++ b/src/main/java/com/zonebug/debugging/config/WebSecurityConfig.java @@ -1,10 +1,11 @@ package com.zonebug.debugging.config; -import com.zonebug.debugging.config.jwt.JwtAccessDeniedHandler; -import com.zonebug.debugging.config.jwt.JwtAuthenticationEntryPoint; -import com.zonebug.debugging.config.jwt.JwtSecurityConfig; -import com.zonebug.debugging.config.jwt.TokenProvider; +import com.zonebug.debugging.security.jwt.JwtAccessDeniedHandler; +import com.zonebug.debugging.security.jwt.JwtAuthenticationEntryPoint; +import com.zonebug.debugging.security.jwt.JwtSecurityConfig; +import com.zonebug.debugging.security.jwt.TokenProvider; +import com.zonebug.debugging.security.user.CustomUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -21,15 +22,18 @@ public class WebSecurityConfig { private final TokenProvider tokenProvider; private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; private final JwtAccessDeniedHandler jwtAccessDeniedHandler; + private final CustomUserDetailsService customUserDetailsService; public WebSecurityConfig( TokenProvider tokenProvider, JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, - JwtAccessDeniedHandler jwtAccessDeniedHandler + JwtAccessDeniedHandler jwtAccessDeniedHandler, + CustomUserDetailsService customUserDetailsService ) { this.tokenProvider = tokenProvider; this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint; this.jwtAccessDeniedHandler = jwtAccessDeniedHandler; + this.customUserDetailsService = customUserDetailsService; } @Bean @@ -58,13 +62,18 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .and() .authorizeHttpRequests((req) -> req - .requestMatchers("/user/authenticate", "/user/signup").permitAll() + .requestMatchers("/user/authenticate", "/user/signup", "/user/signin").permitAll() .requestMatchers("/oauth", "/oauth/kakao", "/oauth/callback/kakao", "/oauth/naver/**").permitAll() .requestMatchers("/source/url").permitAll() .anyRequest().authenticated() ) + .userDetailsService(customUserDetailsService) + + + .apply(new JwtSecurityConfig(tokenProvider)); + return http.build(); } diff --git a/src/main/java/com/zonebug/debugging/controller/AuthController.java b/src/main/java/com/zonebug/debugging/controller/AuthController.java deleted file mode 100644 index 3b8cb16..0000000 --- a/src/main/java/com/zonebug/debugging/controller/AuthController.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.zonebug.debugging.controller; - -import com.zonebug.debugging.dto.LoginDto; -import com.zonebug.debugging.dto.TokenDto; -import com.zonebug.debugging.config.jwt.JwtFilter; -import com.zonebug.debugging.config.jwt.TokenProvider; -import jakarta.validation.Valid; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -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; - -@RestController -@RequestMapping("/user") -public class AuthController { - - private final TokenProvider tokenProvider; - private final AuthenticationManagerBuilder authenticationManagerBuilder; - - private AuthController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { - this.tokenProvider = tokenProvider; - this.authenticationManagerBuilder = authenticationManagerBuilder; - } - - @PostMapping("/authenticate") - public ResponseEntity authorize(@Valid @RequestBody LoginDto loginDto) { - - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword()); - - Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); - SecurityContextHolder.getContext().setAuthentication(authentication); - - String jwt = tokenProvider.createAccessToken(authentication); - - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(JwtFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - - return new ResponseEntity<>(new TokenDto(jwt), httpHeaders, HttpStatus.OK); - } - - -} diff --git a/src/main/java/com/zonebug/debugging/controller/CommunityController.java b/src/main/java/com/zonebug/debugging/controller/CommunityController.java index 86e81cb..a0e3b08 100644 --- a/src/main/java/com/zonebug/debugging/controller/CommunityController.java +++ b/src/main/java/com/zonebug/debugging/controller/CommunityController.java @@ -22,7 +22,8 @@ public class CommunityController { private final CommunityService communityService; @GetMapping("/") - public ResponseEntity getMainPosts(UserDetails authUser) { + public ResponseEntity getMainPosts( + @AuthenticationPrincipal UserDetails authUser) { return ResponseEntity.ok(communityService.getMainPosts(authUser)); } @@ -52,7 +53,7 @@ public ResponseEntity deletePost( return ResponseEntity.ok(communityService.deletePost(authUser, postId)); } - @GetMapping("/{tag}") + @GetMapping("/{tag}")//?tag=으로 수정할 것 public ResponseEntity getSimplePosts( @PathVariable String tag, @AuthenticationPrincipal UserDetails authUser, @@ -60,14 +61,14 @@ public ResponseEntity getSimplePosts( return ResponseEntity.ok(communityService.getTagPosts(authUser, tag, pageNum)); } - @GetMapping("/{postId}") + @GetMapping("/post/{postId}") public ResponseEntity readPost( @AuthenticationPrincipal UserDetails authUser, - @PathVariable Long postId) { + @PathVariable(name = "postId") Long postId) { return ResponseEntity.ok(communityService.readPost(authUser, postId)); } - @GetMapping("/{keyword}") + @GetMapping("/search/{keyword}") public ResponseEntity searchPost( @PathVariable String keyword, @RequestParam(name = "pageNum") Integer pageNum, diff --git a/src/main/java/com/zonebug/debugging/controller/UserController.java b/src/main/java/com/zonebug/debugging/controller/UserController.java index 56bf7a1..cf77a0b 100644 --- a/src/main/java/com/zonebug/debugging/controller/UserController.java +++ b/src/main/java/com/zonebug/debugging/controller/UserController.java @@ -1,27 +1,75 @@ package com.zonebug.debugging.controller; -import com.zonebug.debugging.config.jwt.JwtFilter; import com.zonebug.debugging.domain.user.User; +import com.zonebug.debugging.dto.LoginDto; +import com.zonebug.debugging.dto.TokenDto; import com.zonebug.debugging.dto.UserDto; +import com.zonebug.debugging.security.jwt.JwtFilter; +import com.zonebug.debugging.security.jwt.TokenProvider; +import com.zonebug.debugging.security.user.CustomUserDetails; import com.zonebug.debugging.service.UserService; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; +import java.util.Optional; + @RestController +@RequiredArgsConstructor @RequestMapping("/user") public class UserController { private final UserService userService; + private final TokenProvider tokenProvider; + private final AuthenticationManagerBuilder authenticationManagerBuilder; + - public UserController(UserService userService) { - this.userService = userService; + @GetMapping("") + public ResponseEntity userOk(@AuthenticationPrincipal CustomUserDetails principalDetails) { + return ResponseEntity.ok(principalDetails.getUser()); } + @PostMapping("/signup") - public ResponseEntity signup(@Valid @RequestBody UserDto userDto) { - return ResponseEntity.ok(userService.signup(userDto)); + public ResponseEntity signUp(@Valid @RequestBody UserDto userDto) { + return ResponseEntity.ok(userService.signUp(userDto)); + } + + @PostMapping("/signin") + public ResponseEntity signIn(@Valid @RequestBody LoginDto loginDto) { + return ResponseEntity.ok(userService.signIn(loginDto)); + } + + @PostMapping("/authenticate") + public ResponseEntity authorize(@Valid @RequestBody LoginDto loginDto) { + + UsernamePasswordAuthenticationToken authenticationToken = + new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword()); + + Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); + String accessToken = tokenProvider.createAccessToken(authentication); + String refreshToken = tokenProvider.createRefreshToken(authentication); + + return new ResponseEntity(new TokenDto(accessToken, refreshToken), HttpStatus.OK); } + @GetMapping("/info") + public ResponseEntity> info() { + return ResponseEntity.ok(userService.getCurrentUser()); + } + + // Authentication 회원 정보 + @GetMapping("/info2") + public ResponseEntity user(@AuthenticationPrincipal CustomUserDetails principalDetails) { + User user = principalDetails.getUser(); + + return ResponseEntity.ok(principalDetails.getUser()); + } } diff --git a/src/main/java/com/zonebug/debugging/dto/MainPostDTO.java b/src/main/java/com/zonebug/debugging/dto/MainPostDTO.java index 0b793c7..464f0a6 100644 --- a/src/main/java/com/zonebug/debugging/dto/MainPostDTO.java +++ b/src/main/java/com/zonebug/debugging/dto/MainPostDTO.java @@ -15,6 +15,9 @@ public class MainPostDTO { @NotNull private Long postId; + @NotNull + private String tag; + @NotNull private String title; diff --git a/src/main/java/com/zonebug/debugging/dto/TokenDto.java b/src/main/java/com/zonebug/debugging/dto/TokenDto.java index cdd37d5..2b9054e 100644 --- a/src/main/java/com/zonebug/debugging/dto/TokenDto.java +++ b/src/main/java/com/zonebug/debugging/dto/TokenDto.java @@ -9,6 +9,7 @@ @NoArgsConstructor public class TokenDto { - private String token; + private String accessToken; + private String refreshToken; } diff --git a/src/main/java/com/zonebug/debugging/dto/WritePostDTO.java b/src/main/java/com/zonebug/debugging/dto/WritePostDTO.java index 293d376..fc98e52 100644 --- a/src/main/java/com/zonebug/debugging/dto/WritePostDTO.java +++ b/src/main/java/com/zonebug/debugging/dto/WritePostDTO.java @@ -12,7 +12,6 @@ @AllArgsConstructor public class WritePostDTO { - private User user; private String tag; private String title; private String image; diff --git a/src/main/java/com/zonebug/debugging/dto/response/GetPathResponseDTO.java b/src/main/java/com/zonebug/debugging/dto/response/GetPathResponseDTO.java new file mode 100644 index 0000000..42597f6 --- /dev/null +++ b/src/main/java/com/zonebug/debugging/dto/response/GetPathResponseDTO.java @@ -0,0 +1,17 @@ +package com.zonebug.debugging.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.net.URL; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GetPathResponseDTO { + + private URL url; +} diff --git a/src/main/java/com/zonebug/debugging/config/jwt/JwtAccessDeniedHandler.java b/src/main/java/com/zonebug/debugging/security/jwt/JwtAccessDeniedHandler.java similarity index 93% rename from src/main/java/com/zonebug/debugging/config/jwt/JwtAccessDeniedHandler.java rename to src/main/java/com/zonebug/debugging/security/jwt/JwtAccessDeniedHandler.java index 66ea308..5cdbeb5 100644 --- a/src/main/java/com/zonebug/debugging/config/jwt/JwtAccessDeniedHandler.java +++ b/src/main/java/com/zonebug/debugging/security/jwt/JwtAccessDeniedHandler.java @@ -1,4 +1,4 @@ -package com.zonebug.debugging.config.jwt; +package com.zonebug.debugging.security.jwt; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/zonebug/debugging/config/jwt/JwtAuthenticationEntryPoint.java b/src/main/java/com/zonebug/debugging/security/jwt/JwtAuthenticationEntryPoint.java similarity index 94% rename from src/main/java/com/zonebug/debugging/config/jwt/JwtAuthenticationEntryPoint.java rename to src/main/java/com/zonebug/debugging/security/jwt/JwtAuthenticationEntryPoint.java index dc5522b..5b9b13a 100644 --- a/src/main/java/com/zonebug/debugging/config/jwt/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/zonebug/debugging/security/jwt/JwtAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package com.zonebug.debugging.config.jwt; +package com.zonebug.debugging.security.jwt; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/zonebug/debugging/config/jwt/JwtFilter.java b/src/main/java/com/zonebug/debugging/security/jwt/JwtFilter.java similarity index 97% rename from src/main/java/com/zonebug/debugging/config/jwt/JwtFilter.java rename to src/main/java/com/zonebug/debugging/security/jwt/JwtFilter.java index eeaf4ba..88a2a3f 100644 --- a/src/main/java/com/zonebug/debugging/config/jwt/JwtFilter.java +++ b/src/main/java/com/zonebug/debugging/security/jwt/JwtFilter.java @@ -1,4 +1,4 @@ -package com.zonebug.debugging.config.jwt; +package com.zonebug.debugging.security.jwt; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; diff --git a/src/main/java/com/zonebug/debugging/config/jwt/JwtSecurityConfig.java b/src/main/java/com/zonebug/debugging/security/jwt/JwtSecurityConfig.java similarity index 94% rename from src/main/java/com/zonebug/debugging/config/jwt/JwtSecurityConfig.java rename to src/main/java/com/zonebug/debugging/security/jwt/JwtSecurityConfig.java index 3e0fcdb..e0db2c4 100644 --- a/src/main/java/com/zonebug/debugging/config/jwt/JwtSecurityConfig.java +++ b/src/main/java/com/zonebug/debugging/security/jwt/JwtSecurityConfig.java @@ -1,4 +1,4 @@ -package com.zonebug.debugging.config.jwt; +package com.zonebug.debugging.security.jwt; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/src/main/java/com/zonebug/debugging/config/jwt/TokenProvider.java b/src/main/java/com/zonebug/debugging/security/jwt/TokenProvider.java similarity index 86% rename from src/main/java/com/zonebug/debugging/config/jwt/TokenProvider.java rename to src/main/java/com/zonebug/debugging/security/jwt/TokenProvider.java index da45d33..f4f9ce8 100644 --- a/src/main/java/com/zonebug/debugging/config/jwt/TokenProvider.java +++ b/src/main/java/com/zonebug/debugging/security/jwt/TokenProvider.java @@ -1,5 +1,7 @@ -package com.zonebug.debugging.config.jwt; +package com.zonebug.debugging.security.jwt; +import com.zonebug.debugging.security.user.CustomUserDetails; +import com.zonebug.debugging.security.user.CustomUserDetailsService; import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @@ -24,6 +26,7 @@ public class TokenProvider implements InitializingBean { private final Logger logger = LoggerFactory.getLogger(TokenProvider.class); + private final CustomUserDetailsService customUserDetailsService; private static final String AUTHORITIES_KEY = "auth"; private final String secret; @@ -32,9 +35,10 @@ public class TokenProvider implements InitializingBean { private Key key; public TokenProvider( - @Value("${jwt.secret}") String secret, + CustomUserDetailsService customUserDetailsService, @Value("${jwt.secret}") String secret, @Value("${jwt.accesstoken-validity-in-seconds}") long accessTokenValidityInMilliseconds, @Value("${jwt.refreshtoken-validity-in-seconds}") long refreshTokenValidityInMilliseconds) { + this.customUserDetailsService = customUserDetailsService; this.secret = secret; this.accessTokenValidityInMilliseconds = accessTokenValidityInMilliseconds * 1000; this.refreshTokenValidityInMilliseconds = refreshTokenValidityInMilliseconds; @@ -92,21 +96,23 @@ public Authentication getAuthentication(String token) { .build() .parseClaimsJws(token) .getBody(); - System.out.println("96"); + Collection authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); - System.out.println("101"); + User principal = new User(claims.getSubject(), "", authorities); - System.out.println("103"); - return new UsernamePasswordAuthenticationToken(principal, token, authorities); + + CustomUserDetails customUserDetails = (CustomUserDetails) customUserDetailsService.loadUserByUsername(principal.getUsername()); + return new UsernamePasswordAuthenticationToken(customUserDetails, token, authorities); } public boolean validateToken(String token) { try { Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token); + logger.info("JWT 유효성 확인 완료"); return true; } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) { logger.info("잘못된 JWT 서명입니다."); @@ -120,4 +126,4 @@ public boolean validateToken(String token) { return false; } -} +} \ No newline at end of file diff --git a/src/main/java/com/zonebug/debugging/security/user/CustomUserDetails.java b/src/main/java/com/zonebug/debugging/security/user/CustomUserDetails.java new file mode 100644 index 0000000..db829ab --- /dev/null +++ b/src/main/java/com/zonebug/debugging/security/user/CustomUserDetails.java @@ -0,0 +1,61 @@ +package com.zonebug.debugging.security.user; + +import com.zonebug.debugging.domain.user.User; +import lombok.Data; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.ArrayList; +import java.util.Collection; + +@Data +public class CustomUserDetails implements UserDetails { + + private User user; + + public CustomUserDetails(User user) { + this.user = user; + } + + @Override + public Collection getAuthorities() { + Collection collection = new ArrayList<>(); + collection.add(new GrantedAuthority() { + @Override + public String getAuthority() { + return "ROLE_USER"; + } + }); + return collection; + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public String getUsername() { + return user.getEmail(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/com/zonebug/debugging/service/CustomUserDetailsService.java b/src/main/java/com/zonebug/debugging/security/user/CustomUserDetailsService.java similarity index 97% rename from src/main/java/com/zonebug/debugging/service/CustomUserDetailsService.java rename to src/main/java/com/zonebug/debugging/security/user/CustomUserDetailsService.java index 4645c2c..45000da 100644 --- a/src/main/java/com/zonebug/debugging/service/CustomUserDetailsService.java +++ b/src/main/java/com/zonebug/debugging/security/user/CustomUserDetailsService.java @@ -1,4 +1,4 @@ -package com.zonebug.debugging.service; +package com.zonebug.debugging.security.user; import com.zonebug.debugging.domain.user.User; import com.zonebug.debugging.domain.user.UserRepository; diff --git a/src/main/java/com/zonebug/debugging/util/SecurityUtil.java b/src/main/java/com/zonebug/debugging/security/util/SecurityUtil.java similarity index 53% rename from src/main/java/com/zonebug/debugging/util/SecurityUtil.java rename to src/main/java/com/zonebug/debugging/security/util/SecurityUtil.java index 1d8eaae..47f382c 100644 --- a/src/main/java/com/zonebug/debugging/util/SecurityUtil.java +++ b/src/main/java/com/zonebug/debugging/security/util/SecurityUtil.java @@ -1,10 +1,11 @@ -package com.zonebug.debugging.util; +package com.zonebug.debugging.security.util; +import com.zonebug.debugging.domain.user.User; +import com.zonebug.debugging.security.user.CustomUserDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; import java.util.Optional; @@ -14,7 +15,7 @@ public class SecurityUtil { private SecurityUtil() { } - public static Optional getCurrentUsername() { + public static Optional getCurrentUser() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication == null) { @@ -22,15 +23,13 @@ public static Optional getCurrentUsername() { return Optional.empty(); } - String email = null; - if(authentication.getPrincipal() instanceof UserDetails) { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - email = userDetails.getUsername(); - } else if(authentication.getPrincipal() instanceof String) { - email = (String) authentication.getPrincipal(); + User currentUser = null; + if(authentication.getPrincipal() instanceof CustomUserDetails) { + CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal(); + currentUser = userDetails.getUser(); } - return Optional.ofNullable(email); + return Optional.ofNullable(currentUser); } } diff --git a/src/main/java/com/zonebug/debugging/service/CommunityService.java b/src/main/java/com/zonebug/debugging/service/CommunityService.java index 4f86c1e..ea99537 100644 --- a/src/main/java/com/zonebug/debugging/service/CommunityService.java +++ b/src/main/java/com/zonebug/debugging/service/CommunityService.java @@ -52,9 +52,10 @@ public List tagClassify(String tag) { for (Post post : findPosts) { Long postId = post.getId(); + String postTag = post.getTag(); String contents = post.getContents(); Date createdAt = post.getCreatedAt(); - MainPostDTO mainpostDTO = new MainPostDTO(postId, contents, createdAt); + MainPostDTO mainpostDTO = new MainPostDTO(postId, postTag, contents, createdAt); list.add(mainpostDTO); } return list; @@ -160,6 +161,8 @@ public PostIdResponseDTO writePost(UserDetails authUser, WritePostDTO writePost) .title(writePost.getTitle()) .image(writePost.getImage()) .contents(writePost.getContents()) + .hits(0L) + .createdAt(new Date()) .build(); Post savedPost = postRepository.saveAndFlush(post); diff --git a/src/main/java/com/zonebug/debugging/service/OAuthService.java b/src/main/java/com/zonebug/debugging/service/OAuthService.java index 4ce4808..7565ee6 100644 --- a/src/main/java/com/zonebug/debugging/service/OAuthService.java +++ b/src/main/java/com/zonebug/debugging/service/OAuthService.java @@ -2,10 +2,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.zonebug.debugging.config.jwt.TokenProvider; +import com.zonebug.debugging.security.jwt.TokenProvider; import com.zonebug.debugging.domain.user.User; import com.zonebug.debugging.domain.user.UserRepository; import com.zonebug.debugging.dto.response.OAuthResponseDTO; +import com.zonebug.debugging.security.user.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -23,7 +24,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; -import java.util.HashMap; import java.util.Optional; @Slf4j diff --git a/src/main/java/com/zonebug/debugging/service/UserService.java b/src/main/java/com/zonebug/debugging/service/UserService.java index 94dd5aa..97e1512 100644 --- a/src/main/java/com/zonebug/debugging/service/UserService.java +++ b/src/main/java/com/zonebug/debugging/service/UserService.java @@ -2,8 +2,15 @@ import com.zonebug.debugging.domain.user.User; import com.zonebug.debugging.domain.user.UserRepository; +import com.zonebug.debugging.dto.LoginDto; +import com.zonebug.debugging.dto.TokenDto; import com.zonebug.debugging.dto.UserDto; -import com.zonebug.debugging.util.SecurityUtil; +import com.zonebug.debugging.security.util.SecurityUtil; +import com.zonebug.debugging.security.jwt.TokenProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -11,18 +18,16 @@ import java.util.Optional; @Service +@RequiredArgsConstructor public class UserService { private final UserRepository userRepository; + private final AuthenticationManagerBuilder authenticationManagerBuilder; + private final TokenProvider tokenProvider; private final PasswordEncoder passwordEncoder; - public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - } - @Transactional - public User signup(UserDto userDto) { + public User signUp(UserDto userDto) { if(userRepository.findByEmail(userDto.getEmail()).orElse(null) != null) { throw new RuntimeException("이미 가입된 이메일입니다."); } @@ -32,21 +37,25 @@ public User signup(UserDto userDto) { .password(passwordEncoder.encode(userDto.getPassword())) .nickname(userDto.getNickname()) .period(userDto.getPeriod()) - .type(userDto.getType()) + .type("default") .build(); return userRepository.save(user); } + public TokenDto signIn(LoginDto loginDto) { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword()); + Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); + System.out.println(authentication.getPrincipal()); - @Transactional(readOnly = true) - public Optional getUserWithEmail(String email) { - return SecurityUtil.getCurrentUsername().flatMap(userRepository::findByEmail); + TokenDto tokenDto = new TokenDto(tokenProvider.createAccessToken(authentication), tokenProvider.createRefreshToken(authentication)); + return tokenDto; } + @Transactional(readOnly = true) - public Optional getMyUser() { - return SecurityUtil.getCurrentUsername().flatMap(userRepository::findByEmail); + public Optional getCurrentUser() { + return SecurityUtil.getCurrentUser(); }