Skip to content

Commit

Permalink
Merge branch 'dev' into feature/menu
Browse files Browse the repository at this point in the history
  • Loading branch information
abcxj123 authored May 7, 2024
2 parents e34946d + fcee988 commit 77d854b
Show file tree
Hide file tree
Showing 30 changed files with 567 additions and 73 deletions.
Binary file added .DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ repositories {
}

dependencies {
//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'

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
Expand Down
Binary file added gradle/.DS_Store
Binary file not shown.
Binary file added src/.DS_Store
Binary file not shown.
Binary file added src/main/.DS_Store
Binary file not shown.
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);
}
}
72 changes: 72 additions & 0 deletions src/main/java/com/hanaro/starbucks/config/JwtUtil.java
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;
}
}

}
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 src/main/java/com/hanaro/starbucks/config/SecurityConfig.java
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;
}
}
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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@

import java.util.List;

import static com.hanaro.starbucks.util.APIConstant.API_VERSION;

@RestController
@RequestMapping("api/v1/products")
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping(API_VERSION + "/products")
@RequiredArgsConstructor
@CrossOrigin("http://localhost:5173")
public class MenuController {
private final MenuService menuService;
private final CategoryService categoryService;
Expand All @@ -35,13 +37,13 @@ public MenuResDto getMenuByMenuIdx(@PathVariable int menuIdx) throws Exception{
return menuService.getMenuByMenuIdx(menuIdx);
}

@DeleteMapping("/{menuIdx}")
@DeleteMapping("/admin/{menuIdx}")
public void deleteMenuByMenuIdx(@PathVariable int menuIdx) throws Exception{
menuService.deleteMenuByMenuIdx(menuIdx);
}

@PutMapping(value = "/{menuIdx}", consumes = {MediaType.APPLICATION_JSON_VALUE, "multipart/form-data"})
public void updateMenu(@PathVariable int menuIdx, @RequestPart(value = "dto") MenuReqDto menuReqDto, @RequestPart(value = "menuImg") MultipartFile img) throws Exception{
@PutMapping(value = "/admin/{menuIdx}", consumes = {MediaType.APPLICATION_JSON_VALUE, "multipart/form-data"})
public void updateMenu(@PathVariable int menuIdx, @RequestPart(value = "dto") MenuReqDto menuReqDto, @RequestPart(value = "menuImg", required = false) MultipartFile img) throws Exception{
menuService.updateMenu(menuIdx, menuReqDto, img);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@

import java.util.List;

import static com.hanaro.starbucks.util.APIConstant.API_VERSION;

@RestController
@RequiredArgsConstructor
@RequestMapping("api/v1/orders")
@RequestMapping(API_VERSION + "/orders")
@CrossOrigin("http://localhost:5173")
public class OrderController {
private final OrderService orderService;

Expand All @@ -23,12 +26,12 @@ public OrderResDto getOrder(@PathVariable int orderIdx) {
return orderService.getOrder(orderIdx);
}

@PutMapping("/{orderIdx}")
@PutMapping("/admin/{orderIdx}")
public void updateOrder(@PathVariable int orderIdx, @RequestBody OrderEditReqDto orderEditReqDto) {
orderService.updateOrder(orderIdx, orderEditReqDto);
}

@DeleteMapping("/{orderIdx}")
@DeleteMapping("/admin/{orderIdx}")
public void deleteOrder(@PathVariable int orderIdx) {
orderService.deleteOrder(orderIdx);
}
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/hanaro/starbucks/dto/member/LoginReqDto.java
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 src/main/java/com/hanaro/starbucks/dto/member/MemberResDto.java
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();
}
}
Loading

0 comments on commit 77d854b

Please sign in to comment.