Skip to content

Commit

Permalink
Merge pull request #2 from noisrucer/feat/category-domain
Browse files Browse the repository at this point in the history
Feat/category domain
  • Loading branch information
noisrucer authored Jan 27, 2024
2 parents c021d7f + 59c4fc4 commit 9373836
Show file tree
Hide file tree
Showing 23 changed files with 472 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
Expand All @@ -37,7 +40,7 @@ public PasswordEncoder passwordEncoder() {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(CsrfConfigurer::disable)
.cors(CorsConfigurer::disable)
.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource()))
.formLogin(FormLoginConfigurer::disable)
.httpBasic(HttpBasicConfigurer::disable)
.authorizeHttpRequests((auth) -> auth
Expand All @@ -64,4 +67,18 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.addFilterBefore(new JwtFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();

config.addAllowedOrigin("http://localhost:5173");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);;

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,22 @@ public class CustomException extends RuntimeException {
@Getter
private ErrorInfo errorInfo;

private final String detailedMessage;

public CustomException(ErrorInfo errorInfo) {
super(errorInfo.getMessage());
this.errorInfo = errorInfo;
this.detailedMessage = null;
}

public CustomException(ErrorInfo errorInfo, String detailedMessage) {
super(detailedMessage);
this.errorInfo = errorInfo;
this.detailedMessage = detailedMessage;
}

@Override
public String getMessage() {
return detailedMessage != null ? detailedMessage : super.getMessage();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.girok.girokserver.core.exception;

public class CustomInternalException extends RuntimeException {

public CustomInternalException(String message) {
super(message);
}

public CustomInternalException(String message, Throwable cause) {
super(message, cause);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public enum ErrorInfo {
VERIFICATION_CODE_EXPIRED(400, "VERIFICATION_CODE_EXPIRED", "Verification code is expired"),
INVALID_PASSWORD(400, "INVALID_PASSWORD", "Password is invalid."),

/** Category **/
PARENT_CATEGORY_NOT_EXIST(400, "PARENT_CATEGORY_NOT_EXIST", "Parent Category does not exist."),
DUPLICATE_CATEGORY(400, "DUPLICATE_CATEGORY", "Parent category cannot have multiple child categories with the same name"),


/** JWT Exceptions **/
INVALID_JWT_TOKEN(401, "INVALID_JWT_TOKEN", "JWT token is invalid."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {
ErrorResponse errorResponse = new ErrorResponse(
errorInfo.getStatusCode(),
errorInfo.getErrorCode(),
errorInfo.getMessage()
e.getMessage()
);

return ResponseEntity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

SecurityContextHolder.getContext().setAuthentication(authentication);

JwtUserInfo info = (JwtUserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("info = " + info);
System.out.println("info.getUserId() = " + info.getUserId());


filterChain.doFilter(request, response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecurityException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.security.Key;
Expand Down Expand Up @@ -77,4 +78,8 @@ public JwtUserInfo validateAndExtractUserInfo(String token) {
throw new CustomException(INVALID_JWT_TOKEN);
}
}

public JwtUserInfo getCurrentUserInfo() {
return (JwtUserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "Authentication", description = "Authentication Process API")
@CrossOrigin(origins = "*", allowedHeaders = "*")
@Tag(name = "Authentication")
@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("/api/v1")
public class AuthController {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.girok.girokserver.domain.category.controller;

import com.girok.girokserver.core.security.jwt.JwtTokenProvider;
import com.girok.girokserver.core.security.jwt.dto.JwtUserInfo;
import com.girok.girokserver.domain.category.controller.request.CreateCategoryRequest;
import com.girok.girokserver.domain.category.controller.response.CreateCategoryResponse;
import com.girok.girokserver.domain.category.facade.CategoryFacade;
import com.girok.girokserver.domain.category.vo.CategoryPath;
import com.girok.girokserver.global.enums.CategoryColor;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "Category")
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class CategoryController {

private final CategoryFacade categoryFacade;
private final JwtTokenProvider jwtTokenProvider;

@PostMapping("/categories")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Create a new category")
public ResponseEntity<CreateCategoryResponse> createCategory(@Valid @RequestBody CreateCategoryRequest request) {
JwtUserInfo jwtUserInfo = jwtTokenProvider.getCurrentUserInfo();
Long userId = jwtUserInfo.getUserId();

CategoryColor color = request.getColor();
CategoryPath path = new CategoryPath(request.getPath());

Long categoryId = categoryFacade.createCategory(userId, color, path);
return ResponseEntity.ok().body(new CreateCategoryResponse(categoryId));
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.girok.girokserver.domain.category.controller.request;

import com.girok.girokserver.domain.category.vo.CategoryPath;
import com.girok.girokserver.global.enums.CategoryColor;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;

import java.util.List;

@Getter
public class CreateCategoryRequest {

@NotNull
@Schema(example = "YELLOW")
private CategoryColor color;

@NotEmpty
@Schema(example = "[\"Career\", \"Work\", \"Interview\"]")
private List<String> path;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.girok.girokserver.domain.category.controller.response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class CreateCategoryResponse {

private Long categoryId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.girok.girokserver.domain.category.entity;

import com.girok.girokserver.domain.member.entity.Member;
import com.girok.girokserver.global.baseentity.AuditBase;
import com.girok.girokserver.global.enums.CategoryColor;
import jakarta.persistence.*;
import lombok.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Entity
@Table(name = "category", uniqueConstraints = {
@UniqueConstraint(columnNames = {"parent_id", "name"})
})
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Getter
@Builder
public class Category extends AuditBase {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "name", nullable = false)
private String name;

@Setter
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id", nullable = false)
private Member member;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Category parent;

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Category> children = new ArrayList<>();

@Enumerated(EnumType.STRING)
@Column(name = "color", nullable = false)
private CategoryColor color;

// Constructor methods
public static Category createCategory(Member member, Category parentCategory, String name, CategoryColor color) {
Category category = Category.builder()
.member(member)
.parent(parentCategory) // parent can be null
.name(name)
.color(color)
.build();

member.addCategory(category); // TODO: member.addCategory(category)하면 category.assignMember() 중복
if (parentCategory != null) {
parentCategory.addChildCategory(category);
}
return category;
}


// Relation methods
/**
* Add a child category (<->)
*/
public void addChildCategory(Category childCategory) {
this.children.add(childCategory);
childCategory.parent = this;
}

public void assignParent(Category parentCategory) {
this.parent = parentCategory;
parentCategory.getChildren().add(this);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.girok.girokserver.domain.category.exception;

public class RootCategoryNameAccessException extends RuntimeException {

public RootCategoryNameAccessException() {
super("Root category does not have a parent category.");
}

public RootCategoryNameAccessException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.girok.girokserver.domain.category.exception;

import com.girok.girokserver.core.exception.CustomInternalException;

public class RootCategoryParentAccessException extends CustomInternalException {

public RootCategoryParentAccessException() {
super("Root category does not have a parent category.");
}

public RootCategoryParentAccessException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.girok.girokserver.domain.category.facade;

import com.girok.girokserver.domain.category.entity.Category;
import com.girok.girokserver.domain.category.service.CategoryService;
import com.girok.girokserver.domain.category.vo.CategoryPath;
import com.girok.girokserver.domain.member.entity.Member;
import com.girok.girokserver.domain.member.service.MemberService;
import com.girok.girokserver.global.enums.CategoryColor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class CategoryFacade {

private final CategoryService categoryService;
private final MemberService memberService;

@Transactional
public Long createCategory(Long userId, CategoryColor color, CategoryPath path) {
Member member = memberService.findMemberById(userId);
System.out.println("A");
Category category = categoryService.createCategory(member, color, path);
return category.getId();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.girok.girokserver.domain.category.repository;

import com.girok.girokserver.domain.category.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface CategoryRepository extends JpaRepository<Category, Long> {

Optional<Category> findByParentAndName(Category parentCategory, String name);

}
Loading

0 comments on commit 9373836

Please sign in to comment.