Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing category model #7

Merged
merged 4 commits into from
Sep 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
</maven.checkstyle.plugin.configLocation>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<jjvt.version>0.11.5</jjvt.version>
</properties>

<dependencies>
Expand All @@ -53,11 +54,36 @@
<artifactId>spring-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjvt.version}</version>
</dependency>

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjvt.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjvt.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
Expand Down Expand Up @@ -132,7 +158,7 @@
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<sourceDirectories>${project.build.sourceDirectory},${project.build.testSourceDirectory}
</sourceDirectories>
<excludes>com/bookstore/dto/BookSearchParametersDto.java</excludes>
<excludes>com/bookstore/dto/book/BookSearchParametersDto.java,</excludes>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
Expand Down
62 changes: 62 additions & 0 deletions src/main/java/com/bookstore/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.bookstore.config;

import static org.springframework.security.config.Customizer.withDefaults;

import com.bookstore.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
@Configuration
public class SecurityConfig {
private final UserDetailsService userDetailsService;
private final JwtAuthenticationFilter jwtAuthenticationFilter;

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
auth -> auth
.requestMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated()
)
.httpBasic(withDefaults())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class)
.userDetailsService(userDetailsService)
.build();
}

@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration
) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.bookstore.controller;

import com.bookstore.dto.user.UserLoginRequestDto;
import com.bookstore.dto.user.UserLoginResponseDto;
import com.bookstore.dto.user.UserRegistrationRequestDto;
import com.bookstore.dto.user.UserResponseDto;
import com.bookstore.exception.RegistrationException;
import com.bookstore.security.AuthenticationService;
import com.bookstore.service.UserService;
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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Authentication", description = "User Registration and Login")
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/auth")
public class AuthenticationController {
private final UserService userService;
private final AuthenticationService authenticationService;

@PostMapping("/login")
@ResponseStatus(HttpStatus.ACCEPTED)
@Operation(summary = "User Log In",
description = "Login method")
public UserLoginResponseDto login(@RequestBody @Valid UserLoginRequestDto requestDto) {
return authenticationService.authenticate(requestDto);
}

@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
@Operation(summary = "User registration",
description = "Method for user registration(saves user to DB)")
public UserResponseDto register(@RequestBody @Valid UserRegistrationRequestDto request)
throws RegistrationException {
return userService.register(request);
}
}
32 changes: 20 additions & 12 deletions src/main/java/com/bookstore/controller/BookController.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.bookstore.controller;

import com.bookstore.dto.BookDto;
import com.bookstore.dto.BookSearchParametersDto;
import com.bookstore.dto.CreateBookRequestDto;
import com.bookstore.dto.book.BookDto;
import com.bookstore.dto.book.BookSearchParametersDto;
import com.bookstore.dto.book.CreateBookRequestDto;
import com.bookstore.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand All @@ -11,6 +11,7 @@
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -29,41 +30,48 @@ public class BookController {
private final BookService bookService;

@GetMapping
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Get all books", description = "Get a list of available books")
public List<BookDto> getAll(Pageable pageable) {
return bookService.getAll(pageable);
}

@GetMapping("/{id}")
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Get book by specific id", description = "Get book by specific id")
public BookDto getBookById(@PathVariable Long id) {
return bookService.getBookById(id);
}

@GetMapping("/search")
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Search books", description = "Search book by specific search parameters")
public List<BookDto> searchBooks(BookSearchParametersDto searchParameters) {
return bookService.searchBooks(searchParameters);
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
@Operation(summary = "Create a new book", description = "Create a new book")
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Create a new book(only for admins)", description = "Create a new book")
public BookDto createBook(@RequestBody @Valid CreateBookRequestDto bookRequestDto) {
return bookService.createBook(bookRequestDto);
}

@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
@Operation(summary = "Update the existing book", description = "Update the existing book")
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Update the existing book(only for admins)",
description = "Update the existing book")
public void updateBook(@PathVariable Long id,
@RequestBody @Valid CreateBookRequestDto bookRequestDto) {
bookService.updateBook(id, bookRequestDto);
}

@DeleteMapping("/{id}")
@Operation(summary = "Delete book", description = "Delete book by specific id")
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Delete book(only for admins)", description = "Delete book by specific id")
public void deleteBookById(@PathVariable Long id) {
bookService.deleteBookById(id);
}

@GetMapping("/search")
@Operation(summary = "Search books", description = "Search book by specific search parameters")
public List<BookDto> searchBooks(BookSearchParametersDto searchParameters) {
return bookService.searchBooks(searchParameters);
}
}
79 changes: 79 additions & 0 deletions src/main/java/com/bookstore/controller/CategoryController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.bookstore.controller;

import com.bookstore.dto.book.BookDtoWithoutCategoryIds;
import com.bookstore.dto.category.CategoryDto;
import com.bookstore.service.BookService;
import com.bookstore.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Category management", description = "Endpoints for managing categories")
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/categories")
public class CategoryController {
private final CategoryService categoryService;
private final BookService bookService;

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Create a new category(only for admins)",
description = "Create a new category")
public CategoryDto createCategory(@RequestBody CategoryDto categoryDto) {
return categoryService.save(categoryDto);
}

@GetMapping
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Get all categories", description = "Get all categories")
public List<CategoryDto> getAll(Pageable pageable) {
return categoryService.findAll(pageable);
}

@GetMapping("/{id}")
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Get category by specific id", description = "Get category by specific id")
public CategoryDto getCategoryById(@PathVariable Long id) {
return categoryService.getById(id);
}

@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Update category(only for admins)", description = "Update category")
public CategoryDto updateCategory(@PathVariable Long id,
@RequestBody CategoryDto categoryDto) {
return categoryService.update(id, categoryDto);
}

@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "Delete book(only for admins)", description = "Delete book")
public void deleteCategory(@PathVariable Long id) {
categoryService.deleteById(id);
}

@GetMapping("/{id}/books")
@PreAuthorize("hasRole('USER')")
@Operation(summary = "Get books by specific category_id",
description = "Get books by specific category_id")
public List<BookDtoWithoutCategoryIds> getBooksByCategoryId(@PathVariable Long id,
Pageable pageable) {
return bookService.findAllByCategoryId(id, pageable);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bookstore.dto;
package com.bookstore.dto.book;

import java.math.BigDecimal;
import java.util.Set;
import lombok.Data;

@Data
Expand All @@ -12,4 +13,5 @@ public class BookDto {
private BigDecimal price;
private String description;
private String coverImage;
private Set<Long> categoryIds;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.bookstore.dto.book;

import java.math.BigDecimal;
import lombok.Data;

@Data
public class BookDtoWithoutCategoryIds {
private Long id;
private String title;
private String author;
private String isbn;
private BigDecimal price;
private String description;
private String coverImage;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.bookstore.dto;
package com.bookstore.dto.book;

public record BookSearchParametersDto(String[] titles,
String[] authors,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.bookstore.dto;
package com.bookstore.dto.book;

import com.bookstore.validation.Isbn;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Set;
import lombok.Data;

@Data
Expand All @@ -19,4 +20,6 @@ public class CreateBookRequestDto {
private BigDecimal price;
private String description;
private String coverImage;
@NotNull
private Set<Long> categoryIds;
}
9 changes: 9 additions & 0 deletions src/main/java/com/bookstore/dto/category/CategoryDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.bookstore.dto.category;

import lombok.Data;

@Data
public class CategoryDto {
private String name;
private String description;
}
Loading
Loading