-
Notifications
You must be signed in to change notification settings - Fork 0
10주차 미션_따밥 #34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rud15dns
wants to merge
1
commit into
main
Choose a base branch
from
feat/ttabob_chap10
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
10주차 미션_따밥 #34
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| package umc.server.domain.member.service; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.data.domain.Page; | ||
| import org.springframework.data.domain.PageImpl; | ||
|
|
@@ -34,6 +35,12 @@ | |
| import umc.server.domain.review.dto.res.ReviewResDTO; | ||
| import umc.server.domain.review.entity.Review; | ||
| import umc.server.domain.review.repository.ReviewRepository; | ||
| <<<<<<< Updated upstream | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이거 다 제거해주세요~! |
||
| ======= | ||
| import umc.server.global.auth.CustomUserDetails; | ||
| import umc.server.global.auth.JwtUtil; | ||
| import umc.server.global.auth.enums.Role; | ||
| >>>>>>> Stashed changes | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
@@ -52,6 +59,12 @@ public class MemberServiceImpl implements MemberService{ | |
| private final MemberFoodRepository memberFoodRepository; | ||
| private final MissionRepository missionRepository; | ||
|
|
||
| <<<<<<< Updated upstream | ||
| ======= | ||
| private final PasswordEncoder passwordEncoder; | ||
| private final JwtUtil jwtUtil; | ||
|
|
||
| >>>>>>> Stashed changes | ||
| @Override | ||
| public Member findByUsername(Long memberId) { | ||
| return memberRepository.findById(memberId) | ||
|
|
@@ -88,6 +101,22 @@ public MemberResDTO.JoinDTO join(MemberReqDTO.JoinDTO request) { | |
| return MemberConverter.toJoinDTO(member); | ||
| } | ||
|
|
||
| @Override | ||
| public MemberResDTO.LoginDTO login(MemberReqDTO.@Valid LoginDTO request) { | ||
| Member member = memberRepository.findByEmail(request.email()) | ||
| .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); | ||
|
|
||
| if (!passwordEncoder.matches(request.password(), member.getPassword())) { | ||
| throw new MemberException(MemberErrorCode.PASSWORD_INVALID); | ||
| } | ||
|
|
||
| CustomUserDetails userDetails = new CustomUserDetails(member); | ||
|
|
||
| String accessToken = jwtUtil.createAccessToken(userDetails); | ||
|
|
||
| return MemberConverter.toLoginDTO(member, accessToken); | ||
| } | ||
|
|
||
| @Override | ||
| public MemberResDTO.HomeTopDTO getHomeTop(Long memberId, String region, Long cursor, int size) { | ||
| Member member = findByUsername(memberId); | ||
|
|
||
33 changes: 33 additions & 0 deletions
33
따밥/server/src/main/java/umc/server/global/auth/AuthenticationEntryPointImpl.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package umc.server.global.auth; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
| import umc.server.global.apiPayload.ApiResponse; | ||
| import umc.server.global.apiPayload.code.GeneralErrorCode; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint { | ||
| private final ObjectMapper mapper = new ObjectMapper(); | ||
|
|
||
| @Override | ||
| public void commence( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| AuthenticationException authException | ||
| ) throws IOException, ServletException { | ||
| response.setContentType("application/json;charset=UTF-8"); | ||
| response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
|
|
||
| ApiResponse<Void> errorResponse = ApiResponse.onFailure( | ||
| GeneralErrorCode._UNAUTHORIZED, | ||
| null | ||
| ); | ||
|
|
||
| mapper.writeValue(response.getOutputStream(), errorResponse); | ||
| } | ||
| } |
49 changes: 49 additions & 0 deletions
49
따밥/server/src/main/java/umc/server/global/auth/JwtAuthFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package umc.server.global.auth; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.NonNull; | ||
| import lombok.RequiredArgsConstructor; | ||
| 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.UserDetails; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
| import umc.server.global.apiPayload.ApiResponse; | ||
| import umc.server.global.apiPayload.code.GeneralErrorCode; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @RequiredArgsConstructor | ||
| public class JwtAuthFilter extends OncePerRequestFilter { | ||
| private final JwtUtil jwtUtil; | ||
| private final CustomUserDetailsService userDetailsService; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| @NonNull HttpServletRequest request, | ||
| @NonNull HttpServletResponse response, | ||
| @NonNull FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
|
|
||
| String token = request.getHeader("Authorization"); | ||
| if (token == null || !token.startsWith("Bearer ")) { | ||
| filterChain.doFilter(request, response); | ||
| return; | ||
| } | ||
| token = token.replace("Bearer ", ""); | ||
|
|
||
| if (jwtUtil.isValid(token)) { | ||
| String email = jwtUtil.getEmail(token); | ||
|
|
||
| UserDetails user = userDetailsService.loadUserByUsername(email); | ||
| Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); | ||
| SecurityContextHolder.getContext().setAuthentication(auth); | ||
| // 이 부분이 일정동안 Authentication을 유지하고 있다고 하는 부분인 것 같다. | ||
| } | ||
| filterChain.doFilter(request, response); | ||
| } | ||
| } |
82 changes: 82 additions & 0 deletions
82
따밥/server/src/main/java/umc/server/global/auth/JwtUtil.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| package umc.server.global.auth; | ||
|
|
||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jws; | ||
| import io.jsonwebtoken.JwtException; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import javax.crypto.SecretKey; | ||
| import javax.crypto.spec.SecretKeySpec; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.Date; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @Component | ||
| public class JwtUtil { | ||
| private final SecretKey secretKey; | ||
| private final Duration accessExpiration; | ||
|
|
||
| public JwtUtil( | ||
| @Value("${jwt.token.secretKey}") String secret, | ||
| @Value("${jwt.token.expiration}") Long expiration | ||
| ){ | ||
| this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); | ||
| this.accessExpiration = Duration.ofMillis(expiration); | ||
| } | ||
|
|
||
| // AccessToken 생성 | ||
| public String createAccessToken(CustomUserDetails user){ | ||
| return createToken(user, accessExpiration); | ||
| } | ||
|
|
||
| // 토큰에서 이메일 가져오기 | ||
| public String getEmail(String token){ | ||
| try{ | ||
| return getClaims(token).getPayload().getSubject(); | ||
| } catch (JwtException e){ | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| public boolean isValid(String token){ | ||
| try { | ||
| getClaims(token); | ||
| return true; | ||
| } catch (JwtException e) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| private Jws<Claims> getClaims(String token) throws JwtException{ | ||
| return Jwts.parser() | ||
| .verifyWith(secretKey) | ||
| .clockSkewSeconds(60) | ||
| .build() | ||
| .parseSignedClaims(token); | ||
| } | ||
|
|
||
| private String createToken(CustomUserDetails user, Duration expiration){ | ||
| Instant now = Instant.now(); | ||
|
|
||
| // 인가 정보 | ||
| String authorities = user.getAuthorities().stream() | ||
| .map(GrantedAuthority::getAuthority) | ||
| .collect(Collectors.joining(",")); | ||
|
|
||
| return Jwts.builder() | ||
| .subject(user.getUsername()) // 여기서 username은 email | ||
| .claim("role", authorities) | ||
| .claim("email", user.getUsername()) | ||
| .issuedAt(Date.from(now)) | ||
| .expiration(Date.from(now.plus(expiration))) | ||
| .signWith(secretKey) | ||
| .compact(); | ||
| } | ||
| } |
77 changes: 77 additions & 0 deletions
77
따밥/server/src/main/java/umc/server/global/config/SecurityConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| package umc.server.global.config; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| 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.configurers.AbstractHttpConfigurer; | ||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
| import umc.server.global.auth.AuthenticationEntryPointImpl; | ||
| import umc.server.global.auth.CustomUserDetailsService; | ||
| import umc.server.global.auth.JwtAuthFilter; | ||
| import umc.server.global.auth.JwtUtil; | ||
|
|
||
| @EnableWebSecurity | ||
| @Configuration | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
| private final JwtUtil jwtUtil; | ||
| private final CustomUserDetailsService customUserDetailsService; | ||
| private final String[] allowUris = { | ||
| "/swagger-ui/**", | ||
| "/swagger-resources/**", | ||
| "/v3/api-docs/**", | ||
| "/auth/**" | ||
| }; | ||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| @Bean | ||
| public JwtAuthFilter jwtAuthFilter() { | ||
| return new JwtAuthFilter(jwtUtil, customUserDetailsService); | ||
| } | ||
|
|
||
| @Bean | ||
| public AuthenticationEntryPoint authenticationEntryPoint() { | ||
| return new AuthenticationEntryPointImpl(); | ||
| } | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ | ||
| http | ||
| .csrf(AbstractHttpConfigurer::disable); | ||
| http | ||
| .formLogin(AbstractHttpConfigurer::disable); | ||
|
|
||
| http | ||
| .authorizeHttpRequests(requests -> requests | ||
| .requestMatchers(allowUris).permitAll() | ||
| .requestMatchers("/swagger-ui/index.html#").hasRole("ADMIN") | ||
| .anyRequest().authenticated() | ||
| ); | ||
|
|
||
| http | ||
| .exceptionHandling(exception -> exception.authenticationEntryPoint(authenticationEntryPoint())); | ||
|
|
||
|
|
||
|
|
||
| http | ||
| .addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class); | ||
|
|
||
| http | ||
| .logout(logout -> logout | ||
| .logoutUrl("/logout") | ||
| .logoutSuccessUrl("/login?logout") | ||
| .permitAll() | ||
| ); | ||
|
|
||
| return http.build(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
요거 제거 해주세요