Skip to content

Commit

Permalink
Merge pull request #73 from codestates-seb/hotfix/refact_and_test_v.1…
Browse files Browse the repository at this point in the history
….2.0

hotfix/refact_and_test_v.1.2.0
  • Loading branch information
Si-Hyeak-KANG committed Oct 11, 2022
2 parents b99b7d3 + f6e6f41 commit e1023a6
Show file tree
Hide file tree
Showing 19 changed files with 513 additions and 260 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public ResponseEntity getProducts(@RequestParam(required = false, defaultValue =
@RequestParam(required = false, defaultValue = "create_date") String sort,
@RequestParam(required = false, defaultValue = "desc") String orderBy,
@RequestParam(required = false) String vegetarian) {
QueryParamDto queryParamDto = new QueryParamDto(page, size, sort, orderBy, vegetarian);
QueryParamDto queryParamDto = new QueryParamDto(page-1, size, sort, orderBy, vegetarian);
String currentUserEmail = getCurrentUserEmail();
Page<Product> productsInPage = findProducts(queryParamDto, currentUserEmail);
List<ProductResponseDto> results = productsInPage.stream().map(ProductResponseDto::new).collect(Collectors.toList());
Expand All @@ -66,13 +66,9 @@ public ResponseEntity getProducts(@RequestParam(required = false, defaultValue =

private Page<Product> findProducts(QueryParamDto queryParamDto, String email) {
if (isAnonymousUser(email)) {
if(queryParamDto.getVegetarian()==null){queryParamDto.setVegetarian("플렉시테리언");}
return productService.findProductsWhenAnonymous(queryParamDto);
} else if(isAnonymousUser(email)==false && queryParamDto.getVegetarian()!=null){
return productService.findProductsWhenAnonymous(queryParamDto);
}
else {
return productService.findProductsWhenAuthenticated(queryParamDto, email);
} else {
return productService.findProductsWhenAuthenticated(queryParamDto, email);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,34 +34,19 @@ public ProductResponseDto findProduct(Long productId) {

@Override
public Page<Product> findProductsWhenAnonymous(QueryParamDto queryParamDto) {
String orderBy = queryParamDto.getOrderBy();
int page = queryParamDto.getPage() - 1;
String sort = queryParamDto.getSort();
int size = queryParamDto.getSize();
String vegetarianType = queryParamDto.getVegetarian();

if (isAscending(orderBy)) {
return productRepository.findAllByVegetarianTypeName(vegetarianType, PageRequest.of(page, size, Sort.by(sort)));
if (isNullInputType(queryParamDto.getVegetarian())) {
queryParamDto.setVegetarian("플렉시테리언");
}
return productRepository.findAllByVegetarianTypeName(vegetarianType, PageRequest.of(page, size, Sort.by(sort).descending()));
return getAllByVegetarianType(queryParamDto);
}

@Override
public Page<Product> findProductsWhenAuthenticated(QueryParamDto queryParamDto, String email) {

String orderBy = queryParamDto.getOrderBy();
int page = queryParamDto.getPage() - 1;
String sort = queryParamDto.getSort();
int size = queryParamDto.getSize();

Member member = memberRepository.findByEmail(email)
.orElseThrow(() -> new BusinessLogicException(MEMBER_NOT_FOUND));
String vegetarianTypeName = member.getVegetarianType();

if (isAscending(orderBy)) {
return productRepository.findAllByVegetarianTypeName(vegetarianTypeName, PageRequest.of(page, size, Sort.by(sort)));
if (isNullInputType(queryParamDto.getVegetarian())) {
Member member = getMember(email);
queryParamDto.setVegetarian(member.getVegetarianType());
}
return productRepository.findAllByVegetarianTypeName(vegetarianTypeName, PageRequest.of(page, size, Sort.by(sort).descending()));
return getAllByVegetarianType(queryParamDto);
}

@Override
Expand Down Expand Up @@ -95,7 +80,29 @@ public Product findExistProduct(Long productId) {
.orElseThrow(() -> new BusinessLogicException(ExceptionCode.PRODUCT_NOT_FOUND));
}

private boolean isAscending(String orderBy) {
return orderBy.equals("asc");
private boolean isDescending(String orderBy) {
return orderBy.equals("desc");
}

private boolean isNullInputType(String vegetarianType) {
return vegetarianType == null;
}

private Member getMember(String email) {
return memberRepository.findByEmail(email)
.orElseThrow(() -> new BusinessLogicException(MEMBER_NOT_FOUND));
}

private Page<Product> getAllByVegetarianType(QueryParamDto queryParamDto) {

Sort sort = Sort.by(queryParamDto.getSort());

if (isDescending(queryParamDto.getOrderBy())) {
sort = Sort.by(queryParamDto.getSort()).descending();
}
return productRepository.findAllByVegetarianTypeName(
queryParamDto.getVegetarian(),
PageRequest.of(queryParamDto.getPage(), queryParamDto.getSize(), sort)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Category {
public class
Category {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand All @@ -26,7 +27,6 @@ public class Category {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
@Nullable
//@JsonManagedReference
private Category parent;

/**
Expand Down
5 changes: 3 additions & 2 deletions server/src/main/java/com/noterror/app/api/entity/Product.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import com.noterror.app.api.entity.order.OrderProduct;
import com.noterror.app.api.domain.product.dto.ProductRequestDto;
import com.noterror.app.api.global.audit.Auditable;
import com.noterror.app.api.global.exception.OutOfStockException;
import com.noterror.app.api.global.exception.BusinessLogicException;
import com.noterror.app.api.global.exception.ExceptionCode;
import lombok.*;

import javax.persistence.*;
Expand Down Expand Up @@ -80,7 +81,7 @@ public void updateProductInfo(ProductRequestDto productRequestDto) {
public void removeStock(int quantity) {
int restStock = this.stockQuantity - quantity; //남은 재고
if (restStock < 0) {
throw new OutOfStockException("상품의 재고가 부족합니다. (현재 재고 수량 : " + this.stockQuantity + ")");
throw new BusinessLogicException(ExceptionCode.PRODUCT_SOLD_OUT);
}
this.stockQuantity = restStock;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class Member extends Auditable implements Principal {
@OneToOne(mappedBy = "member")
private Cart cart;

@ElementCollection
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(
name = "roles",
joinColumns = @JoinColumn(name = "member_id")
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import static com.noterror.app.api.global.exception.ExceptionCode.MEMBER_AUTH_FAIL;
import static com.noterror.app.api.global.exception.ExceptionCode.MEMBER_NOT_FOUND;

@Component
Expand All @@ -24,7 +25,7 @@ public MemberDetailsService(MemberRepository memberRepository, CustomAuthorityUt
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Member findMember = memberRepository.findByEmail(username)
.orElseThrow(() -> new BusinessLogicException(MEMBER_NOT_FOUND));
.orElseThrow(() -> new BusinessLogicException(MEMBER_AUTH_FAIL));
return new MemberDetails(findMember, authorityUtils);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.noterror.app.infra.filter;

import com.noterror.app.api.global.exception.BusinessLogicException;
import com.noterror.app.api.global.exception.ExceptionCode;
import com.noterror.app.api.global.exception.response.ErrorResponse;
import com.noterror.app.infra.auth.CustomAuthorityUtils;
import com.noterror.app.infra.jwt.JwtTokenizer;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -57,7 +60,13 @@ private Map<String, Object> verifyJws(HttpServletRequest request) {
// header 에서 JWT를 얻음
String jws = request.getHeader("Authorization").replace("Bearer ", "");
String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey());
Map<String, Object> claims = jwtTokenizer.getClaims(jws, base64EncodedSecretKey).getBody();
Map<String, Object> claims = null;
try {
claims = jwtTokenizer.getClaims(jws, base64EncodedSecretKey).getBody();
} catch (Exception e) {
ErrorResponse.of(ExceptionCode.MEMBER_EXPIRED_TOKEN);
}

return claims;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.noterror.app.infra.handler;

import com.noterror.app.api.global.exception.ExceptionCode;
import com.noterror.app.api.global.exception.response.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -21,5 +22,6 @@ public void handle(HttpServletRequest request,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ErrorResponse.sendErrorResponse(response, HttpStatus.FORBIDDEN);
log.warn("Forbidden error happened: {}", accessDeniedException.getMessage());
ErrorResponse.of(ExceptionCode.MEMBER_FORBIDDEN);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.noterror.app.infra.handler;

import com.noterror.app.api.global.exception.ExceptionCode;
import com.noterror.app.api.global.exception.response.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -22,7 +23,7 @@ public void commence(HttpServletRequest request,
AuthenticationException authException) throws IOException, ServletException {
Exception exception = (Exception) request.getAttribute("exception");
ErrorResponse.sendErrorResponse(response, HttpStatus.UNAUTHORIZED);

ErrorResponse.of(ExceptionCode.MEMBER_UNAUTHORIZED);
logExceptionMessage(authException, exception);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.noterror.app.infra.jwt;

import com.noterror.app.api.global.exception.ExceptionCode;
import com.noterror.app.api.global.exception.response.ErrorResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
Expand Down Expand Up @@ -76,11 +79,10 @@ private Key getKeyFromBase64EncodedKey(String base64EncodedSecretKey) {
// 검증 후, Claims을 반환 하는 용도
public Jws<Claims> getClaims(String jws, String base64EncodedSecretKey) {
Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);

Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(jws);
.setSigningKey(key)
.build()
.parseClaimsJws(jws);
return claims;
}

Expand Down
2 changes: 1 addition & 1 deletion server/src/main/resources/application-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ logging:
jpa: DEBUG

jwt:
access-token-expiration-minutes: 30
access-token-expiration-minutes: 60
refresh-token-expiration-minutes: 420
key:
secret: ${JWT_SECRET_KEY}
Expand Down
Loading

0 comments on commit e1023a6

Please sign in to comment.