Vue работает

This commit is contained in:
maxnes3 2023-05-25 14:50:27 +04:00
parent f4ba1554a2
commit fc036d77f2
49 changed files with 792 additions and 1144 deletions

View File

@ -1,7 +1,6 @@
/*package ru.ip.labworks.labworks.bookshop.controller; package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.AuthorService; import ru.ip.labworks.labworks.bookshop.service.AuthorService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.io.IOException; import java.io.IOException;
@ -9,7 +8,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/author") @RequestMapping("/author")
public class AuthorController { public class AuthorController {
private final AuthorService authorService; private final AuthorService authorService;
@ -62,4 +61,4 @@ public class AuthorController {
public Map<String, List<String>> getAuthorsBooks(){ public Map<String, List<String>> getAuthorsBooks(){
return authorService.AllAuthorsAndBooks(); return authorService.AllAuthorsAndBooks();
} }
}*/ }

View File

@ -9,6 +9,7 @@ public class AuthorDto {
private String firstname; private String firstname;
private String lastname; private String lastname;
private String photo; private String photo;
private String login;
public AuthorDto(){} public AuthorDto(){}
public AuthorDto(Author author){ public AuthorDto(Author author){
@ -16,15 +17,18 @@ public class AuthorDto {
firstname = author.getFirstnameName(); firstname = author.getFirstnameName();
lastname = author.getLastName(); lastname = author.getLastName();
photo = new String(author.getPhoto(), StandardCharsets.UTF_8); photo = new String(author.getPhoto(), StandardCharsets.UTF_8);
login = author.getUser().getLogin();
} }
public Long getId(){return id;} public Long getId(){return id;}
public String getFirstname(){return firstname;} public String getFirstname(){return firstname;}
public String getLastname(){return lastname;} public String getLastname(){return lastname;}
public String getPhoto(){return photo;} public String getPhoto(){return photo;}
public String getLogin(){return login;}
public void setId(Long id){this.id = id;} public void setId(Long id){this.id = id;}
public void setFirstname(String firstname){this.firstname = firstname;} public void setFirstname(String firstname){this.firstname = firstname;}
public void setLastname(String lastname){this.lastname = lastname;} public void setLastname(String lastname){this.lastname = lastname;}
public void setPhoto(String photo){this.photo = photo;} public void setPhoto(String photo){this.photo = photo;}
public void setLogin(String login){this.login = login;}
} }

View File

@ -1,114 +0,0 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.ip.labworks.labworks.bookshop.service.AuthorService;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
@Controller
@RequestMapping("/author")
public class AuthorMvcController {
private final AuthorService authorService;
private final BookService bookService;
private final UserService userService;
public AuthorMvcController(UserService userService, AuthorService authorService, BookService bookService)
{
this.authorService = authorService;
this.bookService = bookService;
this.userService = userService;
}
@GetMapping
public String getAuthors(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("authors",
authorService.findAllAuthors().stream()
.map(AuthorDto::new)
.toList());
return "authors";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String updateAuthor(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("authorDto", new AuthorDto());
} else {
model.addAttribute("authorDto", id);
model.addAttribute("authorDto", new AuthorDto(authorService.findAuthor(id)));
}
return "author-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveAuthor(@PathVariable(required = false) Long id,
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
@ModelAttribute("authorDto") AuthorDto authorDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "author-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
authorDto.setPhoto("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
if (id == null || id <= 0) {
return "redirect:/author/" + authorService.addAuthor(authorDto, userId).getId().toString() + "/books";
} else {
authorService.updateAuthor(id, authorDto, userId);
}
return "redirect:/author";
}
@PostMapping("/delete/{id}")
public String deleteAuthor(@PathVariable Long id, Principal principal) {
authorService.deleteAuthor(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/author";
}
@GetMapping("/{id}/books")
public String getAuthorBooks(@PathVariable Long id, Model model){
model.addAttribute("author",
new AuthorDto(authorService.findAuthor(id)));
model.addAttribute("authorbooks",
authorService.authorBooks(id).stream()
.map(BookDto::new)
.toList());
model.addAttribute("books",
bookService.findAllBooks().stream()
.map(BookDto::new)
.toList());
return "author-mtm";
}
@PostMapping("/{id}/books")
public String addBookToAuthor(@PathVariable Long id, @RequestParam(value = "bookid") Long bookid, Principal principal){
authorService.addBookToAuthor(id, bookid, userService.findByLogin(principal.getName()).getId());
return "redirect:/author/" + id.toString() + "/books";
}
@PostMapping("/{id}/books/{bookid}")
public String removeBookFromAuthor(@PathVariable Long id, @PathVariable Long bookid, Principal principal){
authorService.removeBookFromAuthor(id, bookid, userService.findByLogin(principal.getName()).getId());
return "redirect:/author/" + id.toString() + "/books";
}
@GetMapping("/books")
private String getAllAuthorsBooks(Model model){
model.addAttribute("authorsbooks",
authorService.AllAuthorsAndBooks());
return "all-authors-books";
}
}

View File

@ -1,15 +1,13 @@
/*
package ru.ip.labworks.labworks.bookshop.controller; package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.BookService; import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/book") @RequestMapping("/book")
public class BookController { public class BookController {
private final BookService bookService; private final BookService bookService;
@ -58,4 +56,3 @@ public class BookController {
bookService.deleteBook(id); bookService.deleteBook(id);
} }
} }
*/

View File

@ -12,6 +12,7 @@ public class BookDto {
@DateTimeFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date release; private Date release;
private String cover; private String cover;
private String login;
public BookDto(){} public BookDto(){}
public BookDto(Book book){ public BookDto(Book book){
@ -19,15 +20,18 @@ public class BookDto {
name = book.getName(); name = book.getName();
release = book.getRelease(); release = book.getRelease();
cover = new String(book.getCover(), StandardCharsets.UTF_8); cover = new String(book.getCover(), StandardCharsets.UTF_8);
login = book.getUser().getLogin();
} }
public Long getId(){return id;} public Long getId(){return id;}
public String getName(){return name;} public String getName(){return name;}
public Date getRelease(){return release;} public Date getRelease(){return release;}
public String getCover(){return cover;} public String getCover(){return cover;}
public String getLogin(){return login;}
public void setId(Long id){this.id = id;} public void setId(Long id){this.id = id;}
public void setName(String name){this.name = name;} public void setName(String name){this.name = name;}
public void setRelease(Date release){this.release = release;} public void setRelease(Date release){this.release = release;}
public void setCover(String cover){this.cover = cover;} public void setCover(String cover){this.cover = cover;}
public void setLogin(String login){this.login = login;}
} }

View File

@ -1,106 +0,0 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
@Controller
@RequestMapping("/book")
public class BookMvcController {
private final BookService bookService;
private final GenreService genreService;
private final UserService userService;
public BookMvcController(BookService bookService, GenreService genreService, UserService userService){
this.bookService = bookService;
this.genreService = genreService;
this.userService = userService;
}
@GetMapping
public String getBooks(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("books",
bookService.findAllBooks().stream()
.map(BookDto::new)
.toList());
return "books";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String updateBook(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("bookDto", new BookDto());
} else {
model.addAttribute("bookDto", id);
model.addAttribute("bookDto", new BookDto(bookService.findBook(id)));
}
return "book-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveBook(@PathVariable(required = false) Long id,
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
@ModelAttribute("bookDto") BookDto bookDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "book-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
bookDto.setCover("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
if (id == null || id <= 0) {
return "redirect:/book/" + bookService.addBook(bookDto, userId).getId().toString() + "/genres";
} else {
bookService.updateBook(id, bookDto, userId);
}
return "redirect:/book";
}
@PostMapping("/delete/{id}")
public String deleteBook(@PathVariable Long id, Principal principal) {
bookService.deleteBook(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/book";
}
@GetMapping("/{id}/genres")
public String getBookGenres(@PathVariable Long id, Model model){
model.addAttribute("book",
new BookDto(bookService.findBook(id)));
model.addAttribute("bookgenres",
bookService.bookGenres(id).stream()
.map(GenreDto::new)
.toList());
model.addAttribute("genres",
genreService.findAllGenres().stream()
.map(GenreDto::new)
.toList());
return "book-mtm";
}
@PostMapping("/{id}/genres")
public String addGenreToBook(@PathVariable Long id, @RequestParam(value = "genreid") Long genreid, Principal principal){
bookService.addGenreToBook(id, genreid, userService.findByLogin(principal.getName()).getId());
return "redirect:/book/" + id.toString() + "/genres";
}
@PostMapping("/{id}/genres/{genreid}")
public String removeGenreFromBook(@PathVariable Long id, @PathVariable Long genreid, Principal principal){
bookService.removeGenreFromBook(id, genreid, userService.findByLogin(principal.getName()).getId());
return "redirect:/book/" + id.toString() + "/genres";
}
}

View File

@ -1,14 +1,13 @@
/*package ru.ip.labworks.labworks.bookshop.controller; package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.GenreService; import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/genre") @RequestMapping("/genre")
public class GenreController { public class GenreController {
private final GenreService genreService; private final GenreService genreService;
@ -40,4 +39,4 @@ public class GenreController {
public void deleteGenre(@PathVariable Long id){ public void deleteGenre(@PathVariable Long id){
genreService.deleteGenre(id); genreService.deleteGenre(id);
} }
}*/ }

View File

@ -5,16 +5,20 @@ import ru.ip.labworks.labworks.bookshop.model.Genre;
public class GenreDto { public class GenreDto {
private Long id; private Long id;
private String name; private String name;
private String login;
public GenreDto(){} public GenreDto(){}
public GenreDto(Genre genre){ public GenreDto(Genre genre){
id = genre.getId(); id = genre.getId();
name = genre.getName(); name = genre.getName();
login = genre.getUser().getLogin();
} }
public Long getId(){return id;} public Long getId(){return id;}
public String getName(){return name;} public String getName(){return name;}
public String getLogin(){return login;}
public void setId(Long id){this.id = id;} public void setId(Long id){this.id = id;}
public void setName(String name){this.name = name;} public void setName(String name){this.name = name;}
public void setLogin(String login){this.login = login;}
} }

View File

@ -1,72 +0,0 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
@Controller
@RequestMapping("/genre")
public class GenreMvcController {
private final GenreService genreService;
private final UserService userService;
public GenreMvcController(GenreService genreService, UserService userService){
this.genreService = genreService;
this.userService = userService;
}
@GetMapping
public String getBooks(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("genres",
genreService.findAllGenres().stream()
.map(GenreDto::new)
.toList());
return "genres";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String editBook(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("genreDto", new GenreDto());
} else {
model.addAttribute("genreDto", id);
model.addAttribute("genreDto", new GenreDto(genreService.findGenre(id)));
}
return "genre-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveBook(@PathVariable(required = false) Long id,
@ModelAttribute("genreDto") GenreDto genreDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "genre-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
if (id == null || id <= 0) {
genreService.addGenre(genreDto, userId);
} else {
genreService.updateGenre(id, genreDto, userId);
}
return "redirect:/genre";
}
@PostMapping("/delete/{id}")
public String deleteGenre(@PathVariable Long id, Principal principal) {
genreService.deleteGenre(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/genre";
}
}

View File

@ -0,0 +1,64 @@
package ru.ip.labworks.labworks.bookshop.controller;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGN_UP = "/sign_up";
public static final String URL_WHO_AM_I = "/who_am_i";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
@GetMapping(URL_WHO_AM_I)
public String role(@RequestParam("userLogin") String userLogin) {
return userService.findByLogin(userLogin).getRole().name();
}
@PostMapping(URL_SIGN_UP)
public String signUp(@RequestBody @Valid UserSignUpDTO userSignupDto) {
try {
final User user = userService.addUser(userSignupDto.getLogin(),
userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), UserRole.USER);
return "created " + user.getLogin();
} catch (ValidationException e) {
return e.getMessage();
}
}
@GetMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public UserDto getUser(@PathVariable Long id) {
return new UserDto(userService.findUser(id));
}
@GetMapping("/")
@Secured({UserRole.AsString.ADMIN})
public List<UserDto> getUsers() {
return userService.findAllUsers().stream()
.map(UserDto::new)
.toList();
}
@PutMapping("/{id}")
public UserDto updateUser(@RequestBody @Valid UserDto userDto){
return new UserDto(userService.updateUser(userDto));
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}

View File

@ -4,14 +4,17 @@ import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole; import ru.ip.labworks.labworks.bookshop.model.UserRole;
public class UserDto { public class UserDto {
private final long id; private long id;
private final String login; private String login;
private final UserRole role; private UserRole role;
private String password;
public UserDto(){}
public UserDto(User user) { public UserDto(User user) {
this.id = user.getId(); this.id = user.getId();
this.login = user.getLogin(); this.login = user.getLogin();
this.role = user.getRole(); this.role = user.getRole();
this.password = user.getPassword();
} }
public long getId() { public long getId() {
@ -25,4 +28,23 @@ public class UserDto {
public UserRole getRole() { public UserRole getRole() {
return role; return role;
} }
public String getPassword()
{
return password;
}
public void setId(Long id) {
this.id = id;
}
public void setLogin(String login)
{
this.login = login;
}
public void setPassword(String password)
{
this.password = password;
}
} }

View File

@ -1,41 +0,0 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -1,48 +0,0 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
@Controller
@RequestMapping(UserSignUpMvcController.SIGNUP_URL)
public class UserSignUpMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignUpMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("UserDTO", new UserSignUpDTO());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("UserDTO") @Valid UserSignUpDTO userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -4,6 +4,8 @@ import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import ru.ip.labworks.labworks.bookshop.controller.UserSignUpDTO;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@ -35,6 +37,12 @@ public class User {
this.role = role; this.role = role;
} }
public User(UserSignUpDTO userDto){
this.login = userDto.getLogin();
this.password = userDto.getPassword();
this.role = UserRole.USER;
}
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -45,8 +45,8 @@ public class AuthorService {
} }
@Transactional @Transactional
public Author addAuthor(AuthorDto authorDto, Long userId) throws IOException { public Author addAuthor(AuthorDto authorDto) throws IOException {
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(authorDto.getLogin());
final Author author = new Author(authorDto); final Author author = new Author(authorDto);
author.setUser(currentUser); author.setUser(currentUser);
validatorUtil.validate(author); validatorUtil.validate(author);
@ -88,8 +88,8 @@ public class AuthorService {
} }
@Transactional @Transactional
public Author updateAuthor(Long id, AuthorDto authorDto, Long userId){ public Author updateAuthor(Long id, AuthorDto authorDto){
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(authorDto.getLogin());
final Author currentAuthor = findAuthor(id); final Author currentAuthor = findAuthor(id);
if(currentUser.getId() != currentAuthor.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){ if(currentUser.getId() != currentAuthor.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null; return null;
@ -102,12 +102,7 @@ public class AuthorService {
} }
@Transactional @Transactional
public void deleteAuthor(Long id, Long userId) { public void deleteAuthor(Long id) {
User currentUser = userService.findUser(userId);
final Author currentAuthor = findAuthor(id);
if(currentUser.getId() != currentAuthor.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
authorRepository.deleteById(id); authorRepository.deleteById(id);
} }
@ -117,12 +112,8 @@ public class AuthorService {
} }
@Transactional @Transactional
public void addBookToAuthor(Long id, Long bookId, Long userId){ public void addBookToAuthor(Long id, Long bookId){
User currentUser = userService.findUser(userId);
Optional<Author> author = authorRepository.findById(id); Optional<Author> author = authorRepository.findById(id);
if(currentUser.getId() != author.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if (author.isPresent() && !author.get().getBooks().contains(bookService.findBook(bookId))){ if (author.isPresent() && !author.get().getBooks().contains(bookService.findBook(bookId))){
author.get().addBook(bookService.findBook(bookId)); author.get().addBook(bookService.findBook(bookId));
} }
@ -130,12 +121,8 @@ public class AuthorService {
} }
@Transactional @Transactional
public void removeBookFromAuthor(Long id, Long bookId, Long userId){ public void removeBookFromAuthor(Long id, Long bookId){
User currentUser = userService.findUser(userId);
Optional<Author> author = authorRepository.findById(id); Optional<Author> author = authorRepository.findById(id);
if(currentUser.getId() != author.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if(author.isPresent() && author.get().getBooks().contains(bookService.findBook(bookId))){ if(author.isPresent() && author.get().getBooks().contains(bookService.findBook(bookId))){
author.get().removeBook(bookService.findBook(bookId)); author.get().removeBook(bookService.findBook(bookId));
} }

View File

@ -58,8 +58,8 @@ public class BookService {
} }
@Transactional @Transactional
public Book addBook(BookDto bookDto, Long userId) throws IOException { public Book addBook(BookDto bookDto) throws IOException {
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(bookDto.getLogin());
final Book book = new Book(bookDto); final Book book = new Book(bookDto);
book.setUser(currentUser); book.setUser(currentUser);
validatorUtil.validate(book); validatorUtil.validate(book);
@ -96,8 +96,8 @@ public class BookService {
} }
@Transactional @Transactional
public Book updateBook(Long id, BookDto bookDto, Long userId){ public Book updateBook(Long id, BookDto bookDto){
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(bookDto.getLogin());
final Book currentBook = findBook(id); final Book currentBook = findBook(id);
if(currentUser.getId() != currentBook.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){ if(currentUser.getId() != currentBook.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null; return null;
@ -110,12 +110,7 @@ public class BookService {
} }
@Transactional @Transactional
public void deleteBook(Long id, Long userId) { public void deleteBook(Long id) {
User currentUser = userService.findUser(userId);
final Book currentBook = findBook(id);
if(currentUser.getId() != currentBook.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
bookRepository.deleteById(id); bookRepository.deleteById(id);
} }
@ -125,12 +120,8 @@ public class BookService {
} }
@Transactional @Transactional
public void addGenreToBook(Long id, Long genreId, Long userId){ public void addGenreToBook(Long id, Long genreId){
User currentUser = userService.findUser(userId);
Optional<Book> book = bookRepository.findById(id); Optional<Book> book = bookRepository.findById(id);
if(currentUser.getId() != book.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if (book.isPresent() && !book.get().getGenres().contains(genreService.findGenre(genreId))){ if (book.isPresent() && !book.get().getGenres().contains(genreService.findGenre(genreId))){
book.get().addGenre(genreService.findGenre(genreId)); book.get().addGenre(genreService.findGenre(genreId));
} }
@ -138,12 +129,8 @@ public class BookService {
} }
@Transactional @Transactional
public void removeGenreFromBook(Long id, Long genreId, Long userId){ public void removeGenreFromBook(Long id, Long genreId){
User currentUser = userService.findUser(userId);
Optional<Book> book = bookRepository.findById(id); Optional<Book> book = bookRepository.findById(id);
if(currentUser.getId() != book.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if(book.isPresent() && book.get().getGenres().contains(genreService.findGenre(genreId))){ if(book.isPresent() && book.get().getGenres().contains(genreService.findGenre(genreId))){
book.get().removeGenre(genreService.findGenre(genreId)); book.get().removeGenre(genreService.findGenre(genreId));
} }

View File

@ -39,8 +39,8 @@ public class GenreService {
return genreRepository.save(genre); return genreRepository.save(genre);
} }
@Transactional @Transactional
public Genre addGenre(GenreDto genreDto, Long userId) throws IOException { public Genre addGenre(GenreDto genreDto) throws IOException {
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(genreDto.getLogin());
final Genre genre = new Genre(genreDto); final Genre genre = new Genre(genreDto);
genre.setUser(currentUser); genre.setUser(currentUser);
validatorUtil.validate(genre); validatorUtil.validate(genre);
@ -69,8 +69,8 @@ public class GenreService {
} }
@Transactional @Transactional
public Genre updateGenre(Long id, GenreDto genreDto, Long userId){ public Genre updateGenre(Long id, GenreDto genreDto){
User currentUser = userService.findUser(userId); User currentUser = userService.findByLogin(genreDto.getLogin());
final Genre currentGenre = findGenre(id); final Genre currentGenre = findGenre(id);
if(currentUser.getId() != currentGenre.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){ if(currentUser.getId() != currentGenre.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null; return null;
@ -80,12 +80,7 @@ public class GenreService {
} }
@Transactional @Transactional
public void deleteGenre(Long id, Long userId) { public void deleteGenre(Long id) {
User currentUser = userService.findUser(userId);
final Genre currentGenre = findGenre(id);
if(currentUser.getId() != currentGenre.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
genreRepository.deleteById(id); genreRepository.deleteById(id);
} }

View File

@ -9,12 +9,19 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ip.labworks.labworks.bookshop.controller.UserDto;
import ru.ip.labworks.labworks.bookshop.controller.UserSignUpDTO;
import ru.ip.labworks.labworks.bookshop.model.User; import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole; import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.repository.UserRepository; import ru.ip.labworks.labworks.bookshop.repository.UserRepository;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import ru.ip.labworks.labworks.configuration.jwt.JwtException;
import ru.ip.labworks.labworks.configuration.jwt.JwtProvider;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@ -22,31 +29,77 @@ import java.util.Optional;
public class UserService implements UserDetailsService { public class UserService implements UserDetailsService {
private final UserRepository userRepository; private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository, public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder) { PasswordEncoder passwordEncoder,
JwtProvider jwtProvider){
this.userRepository = userRepository; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
} this.jwtProvider = jwtProvider;
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
} }
public User findByLogin(String login) { public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login); return userRepository.findOneByLoginIgnoreCase(login);
} }
public User createUser(String login, String password, String passwordConfirm) { public Page<User> findAllPages(int page, int size) {
return createUser(login, password, passwordConfirm, UserRole.USER); return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
} }
public User createUser(String login, String password, String passwordConfirm, UserRole role) { @Transactional
public User addUser(UserSignUpDTO userDto){
final User user = new User(userDto);
userRepository.save(user);
return user;
}
@Transactional
public User addUser(String login, String password,
String passwordConfirm,
UserRole role){
if (findByLogin(login) != null) { if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login)); throw new ValidationException(String.format("User '%s' already exists", login));
} }
final User user = new User(login, passwordEncoder.encode(password), role);
if (!Objects.equals(password, passwordConfirm)) { if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals"); throw new ValidationException("Passwords not equals");
} }
final User user = new User(login,passwordEncoder.encode(password),role);
return userRepository.save(user); return userRepository.save(user);
} }
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
@Transactional
public User updateUser(UserDto userDto) {
final User currentUser = findUser(userDto.getId());
currentUser.setLogin(userDto.getLogin());
currentUser.setPassword(userDto.getPassword());
return userRepository.save(currentUser);
}
@Transactional
public User updateUser(Long id,String login, String password) {
if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("User name, login or password is null or empty");
}
final User currentUser = findUser(id);
currentUser.setLogin(login);
currentUser.setPassword(password);
return userRepository.save(currentUser);
}
@Transactional
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
@Transactional
public void deleteAllUsers() {
userRepository.deleteAll();
}
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
@ -57,10 +110,20 @@ public class UserService implements UserDetailsService {
return new org.springframework.security.core.userdetails.User( return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole())); userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
} }
public String loginAndGetToken(UserDto userDto) {
@Transactional(readOnly = true) final User user = findByLogin(userDto.getLogin());
public User findUser(Long id) { if (user == null) {
final Optional<User> user = userRepository.findById(id); }
return user.orElseThrow(() -> new UserNotFoundException(id)); if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
} }
} }

View File

@ -10,10 +10,13 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import ru.ip.labworks.labworks.bookshop.controller.UserSignUpMvcController; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.ip.labworks.labworks.bookshop.controller.UserController;
import ru.ip.labworks.labworks.bookshop.model.UserRole; import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService; import ru.ip.labworks.labworks.bookshop.service.UserService;
import ru.ip.labworks.labworks.configuration.jwt.JwtFilter;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -23,10 +26,15 @@ import ru.ip.labworks.labworks.bookshop.service.UserService;
public class SecurityConfiguration { public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login"; private static final String LOGIN_URL = "/login";
private final UserService userService; public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
public SecurityConfiguration(UserService userService) { private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService)
{
this.userService = userService; this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup(); createAdminOnStartup();
} }
@ -34,35 +42,44 @@ public class SecurityConfiguration {
final String admin = "admin"; final String admin = "admin";
if (userService.findByLogin(admin) == null) { if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created"); log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN); userService.addUser(admin, admin, admin, UserRole.ADMIN);
} }
} }
@Bean @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and() http.cors()
.cors().and() .and()
.csrf().disable() .csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests() .authorizeHttpRequests()
.requestMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll() .requestMatchers("", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll() .requestMatchers("/", SPA_URL_MASK).permitAll()
.anyRequest().authenticated() .requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SIGN_UP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_WHO_AM_I).permitAll()
.anyRequest()
.authenticated()
.and() .and()
.formLogin() .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.loginPage(LOGIN_URL).permitAll() .anonymous();
.defaultSuccessUrl("/author", true)
.and()
.logout().permitAll();
return http.userDetailsService(userService).build(); return http.userDetailsService(userService).build();
} }
@Bean @Bean
public WebSecurityCustomizer webSecurityCustomizer() { public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring() return (web) -> web.ignoring()
.requestMatchers("/css/**") .requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/js/**") .requestMatchers("/*.js")
.requestMatchers("/templates/**") .requestMatchers("/*.html")
.requestMatchers("/webjars/**"); .requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console/**");
} }
} }

View File

@ -2,18 +2,10 @@ package ru.ip.labworks.labworks.configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*"); registry.addMapping("/**").allowedMethods("*");

View File

@ -0,0 +1,11 @@
package ru.ip.labworks.labworks.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,72 @@
package ru.ip.labworks.labworks.configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer ";
private final UserService userService;
public JwtFilter(UserService userService) {
this.userService = userService;
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION);
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
return bearer.substring(TOKEN_BEGIN_STR.length());
}
return null;
}
private void raiseException(ServletResponse response, int status, String message) throws IOException {
if (response instanceof final HttpServletResponse httpResponse) {
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpResponse.setStatus(status);
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
response.getOutputStream().write(body);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof final HttpServletRequest httpRequest) {
final String token = getTokenFromRequest(httpRequest);
if (StringUtils.hasText(token)) {
try {
final UserDetails user = userService.loadUserByToken(token);
final UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException e) {
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
String.format("Internal error: %s", e.getMessage()));
return;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package ru.ip.labworks.labworks.configuration.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
public class JwtProperties {
private String devToken = "";
private Boolean isDev = true;
public String getDevToken() {
return devToken;
}
public void setDevToken(String devToken) {
this.devToken = devToken;
}
public Boolean isDev() {
return isDev;
}
public void setDev(Boolean dev) {
isDev = dev;
}
}

View File

@ -0,0 +1,108 @@
package ru.ip.labworks.labworks.configuration.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
@Component
public class JwtProvider {
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
private final static String ISSUER = "auth0";
private final Algorithm algorithm;
private final JWTVerifier verifier;
public JwtProvider(JwtProperties jwtProperties) {
if (!jwtProperties.isDev()) {
LOG.info("Generate new JWT key for prod");
try {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
} catch (NoSuchAlgorithmException e) {
throw new JwtException(e);
}
} else {
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
}
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
public String generateToken(String login) {
final Date issueDate = Date.from(LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
final Date expireDate = Date.from(LocalDate.now()
.plusDays(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
var temp = JWT.create();
var temp2 = temp.withIssuer(ISSUER);
var temp3 = temp2.withIssuedAt(issueDate);
var temp4 = temp3.withExpiresAt(expireDate);
var temp5 = temp4.withSubject(login);
var temp6 = temp5.sign(algorithm);
return temp6;
}
private DecodedJWT validateToken(String token) {
try {
return verifier.verify(token);
} catch (JWTVerificationException e) {
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
}
}
public boolean isTokenValid(String token) {
if (!StringUtils.hasText(token)) {
return false;
}
try {
validateToken(token);
return true;
} catch (JwtException e) {
LOG.error(e.getMessage());
return false;
}
}
public Optional<String> getLoginFromToken(String token) {
try {
return Optional.ofNullable(validateToken(token).getSubject());
} catch (JwtException e) {
LOG.error(e.getMessage());
return Optional.empty();
}
}
}

View File

@ -9,3 +9,6 @@ spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true spring.h2.console.enabled=true
spring.h2.console.settings.trace=false spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false spring.h2.console.settings.web-allow-others=false
jwt.dev-token=my-secret-jwt
jwt.dev=true
jwt.secret = my-secret-jwt

View File

@ -13,6 +13,7 @@
<a class="nav-link active" aria-current="page" href="/authors">Authors</a> <a class="nav-link active" aria-current="page" href="/authors">Authors</a>
<a class="nav-link active" href="/books">Books</a> <a class="nav-link active" href="/books">Books</a>
<a class="nav-link active" href="/genres">Genres</a> <a class="nav-link active" href="/genres">Genres</a>
<a class="nav-link active" href="/users">Users</a>
</div> </div>
</div> </div>
</div> </div>

View File

@ -26,11 +26,38 @@ export default{
bookid: 0, bookid: 0,
URL: "http://localhost:8080/", URL: "http://localhost:8080/",
author: new Author(), author: new Author(),
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
} }
}, },
methods:{ methods:{
getAuthors(){ getAuthors(){
axios.get(this.URL + "author") axios.get(this.URL + "author", this.getParams)
.then(response => { .then(response => {
this.authors = response.data; this.authors = response.data;
console.log(response.data); console.log(response.data);
@ -41,8 +68,9 @@ export default{
}, },
async addAuthor(){ async addAuthor(){
await this.toBase64(); await this.toBase64();
this.author.login = localStorage.getItem("user");
console.log(this.author); console.log(this.author);
axios.post(this.URL + "author", this.author) axios.post(this.URL + "author", this.author, this.postParams)
.then((response) => { .then((response) => {
this.getAuthors(); this.getAuthors();
this.closeModal(); this.closeModal();
@ -54,14 +82,14 @@ export default{
}); });
}, },
deleteAuthor(id){ deleteAuthor(id){
axios.delete(this.URL + `author/${id}`) axios.delete(this.URL + `author/${id}`, this.delParams)
.then(() =>{ .then(() =>{
this.getAuthors(); this.getAuthors();
}) })
}, },
async updateAuthor(author){ async updateAuthor(author){
if(author.photo === undefined) await this.toBase64(); if(author.photo === undefined) await this.toBase64();
axios.put(this.URL + `author/${author.id}`, this.author) axios.put(this.URL + `author/${author.id}`, this.author, this.putParams)
.then(() =>{ .then(() =>{
this.getAuthors(); this.getAuthors();
}) })
@ -106,7 +134,7 @@ export default{
}); });
}, },
getAllBooks(){ getAllBooks(){
axios.get(this.URL + "book") axios.get(this.URL + "book", this.getParams)
.then(response => { .then(response => {
this.allBooks = response.data; this.allBooks = response.data;
console.log(response.data); console.log(response.data);
@ -116,7 +144,7 @@ export default{
}); });
}, },
getAuthorBooks(){ getAuthorBooks(){
axios.get(this.URL + `author/${this.author.id}/books`) axios.get(this.URL + `author/${this.author.id}/books`, this.getParams)
.then(response => { .then(response => {
this.authorBooks = response.data; this.authorBooks = response.data;
console.log(response.data); console.log(response.data);
@ -127,7 +155,7 @@ export default{
}, },
addBook(){ addBook(){
console.log(this.bookid + " " + this.author.id); console.log(this.bookid + " " + this.author.id);
axios.post(this.URL + `author/${this.author.id}/Book/${this.bookid}`) axios.post(this.URL + `author/${this.author.id}/Book/${this.bookid}`, null, this.postParams)
.then(() => { .then(() => {
this.getAuthorBooks(); this.getAuthorBooks();
}) })
@ -136,13 +164,13 @@ export default{
}); });
}, },
removeBook(id){ removeBook(id){
axios.delete(this.URL + `author/${this.author.id}/Book/${id}`) axios.delete(this.URL + `author/${this.author.id}/Book/${id}`, this.delParams)
.then(() =>{ .then(() =>{
this.getAuthorBooks(); this.getAuthorBooks();
}) })
}, },
getAuthorsBooks(){ getAuthorsBooks(){
axios.get(this.URL + "author/books") axios.get(this.URL + "author/books", this.getParams)
.then(response => { .then(response => {
console.log(response.data); console.log(response.data);
this.mapAuthorsBooks = response.data; this.mapAuthorsBooks = response.data;

View File

@ -25,11 +25,38 @@ export default{
genreid: 0, genreid: 0,
URL: "http://localhost:8080/", URL: "http://localhost:8080/",
book: new Book(), book: new Book(),
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
} }
}, },
methods:{ methods:{
getBooks(){ getBooks(){
axios.get(this.URL + "book") axios.get(this.URL + "book", this.getParams)
.then(response => { .then(response => {
this.books = response.data; this.books = response.data;
console.log(response.data); console.log(response.data);
@ -41,7 +68,7 @@ export default{
async addBook(){ async addBook(){
await this.toBase64(); await this.toBase64();
console.log(this.book); console.log(this.book);
axios.post(this.URL + "book", this.book) axios.post(this.URL + "book", this.book, this.postParams)
.then((response) => { .then((response) => {
this.getBooks(); this.getBooks();
this.closeModal(); this.closeModal();
@ -53,14 +80,14 @@ export default{
}); });
}, },
deleteBook(id){ deleteBook(id){
axios.delete(this.URL + `book/${id}`) axios.delete(this.URL + `book/${id}`, this.delParams)
.then(() =>{ .then(() =>{
this.getBooks(); this.getBooks();
}) })
}, },
async updateBook(book){ async updateBook(book){
if(book.cover === undefined) await this.toBase64(); if(book.cover === undefined) await this.toBase64();
axios.put(this.URL + `book/${book.id}`, this.book) axios.put(this.URL + `book/${book.id}`, this.book, this.putParams)
.then(() =>{ .then(() =>{
this.getBooks(); this.getBooks();
}) })
@ -98,7 +125,7 @@ export default{
}); });
}, },
getAllGenres(){ getAllGenres(){
axios.get(this.URL + "genre") axios.get(this.URL + "genre", this.getParams)
.then(response => { .then(response => {
this.allGenres = response.data; this.allGenres = response.data;
console.log(response.data); console.log(response.data);
@ -108,7 +135,7 @@ export default{
}); });
}, },
getBookGenres(){ getBookGenres(){
axios.get(this.URL + `book/${this.book.id}/genres`) axios.get(this.URL + `book/${this.book.id}/genres`, this.getParams)
.then(response => { .then(response => {
this.bookGenres = response.data; this.bookGenres = response.data;
console.log(response.data); console.log(response.data);
@ -118,7 +145,7 @@ export default{
}); });
}, },
addGenre(){ addGenre(){
axios.post(this.URL + `book/${this.book.id}/Genre/${this.genreid}`) axios.post(this.URL + `book/${this.book.id}/Genre/${this.genreid}`, null, this.postParams)
.then(() => { .then(() => {
this.getBookGenres(); this.getBookGenres();
}) })
@ -127,7 +154,7 @@ export default{
}); });
}, },
removeGenre(id){ removeGenre(id){
axios.delete(this.URL + `book/${this.book.id}/Genre/${id}`) axios.delete(this.URL + `book/${this.book.id}/Genre/${id}`, this.delParams)
.then(() =>{ .then(() =>{
this.getBookGenres(); this.getBookGenres();
}) })

View File

@ -0,0 +1,9 @@
<template>
<div>
<a>Ошибка доступа</a>
</div>
</template>
<script>
</script>
<style>
</style>

View File

@ -22,11 +22,38 @@ export default{
genres: [], genres: [],
URL: "http://localhost:8080/", URL: "http://localhost:8080/",
genre: new Genre(), genre: new Genre(),
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
} }
}, },
methods:{ methods:{
getGenres(){ getGenres(){
axios.get(this.URL + "genre") axios.get(this.URL + "genre", this.getParams)
.then(response => { .then(response => {
this.genres = response.data; this.genres = response.data;
console.log(response.data); console.log(response.data);
@ -37,7 +64,7 @@ export default{
}, },
addGenre(){ addGenre(){
console.log(this.genre); console.log(this.genre);
axios.post(this.URL + "genre", this.genre) axios.post(this.URL + "genre", this.genre, this.postParams)
.then(() => { .then(() => {
this.getGenres(); this.getGenres();
this.closeModal(); this.closeModal();
@ -47,14 +74,14 @@ export default{
}); });
}, },
deleteGenre(id){ deleteGenre(id){
axios.delete(this.URL + `genre/${id}`) axios.delete(this.URL + `genre/${id}`, this.delParams)
.then(() =>{ .then(() =>{
this.getGenres(); this.getGenres();
}) })
}, },
updateGenre(genre){ updateGenre(genre){
this.genre = genre; this.genre = genre;
axios.put(this.URL + `genre/${genre.id}`, this.genre) axios.put(this.URL + `genre/${genre.id}`, this.genre, this.putParams)
.then(() =>{ .then(() =>{
this.getGenres(); this.getGenres();
}) })

View File

@ -1,41 +0,0 @@
<script>
import Header from '../components/Header.vue'
import Footer from '../components/Footer.vue'
export default{
components:{
Header,
Footer
},
data(){
return {
action: "",
type: "",
str_1: "",
str_2: "",
result: ""
}
},
methods:{
GetRepuest(){
if (this.action.length == 0 || this.str_1.length == 0 || this.str_2.length == 0){
console.warn("Invalid input to fetch!");
}
console.log("http://localhost:8080/" + this.action + "?type=" + this.type + "&arg1=" + this.str_1 + "&arg2=" + this.str_2)
fetch("http://localhost:8080/" + this.action + "?type=" + this.type + "&arg1=" + this.str_1 + "&arg2=" + this.str_2)
.then(res => res.text())
.then(res => {
this.result = res;
})
}
}
}
</script>
<template>
<Header></Header>
<Footer></Footer>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,83 @@
<template>
<div>
<div class="login">
<form @submit.prevent class="login__form" action="/">
<div class="form__login">
<input class="login-input form-control"
id="login" v-model="newUser.login"
validate="false"
placeholder="Логин"
type="text"
name="Логин">
</div>
<div class="form__password">
<input class="password-input form-control"
id="password" v-model="newUser.password"
validate="false"
placeholder="Пароль"
type="password"
name="Пароль">
</div>
<div class="login__buttons mt-5">
<button type="submit" class="login__confirm" id="login__confirm" @click="login">Войти</button>
<a class="login__registration" href="registration">Регистрация</a>
</div>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
mounted(){
},
data(){
return{
newUser: new Object,
token: '',
user: '',
role: '',
}
},
methods: {
async login() {
await this.getRole()
try {
const response = await axios.post(`http://localhost:8080/jwt/login`, this.newUser);
if (response.status === 200) {
localStorage.setItem("token", response.data);
localStorage.setItem("user", this.newUser.login);
this.token = response.data;
this.user = this.newUser.login;
this.$emit('login', {
token: this.token,
user: this.newUser.login,
role: this.role,
});
this.$router.push("/authors")
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
}
} catch (error) {
console.log(error);
}
},
async getRole(){
await axios.get(`http://localhost:8080/who_am_i?userLogin=${this.newUser.login}`)
.then((response) => {
localStorage.setItem("role", response.data)
this.role = response.data
})
.catch(error => {
console.log(error);
})
}
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,46 @@
<template>
<div class="registration">
<form @submit.prevent="registration" class="registration__form" action="#">
<div class="form__login">
<input class="login-input form-control" v-model="login" id="login" required="" validate="false" placeholder="Логин" type="text" name="Логин">
</div>
<div class="form__password">
<input class="password-input form-control" v-model="password" id="password" required="" validate="false" placeholder="Пароль" type="password" name="Пароль">
</div>
<div class="registration__buttons">
<button class="registration__confirm" id="reg_btn" type="submit">Зарегестрироваться</button><a class="registration__login" href="/login">Уже есть аккаунт</a>
</div>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
login: "",
password: "",
}
},
methods:{
registration(){
// Отправляем данные формы на сервер
let user = {
login: this.login,
password: this.password,
passwordConfirm: this.password
}
axios.post(`http://localhost:8080/sign_up`, user)
.then((response) => {
if (response.status === 200) {
alert(response.data);
}
})
.catch(error => {
console.log(error);
});
this.$router.push('/login');
}
}
}
</script>

View File

@ -0,0 +1,52 @@
<template >
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr v-for="(user, index) in users" :key="index">
<td>{{ user.id }}</td>
<td>{{ user.login }}</td>
<td>{{ user.role }}</td>
</tr>
</tbody>
</table>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
users: []
}
},
created(){
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
axios.get(`http://localhost:8080`, requestParams)
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
},
methods:{
}
}
</script>
<style >
</style>

View File

@ -1,14 +1,20 @@
import {createRouter, createWebHistory} from "vue-router" import {createRouter, createWebHistory} from "vue-router"
import Index from '../pages/Index.vue'
import Authors from '../pages/Authors.vue' import Authors from '../pages/Authors.vue'
import Books from '../pages/Books.vue' import Books from '../pages/Books.vue'
import Genres from '../pages/Genres.vue' import Genres from '../pages/Genres.vue'
import users from "../pages/users.vue";
import login from "../pages/login.vue";
import registration from "../pages/registration.vue";
import Error from "../pages/Error.vue";
const routes = [ const routes = [
{path: '/', component: Index}, {path: '/authors', component: Authors, meta: { requiresAuth: true }},
{path: '/authors', component: Authors}, {path: '/books', component: Books, meta: { requiresAuth: true }},
{path: '/books', component: Books}, {path: '/genres', component: Genres, meta: { requiresAuth: true }},
{path: '/genres', component: Genres}, {path: "/users", component: users, meta: { requiresAuth: true, requiresAdmin: true }},
{path: "/login", component: login},
{path: "/registration", component: registration},
{path: "/error", component: Error, meta: { requiresAuth: true }},
] ]
const router = createRouter({ const router = createRouter({
@ -17,4 +23,22 @@ const router = createRouter({
routes routes
}) })
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem("token");
if (to.matched.some((route) => route.meta.requiresAuth)) {
if (!isAuthenticated) {
next("/login");
return;
}
}
const isAdmin = localStorage.getItem("role") === "ADMIN";
if (to.matched.some((route) => route.meta.requiresAdmin)) {
if (!isAdmin) {
next("/error");
return;
}
}
next();
});
export default router; export default router;

View File

@ -1,36 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Автор</th>
<th scope="col">Название книг</th>
</tr>
</thead>
<tbody>
<tr th:each="ab, iterator: ${authorsbooks}">
<td th:text="${ab.key}" style="width: 25%"/>
<td>
<ul>
<li th:each="value : ${ab.value}">
<span th:text="${value}"></span>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<a class="btn btn-secondary" th:href="@{/author}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -1,54 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Дата релиза</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="ab, iterator: ${authorbooks}">
<td th:text="${ab.name}" style="width: 25%"/>
<td th:text="${ab.release}" style="width: 25%"/>
<td><img th:src="${ab.cover}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${ab.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/author/{id}/books/{bookid}(id=${author.id}, bookid=${ab.id})}" method="post">
<button th:id="'remove-' + ${ab.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<form th:action="@{/author/{id}/books(id=${author.id})}" enctype="bookid/form-data" method="post">
<div class="input-group mb-3">
<select class="form-select" th:name="bookid">
<option th:each="book, iterator: ${books}" th:value="${book.id}" th:text="${book.name}"></option>
</select>
<button class="btn btn-outline-secondary" type="submit">Добавить</button>
</div>
</form>
<div>
<a class="btn btn-secondary" th:href="@{/author}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -1,40 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/author/{id}(id=${id})}" th:object="${authorDto}" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="firstname" class="form-label">Имя</label>
<input type="text" class="form-control" id="firstname" th:field="${authorDto.firstname}" required="true">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Фамилия</label>
<input type="text" class="form-control" id="lastname" th:field="${authorDto.lastname}" required="true">
</div>
<div class="mb-3">
<label for="photo" class="form-label">Фото</label>
<input type="file" class="form-control" id="photo" th:name="multipartFile" required="true">
<img th:src="${authorDto.photo}" class="img-thumbnail mw-50 mh-50"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/author}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,61 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/author/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
<a class="btn btn-primary button-fixed"
th:href="@{/author/books}">
<i class="fa-solid fa-plus"></i> Список авторов с книгами
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Имя</th>
<th scope="col">Фамилия</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="author, iterator: ${authors}">
<td th:text="${author.firstname}" style="width: 15%"/>
<td th:text="${author.lastname}" style="width: 15%"/>
<td><img th:src="${author.photo}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/author/update/{id}(id=${author.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${author.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/author/{id}/books(id=${author.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Книга
</a>
</div>
<form th:action="@{/author/delete/{id}(id=${author.id})}" method="post">
<button th:id="'remove-' + ${author.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,50 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="bg, iterator: ${bookgenres}">
<td th:text="${bg.name}" style="width: 25%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${bg.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/book/{id}/genres/{genreid}(id=${book.id}, genreid=${bg.id})}" method="post">
<button th:id="'remove-' + ${bg.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<form th:action="@{/book/{id}/genres(id=${book.id})}" enctype="genreid/form-data" method="post">
<div class="input-group mb-3">
<select class="form-select" th:name="genreid">
<option th:each="genre, iterator: ${genres}" th:value="${genre.id}" th:text="${genre.name}"></option>
</select>
<button class="btn btn-outline-secondary" type="submit">Добавить</button>
</div>
</form>
<div>
<a class="btn btn-secondary" th:href="@{/book}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -1,40 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/book/{id}(id=${id})}" th:object="${bookDto}" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${bookDto.name}" required="true">
</div>
<div class="mb-3">
<label for="release" class="form-label">Дата релиза</label>
<input type="date" class="form-control" id="release" th:field="${bookDto.release}" required="true">
</div>
<div class="mb-3">
<label for="cover" class="form-label">Обложка</label>
<input type="file" class="form-control" id="cover" th:name="multipartFile" required="true">
<img th:src="${bookDto.cover}" class="img-thumbnail mw-50 mh-50"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/book}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,57 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/book/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Дата релиза</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="book, iterator: ${books}">
<td th:text="${book.name}" style="width: 25%"/>
<td th:text="${book.release}" style="width: 25%"/>
<td><img th:src="${book.cover}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/book/update/{id}(id=${book.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${book.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/book/{id}/genres(id=${book.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Жанры
</a>
</div>
<form th:action="@{/book/delete/{id}(id=${book.id})}" method="post">
<button th:id="'remove-' + ${book.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,50 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Онлайн библиотека</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
</head>
<body>
<header class="fixed-top">
<nav class="navbar navbar-expand-lg bg-success" data-bs-theme="dark">
<div class="container">
<a class="navbar-brand" href="#">
<strong class="text-white">{ OBS } Online Book Service</strong>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active text-white" aria-current="page" href="/author" th:classappend="${#strings.equals(activeLink, '/author')} ? 'active' : ''">Authors</a>
<a class="nav-link active text-white" href="/book" th:classappend="${#strings.equals(activeLink, '/book')} ? 'active' : ''">Books</a>
<a class="nav-link active text-white" href="/genre" th:classappend="${#strings.equals(activeLink, '/genre')} ? 'active' : ''">Genres</a>
<a class="nav-link active text-white" href="/users" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Users</a>
<a class="nav-link active text-white" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Logout</a>
</div>
</div>
</div>
</nav>
</header>
<div class="container-fluid" style="margin-top: 50pt;">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
<footer class="container pt-4 my-md-5 pt-md-5 text-center border-top">
<div class="row">
<div class="col-12 col-md">
<h5 class=""><strong>End</strong></h5>
</div>
</div>
</footer>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/author">На главную</a>
</div>
</body>
</html>

View File

@ -1,31 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/genre/{id}(id=${id})}" th:object="${genreDto}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${genreDto.name}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/genre}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,49 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/genre/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="genre, iterator: ${genres}">
<td th:text="${genre.name}" style="width: 60%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/genre/update/{id}(id=${genre.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${genre.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/genre/delete/{id}(id=${genre.id})}" method="post">
<button th:id="'remove-' + ${genre.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,42 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.w3.org/1999/xhtml"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
User not found
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Logout success
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
User '<span th:text="${param.created}"></span>' was successfully created
</div>
<form th:action="@{/login}" method="post">
<div class="mb-3">
<p class="mb-1">Login</p>
<input name="username" id="username" class="form-control"
type="text" required autofocus />
</div>
<div class="mb-3">
<p class="mb-1">Password</p>
<input name="password" id="password" class="form-control"
type="password" required />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">
Sign in
</button>
</div>
<div>
<p>
<span>Not a member yet?</span>
<a href="/signup">Sign Up here</a>
</p>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,29 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container container-padding mt-3" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${UserDTO}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${UserDTO.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mx-4">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active">
</a>
</div>
</div>
</body>
</html>