Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/release' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
deer0123 committed Nov 27, 2024
2 parents c23e7ef + 3c3c9bc commit 0b3e16f
Show file tree
Hide file tree
Showing 10 changed files with 203 additions and 182 deletions.
72 changes: 72 additions & 0 deletions RE-BOOK.postman_collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"info": {
"_postman_id": "fad9a20d-e95e-42bc-ac31-f3760eb4abfd",
"name": "RE:BOOK",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "38853273"
},
"item": [
{
"name": "좋아요 토글",
"request": {
"auth": {
"type": "bearer"
},
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "\r\n",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8181/board/detail/01248c3f-b3d9-425d-abfd-6701e218488a/toggle-like",
"protocol": "http",
"host": [
"localhost"
],
"port": "8181",
"path": [
"board",
"detail",
"01248c3f-b3d9-425d-abfd-6701e218488a",
"toggle-like"
]
}
},
"response": []
},
{
"name": "로그인",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"email\":\"[email protected]\",\r\n \"password\":\"1234\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8181/sign-in",
"protocol": "http",
"host": [
"localhost"
],
"port": "8181",
"path": [
"sign-in"
]
}
},
"response": []
}
]
}
11 changes: 8 additions & 3 deletions src/main/java/com/re_book/board/controller/BoardController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
Expand All @@ -35,7 +36,7 @@ public class BoardController {
private final ReviewService reviewService;
private final JwtTokenProvider jwtTokenProvider;


// list입니다.
@GetMapping("/list")
public ResponseEntity<?> list(@PageableDefault(size = 9) Pageable page,
@RequestParam(required = false) String sort,
Expand Down Expand Up @@ -64,7 +65,9 @@ public ResponseEntity<?> list(@PageableDefault(size = 9) Pageable page,
@GetMapping("/detail/{id}")
public ResponseEntity<?> detailPage(
@PathVariable String id,
@PageableDefault(page = 0, size = 10) Pageable page,
// @PageableDefault(page = 0, size = 10) Pageable page,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size,
@RequestHeader(value = "Authorization", required = false) String authorization,
@AuthenticationPrincipal TokenUserInfo userInfo) {

Expand All @@ -81,8 +84,10 @@ public ResponseEntity<?> detailPage(
boolean isLiked = (memberId != null) && bookDetail.isLiked();
int likeCount = bookDetail.getLikeCount();

// Pageable 객체 생성
Pageable pageable = PageRequest.of(page, size);
// 리뷰 목록 가져오기
Page<ReviewResponseDTO> reviewPage = reviewService.getReviewList(id, page);
Page<ReviewResponseDTO> reviewPage = reviewService.getReviewList(id, pageable);

// 책 정보가 제대로 전달되는지 로그로 확인
log.info("Book detail: {}", bookDetail);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public ResponseEntity<?> createReview(
response.put("success", true);
response.put("message", "리뷰가 성공적으로 작성되었습니다.");
response.put("reviewId", savedReview.getId());
response.put("nickname", savedReview.getMember().getName());
response.put("memberName", savedReview.getMember().getName());
response.put("content", savedReview.getContent());
response.put("rating", savedReview.getRating());

Expand All @@ -81,6 +81,8 @@ public ResponseEntity<?> updateReview(
@PathVariable String reviewId,
@Valid @RequestBody ReviewUpdateRequestDTO dto,
@AuthenticationPrincipal TokenUserInfo userInfo) {
log.info("reviewId: {}", reviewId);


if (userInfo == null) {
Map<String, Object> errorResponse = new HashMap<>();
Expand Down
100 changes: 25 additions & 75 deletions src/main/java/com/re_book/common/auth/JwtTokenProvider.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.re_book.common.auth;



import com.re_book.user.entity.Role;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
Expand All @@ -14,111 +12,63 @@

@Component
@Slf4j
// 역할: 토큰을 발급하고, 서명 위조를 검사하는 객체
public class JwtTokenProvider {

// 서명에 사용할 값 (512비트 이상의 랜덤 문자열을 권장)
// yml에 있는 값 땡겨오기 (properties 방식으로 선언)
@Value("${jwt.secretKey}")
private String secretKey;

@Value("${jwt.expiration}")
private int expiration;

@Value("${jwt.secretKeyRt}")
private String secreKeyRt;
private String secretKeyRt;

@Value("${jwt.expirationRt}")
private int expirationRt;


// 토큰 생성 메서드
/*
{
"iss": "서비스 이름(발급자)",
"exp": "2023-12-27(만료일자)",
"iat": "2023-11-27(발급일자)",
"email": "로그인한 사람 이메일",
"role": "Premium"
...
== 서명
}
*/
public String createToken(String email, String role) {
// Claims: 페이로드에 들어갈 사용자 정보
public String createToken(String email, String role, String name) {
Claims claims = Jwts.claims().setSubject(email);
claims.put("role", role);
claims.put("name", name); // name 추가
Date date = new Date();

return Jwts.builder()
.setClaims(claims)
.setIssuedAt(date)
//현재 시간 밀리초에 30분을 더한 시간을 만료시간으로 세팅
.setExpiration(new Date(date.getTime() + expiration * 60 * 1000L))
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
.setClaims(claims)
.setIssuedAt(date)
.setExpiration(new Date(date.getTime() + expiration * 60 * 1000L))
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}

public String createRefreshToken(String id, String role) {
// Claims: 페이로드에 들어갈 사용자 정보
public String createRefreshToken(String id, String role,String name) {
Claims claims = Jwts.claims().setSubject(id);
claims.put("role", role);
claims.put("name", name); // name 추가
Date date = new Date();

return Jwts.builder()
.setClaims(claims)
.setIssuedAt(date)
//현재 시간 밀리초에 30분을 더한 시간을 만료시간으로 세팅
.setExpiration(new Date(date.getTime() + expirationRt * 60 * 1000L))
.signWith(SignatureAlgorithm.HS256, secreKeyRt)
.compact();
.setClaims(claims)
.setIssuedAt(date)
.setExpiration(new Date(date.getTime() + expirationRt * 60 * 1000L))
.signWith(SignatureAlgorithm.HS256, secretKeyRt)
.compact();
}


/**
* 클라이언트가 전송한 토큰을 디코딩하여 토큰의 위조 여부를 확인
* 토큰을 json으로 파싱해서 클레임(토큰 정보)을 리턴
*
* @param token - 필터가 전달해 준 토큰
* @return - 토큰 안에 있는 인증된 유저 정보를 반환
*/
// 토큰 검증 및 정보 반환 메서드
public TokenUserInfo validateAndGetTokenUserInfo(String token) throws Exception {
Claims claims = Jwts.parserBuilder()
// 토큰 발급자의 발급 당시의 서명을 넣어줌.
.setSigningKey(secretKey)
// 서명 위조 검사: 위조된 경우에는 예외가 발생합니다.
// 위조되지 않았다면 payload를 리턴.
.build()
.parseClaimsJws(token)
.getBody();
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();

log.info("claims : {}", claims);

return TokenUserInfo.builder()
.id(claims.getSubject())
// 클레임이 get 할 수 있는 타입이 정해져 있어서 Role을 못 꺼냅니다.
// 일단 String으로 꺼내고, 다시 Role 타입으로 포장해서 집어 넣겠습니다.
.role(Role.valueOf(claims.get("role", String.class)))
.build();



.id(claims.getSubject())
.role(Role.valueOf(claims.get("role", String.class)))
.name(claims.get("name", String.class)) // name 추가
.build();
}
}

















}
1 change: 1 addition & 0 deletions src/main/java/com/re_book/common/auth/TokenUserInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ public class TokenUserInfo {

private String id;
private Role role;
private String name;

}
6 changes: 3 additions & 3 deletions src/main/java/com/re_book/config/InterceptorConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
//@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Autowired
// @Autowired
private AfterLoginInterceptor afterLoginInterceptor;
@Autowired
// @Autowired
private BeforeLoginInterceptor beforeLoginInterceptor;

@Override
Expand Down
Loading

0 comments on commit 0b3e16f

Please sign in to comment.