-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'dev' into feature/menu
- Loading branch information
Showing
30 changed files
with
567 additions
and
73 deletions.
There are no files selected for viewing
This file contains 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
Binary file not shown.
Binary file not shown.
Binary file not shown.
30 changes: 30 additions & 0 deletions
30
src/main/java/com/hanaro/starbucks/config/JwtAuthenticationFilter.java
This file contains 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,30 @@ | ||
package com.hanaro.starbucks.config; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.ServletRequest; | ||
import jakarta.servlet.ServletResponse; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.web.filter.GenericFilterBean; | ||
|
||
import java.io.IOException; | ||
|
||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends GenericFilterBean { | ||
|
||
private final JwtUtil jwtTokenProvider; | ||
|
||
@Override | ||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { | ||
String token = jwtTokenProvider.resolveToken((HttpServletRequest) request); | ||
|
||
if (token != null && jwtTokenProvider.validateToken(token)) { | ||
Authentication authentication = jwtTokenProvider.getAuthentication(token); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
filterChain.doFilter(request, response); | ||
} | ||
} |
This file contains 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,72 @@ | ||
package com.hanaro.starbucks.config; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.Jws; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.SignatureAlgorithm; | ||
import jakarta.annotation.PostConstruct; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.util.Base64; | ||
import java.util.Date; | ||
import java.util.List; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtUtil { | ||
@Value("${jwt.secretKey}") | ||
private String secretKey; | ||
|
||
@Value("${jwt.expiration_time}") | ||
private long expireTime; | ||
|
||
private final UserDetailsService userDetailsService; | ||
|
||
@PostConstruct | ||
protected void init() { | ||
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); | ||
} | ||
|
||
public String createToken(String userId, List<String> roleList) { | ||
Claims claims = Jwts.claims().setSubject(userId); | ||
claims.put("roles", roleList); | ||
Date now = new Date(); | ||
return Jwts.builder() | ||
.setClaims(claims) | ||
.setIssuedAt(now) | ||
.setExpiration(new Date(now.getTime() + expireTime)) | ||
.signWith(SignatureAlgorithm.HS256, secretKey) | ||
.compact(); | ||
} | ||
|
||
public Authentication getAuthentication(String token) { | ||
String userId = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); | ||
UserDetails userDetails = userDetailsService.loadUserByUsername(userId); | ||
return new UsernamePasswordAuthenticationToken( | ||
userDetails, "", userDetails.getAuthorities() | ||
); | ||
} | ||
|
||
public String resolveToken(HttpServletRequest request) { | ||
return request.getHeader("X-AUTH-TOKEN"); | ||
} | ||
|
||
public boolean validateToken(String token){ | ||
try{ | ||
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey) | ||
.parseClaimsJws(token); | ||
return claims.getBody().getExpiration().before(new Date()) == false; | ||
} | ||
catch (Exception e){ | ||
return false; | ||
} | ||
} | ||
|
||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/hanaro/starbucks/config/PasswordEncoderConfig.java
This file contains 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,13 @@ | ||
package com.hanaro.starbucks.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
|
||
@Configuration | ||
public class PasswordEncoderConfig { | ||
@Bean | ||
public BCryptPasswordEncoder bCryptPasswordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
src/main/java/com/hanaro/starbucks/config/SecurityConfig.java
This file contains 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 com.hanaro.starbucks.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.http.SessionCreationPolicy; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; | ||
import org.springframework.web.cors.CorsConfiguration; | ||
import org.springframework.web.cors.CorsConfigurationSource; | ||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
|
||
import java.util.Collections; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
@RequiredArgsConstructor | ||
public class SecurityConfig { | ||
private final JwtUtil jwtConfig; | ||
|
||
@Bean | ||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | ||
http | ||
.csrf((auth) -> auth.disable()) | ||
.cors((cors) -> cors.configurationSource(corsConfigurationSource())) | ||
|
||
// .authorizeHttpRequests((auth) -> auth | ||
// // 로그인과 회원가입은 모든 사용자에게 허용한다. | ||
// .requestMatchers( | ||
// new AntPathRequestMatcher("/login"), | ||
// new AntPathRequestMatcher("/signup") | ||
// ).permitAll() // 권한이 있든 말든 모두 접근 가능 | ||
// // admin일 경우에만 /admin에 대한 요청에서 접근을 허용한다. | ||
// .requestMatchers("/admin").hasRole("ADMIN") | ||
// // 그 외 모든 요청은 인증된 사용자에게만 허용한다. | ||
// .anyRequest().authenticated() | ||
// ) | ||
// .formLogin((formLogin) -> formLogin | ||
// .loginProcessingUrl("/login") | ||
// .successHandler(((request, response, authentication) -> { | ||
// System.out.println("로그인 성공했습니다."); | ||
// response.sendRedirect("/"); | ||
// })) | ||
// .permitAll() | ||
// ); | ||
|
||
.authorizeHttpRequests( (auth) -> auth | ||
.requestMatchers( new AntPathRequestMatcher("/**") ) | ||
.permitAll()) | ||
|
||
.sessionManagement(sessionManagement -> | ||
sessionManagement.sessionCreationPolicy( | ||
SessionCreationPolicy.STATELESS // 세션에 저장하지 않겠다. 기본이 세션에 저장하는 것 | ||
)) | ||
.addFilterBefore(new JwtAuthenticationFilter(jwtConfig), | ||
UsernamePasswordAuthenticationFilter.class); | ||
|
||
|
||
return http.build(); | ||
} | ||
|
||
@Bean | ||
CorsConfigurationSource corsConfigurationSource() { | ||
CorsConfiguration config = new CorsConfiguration(); | ||
config.setAllowedHeaders(Collections.singletonList("*")); // 허용할 HTTP header | ||
config.setAllowedMethods(Collections.singletonList("*")); // 허용할 HTTP method | ||
config.setAllowedOriginPatterns(Collections.singletonList("http://localhost:5173")); // 허용할 출처 | ||
config.setAllowCredentials(true); // 쿠키 인증 요청 허용 | ||
|
||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
source.registerCorsConfiguration("/**", config); | ||
return source; | ||
} | ||
} |
68 changes: 68 additions & 0 deletions
68
src/main/java/com/hanaro/starbucks/controller/MemberController.java
This file contains 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,68 @@ | ||
package com.hanaro.starbucks.controller; | ||
|
||
import com.hanaro.starbucks.config.JwtUtil; | ||
import com.hanaro.starbucks.dto.member.LoginReqDto; | ||
import com.hanaro.starbucks.dto.member.MemberResDto; | ||
import com.hanaro.starbucks.dto.member.SignupReqDto; | ||
import com.hanaro.starbucks.dto.member.MemberUpdateReqDto; | ||
import com.hanaro.starbucks.service.MemberService; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.web.bind.annotation.*; | ||
|
||
import java.util.Arrays; | ||
import java.util.List; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
@RequestMapping("/api/v1/users") | ||
public class MemberController { | ||
private final MemberService memberService; | ||
private final JwtUtil jwtUtil; | ||
|
||
@GetMapping("") | ||
public List<MemberResDto> getUsers(){ | ||
return memberService.getUsers(); | ||
} | ||
@GetMapping("/{userIdx}") | ||
public MemberResDto getUser(@PathVariable int userIdx){ | ||
return memberService.getUser(userIdx); | ||
} | ||
|
||
@PostMapping("/signup") | ||
@ResponseBody | ||
public ResponseEntity<?> signup(@RequestBody SignupReqDto user) { | ||
System.out.println(user); | ||
boolean findUser = memberService.findUserByUserId(user.getUserId()); | ||
System.out.println(findUser); | ||
if (!findUser) { | ||
MemberResDto newUser = memberService.createUser(user); | ||
return ResponseEntity.ok(newUser.getUserId()); | ||
} | ||
return ResponseEntity.status(HttpStatus.CONFLICT).body("이미 존재하는 사용자입니다."); | ||
} | ||
|
||
@PostMapping("/login") | ||
@ResponseBody | ||
public ResponseEntity<?> login(@RequestBody LoginReqDto user) { | ||
MemberResDto findUser = memberService.findUserByUserIdAndUserPw(user.getUserId(), user.getUserPw()); | ||
if (findUser != null) { | ||
String token = jwtUtil.createToken(findUser.getUserId(), Arrays.asList(findUser.getUserRole())); | ||
return ResponseEntity.ok(token); | ||
} else { | ||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("로그인에 실패하였습니다. 아이디와 비밀번호를 확인해주세요."); | ||
} | ||
} | ||
|
||
@PutMapping("/admin/{userIdx}") | ||
public void updateUser(@PathVariable int userIdx, @RequestBody MemberUpdateReqDto user){ | ||
memberService.updateUser(userIdx, user); | ||
} | ||
|
||
@DeleteMapping("/admin/{userIdx}") | ||
public void deleteUser(@PathVariable int userIdx){ | ||
memberService.deleteUser(userIdx); | ||
} | ||
|
||
} |
This file contains 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 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
12 changes: 12 additions & 0 deletions
12
src/main/java/com/hanaro/starbucks/dto/member/LoginReqDto.java
This file contains 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,12 @@ | ||
package com.hanaro.starbucks.dto.member; | ||
|
||
import lombok.AllArgsConstructor; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
|
||
@Getter | ||
@NoArgsConstructor | ||
@AllArgsConstructor | ||
public class LoginReqDto { | ||
private String userId, userPw; | ||
} |
36 changes: 36 additions & 0 deletions
36
src/main/java/com/hanaro/starbucks/dto/member/MemberResDto.java
This file contains 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,36 @@ | ||
package com.hanaro.starbucks.dto.member; | ||
|
||
import com.hanaro.starbucks.entity.Member; | ||
import lombok.Builder; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
|
||
import java.time.LocalDate; | ||
|
||
@Getter | ||
@NoArgsConstructor | ||
public class MemberResDto { | ||
private int userIdx; | ||
|
||
private String userId; | ||
|
||
private String userPw; | ||
|
||
private String userNickname; | ||
|
||
private String userRole; | ||
|
||
private int userPoint; | ||
|
||
private LocalDate userJoinDate; | ||
|
||
@Builder | ||
public MemberResDto(Member user){ | ||
this.userId = user.getUserId(); | ||
this.userPw = user.getUserPw(); | ||
this.userNickname = user.getUserNickname(); | ||
this.userRole = user.getUserRole(); | ||
this.userPoint = user.getUserPoint(); | ||
this.userJoinDate = user.getUserJoinDate(); | ||
} | ||
} |
Oops, something went wrong.