This commit is contained in:
Татьяна Артамонова 2023-06-12 19:03:11 +04:00
parent d12e8a5f61
commit cdbbe467d0
39 changed files with 812 additions and 56 deletions

View File

@ -30,6 +30,11 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.hibernate.validator:hibernate-validator' implementation 'org.hibernate.validator:hibernate-validator'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
} }
tasks.named('test') { tasks.named('test') {

View File

@ -12,4 +12,7 @@ public interface IAlbumRepository extends JpaRepository<Album, Long> {
"join a.songs s " + "join a.songs s " +
"group by a.id, a.albumName, s.songName") "group by a.id, a.albumName, s.songName")
List<Object[]> getAll(); List<Object[]> getAll();
@Query("SELECT a FROM Album a WHERE a.albumName = :name")
List<Album> getAlbumsByName(String name);
} }

View File

@ -11,4 +11,7 @@ import java.util.List;
public interface IArtistRepository extends JpaRepository<Artist, Long> { public interface IArtistRepository extends JpaRepository<Artist, Long> {
@Query(value = "SELECT * FROM artist_album", nativeQuery = true) @Query(value = "SELECT * FROM artist_album", nativeQuery = true)
List<Object[]> getAllArtistAlbum(); List<Object[]> getAllArtistAlbum();
@Query("SELECT a FROM Artist a WHERE a.artistName = :name")
List<Artist> getArtistsByName(String name);
} }

View File

@ -10,4 +10,7 @@ import java.util.List;
public interface ISongRepository extends JpaRepository<Song, Long> { public interface ISongRepository extends JpaRepository<Song, Long> {
@Query("SELECT a.songs FROM Album a WHERE :song MEMBER OF a.songs") @Query("SELECT a.songs FROM Album a WHERE :song MEMBER OF a.songs")
List<Song> findSongsInAlbum(@Param("song") Song song); List<Song> findSongsInAlbum(@Param("song") Song song);
@Query("SELECT s FROM Song s WHERE s.songName = :name")
List<Song> getSongsByName(String name);
} }

View File

@ -0,0 +1,8 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.database.model.User;
public interface IUserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.sbapp.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,67 @@
package ru.ulstu.is.sbapp.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import ru.ulstu.is.sbapp.controllers.UserSignUpMvcController;
import ru.ulstu.is.sbapp.database.model.UserRole;
import ru.ulstu.is.sbapp.database.service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.defaultSuccessUrl("/artist", true)
.and()
.logout().permitAll();
return http.userDetailsService(userService).build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**");
}
}

View File

@ -1,4 +1,4 @@
package ru.ulstu.is.sbapp; package ru.ulstu.is.sbapp.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;
@ -15,6 +15,6 @@ public class WebConfiguration implements WebMvcConfigurer {
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry); WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("artist"); registry.addViewController("login");
} }
} }

View File

@ -3,7 +3,7 @@ package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration; import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.database.model.Artist; import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song; import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.service.AlbumService; import ru.ulstu.is.sbapp.database.service.AlbumService;

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -27,19 +28,25 @@ public class AlbumMvcController {
} }
@GetMapping @GetMapping
public String getAlbums(Model model) { public String getAlbums(Model model, Authentication authentication) {
model.addAttribute("albums", model.addAttribute("albums",
albumService.findAllAlbums().stream() albumService.findAllAlbums().stream()
.map(AlbumDTO::new) .map(AlbumDTO::new)
.toList()); .toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "album"; return "album";
} }
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
public String editAlbum(@PathVariable(required = false) Long id, public String editAlbum(@PathVariable(required = false) Long id,
Model model) { Model model, Authentication authentication) {
if (id == null || id <= 0) { if (id == null || id <= 0) {
model.addAttribute("albumDTO", new AlbumDTO()); model.addAttribute("albumDTO", new AlbumDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else { } else {
model.addAttribute("albumId", id); model.addAttribute("albumId", id);
model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id))); model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id)));
@ -136,19 +143,4 @@ public class AlbumMvcController {
Map<String, List<String>> report = albumService.getAll(); Map<String, List<String>> report = albumService.getAll();
return "report"; return "report";
} }
// @GetMapping("/addArtistToAlbum/{id}")
// public String addArtistToAlbumForm(@PathVariable Long id, Model model) {
// model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id)));
// model.addAttribute("albumId", id);
// model.addAttribute("artists", artistService.findAllArtists());
// return "add-artist-to-album";
// }
//
// @PostMapping("/addArtistToAlbum/{id}")
// public String addArtistToAlbum(@PathVariable Long id,
// @RequestParam("artistId") List<Long> artistIds) {
// albumService.addArtistToAlbum(id, artistIds);
// return "redirect:/album";
// }
} }

View File

@ -2,7 +2,7 @@ package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration; import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.ArtistService; import ru.ulstu.is.sbapp.database.service.ArtistService;
import java.util.List; import java.util.List;
@ -49,7 +49,7 @@ public class ArtistController {
} }
@PostMapping("/{id}/addArtistToAlbum") @PostMapping("/{id}/addArtistToAlbum")
public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> groupsIds){ public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> albumsIds){
artistService.addArtistToAlbum(id, groupsIds); artistService.addArtistToAlbum(id, albumsIds);
} }
} }

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -24,19 +25,25 @@ public class ArtistMvcController {
} }
@GetMapping @GetMapping
public String getArtists(Model model) { public String getArtists(Model model, Authentication authentication) {
model.addAttribute("artists", model.addAttribute("artists",
artistService.findAllArtists().stream() artistService.findAllArtists().stream()
.map(ArtistDTO::new) .map(ArtistDTO::new)
.toList()); .toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "artist"; return "artist";
} }
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
public String editArtist(@PathVariable(required = false) Long id, public String editArtist(@PathVariable(required = false) Long id,
Model model) { Model model, Authentication authentication) {
if (id == null || id <= 0) { if (id == null || id <= 0) {
model.addAttribute("artistDTO", new ArtistDTO()); model.addAttribute("artistDTO", new ArtistDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else { } else {
model.addAttribute("artistId", id); model.addAttribute("artistId", id);
model.addAttribute("artistDTO", new ArtistDTO(artistService.findArtist(id))); model.addAttribute("artistDTO", new ArtistDTO(artistService.findArtist(id)));

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.FindByNameService;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/find")
public class FindController {
private final FindByNameService findService;
public FindController(FindByNameService findService) {
this.findService = findService;
}
@GetMapping("/get/{name}")
public Map<String, List<Object>> getByName(@PathVariable(required = false) String name){
return findService.GetByName(name);
}
}

View File

@ -0,0 +1,42 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.is.sbapp.database.service.FindByNameService;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/find")
public class FindMvcController {
private final FindByNameService findService;
public FindMvcController(FindByNameService findService) {
this.findService = findService;
}
@GetMapping("/get/{name}")
public String getByName(@PathVariable(required = false) String name, Model model) {
Map<String, List<Object>> searchResult = findService.GetByName(name);
//model.addAttribute("name", name);
model.addAttribute("searchResult", searchResult != null);
model.addAttribute("name", name);
if (searchResult != null) {
model.addAttribute("songs", searchResult.get("songs"));
model.addAttribute("albums", searchResult.get("albums"));
model.addAttribute("artists", searchResult.get("artists"));
}
return "find";
}
@GetMapping("/get/")
public String getFind() {
return "find";
}
}

View File

@ -2,7 +2,7 @@ package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration; import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.AlbumService; import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.SongService; import ru.ulstu.is.sbapp.database.service.SongService;

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -21,20 +22,26 @@ public class SongMvcController {
} }
@GetMapping @GetMapping
public String getSongs(Model model) { public String getSongs(Model model, Authentication authentication) {
model.addAttribute("songs", model.addAttribute("songs",
songService.findAllSongs().stream() songService.findAllSongs().stream()
.map(SongDTO::new) .map(SongDTO::new)
.toList()); .toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "song"; return "song";
} }
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
public String editSong(@PathVariable(required = false) Long id, public String editSong(@PathVariable(required = false) Long id,
Model model) { Model model, Authentication authentication) {
model.addAttribute("Albums", albumService.findAllAlbums()); model.addAttribute("Albums", albumService.findAllAlbums());
if (id == null || id <= 0) { if (id == null || id <= 0) {
model.addAttribute("songDTO", new SongDTO()); model.addAttribute("songDTO", new SongDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else { } else {
model.addAttribute("songId", id); model.addAttribute("songId", id);
model.addAttribute("songDTO", new SongDTO(songService.findSong(id))); model.addAttribute("songDTO", new SongDTO(songService.findSong(id)));

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.User;
import ru.ulstu.is.sbapp.database.model.UserRole;
public class UserDTO {
private final long id;
private final String login;
private final UserRole role;
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
}

View File

@ -0,0 +1,41 @@
package ru.ulstu.is.sbapp.controllers;
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.ulstu.is.sbapp.database.model.UserRole;
import ru.ulstu.is.sbapp.database.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

@ -0,0 +1,40 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignUpDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,47 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
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.ulstu.is.sbapp.database.model.User;
import ru.ulstu.is.sbapp.database.service.UserService;
import ru.ulstu.is.sbapp.database.util.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

@ -26,6 +26,9 @@ public class Album {
inverseJoinColumns = {@JoinColumn(name = "artist_id")}) inverseJoinColumns = {@JoinColumn(name = "artist_id")})
private List<Artist> artists; private List<Artist> artists;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Album() { public Album() {
this.songs = new ArrayList<>(); this.songs = new ArrayList<>();
} }
@ -39,6 +42,12 @@ public class Album {
public String getAlbumName() { return albumName; } public String getAlbumName() { return albumName; }
public void setAlbumName(String name) { this.albumName = name; } public void setAlbumName(String name) { this.albumName = name; }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View File

@ -23,6 +23,10 @@ public class Artist {
inverseJoinColumns = {@JoinColumn(name = "album_id")}) inverseJoinColumns = {@JoinColumn(name = "album_id")})
private List<Album> albums = new ArrayList<>(); private List<Album> albums = new ArrayList<>();
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Artist() { public Artist() {
} }
@ -37,6 +41,13 @@ public class Artist {
public String getGenre() { return genre; } public String getGenre() { return genre; }
public void setGenre(String genre) { this.genre = genre; } public void setGenre(String genre) { this.genre = genre; }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View File

@ -21,6 +21,10 @@ public class Song {
@JoinColumn(name = "album_id", nullable = true) @JoinColumn(name = "album_id", nullable = true)
private Album album; private Album album;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Song() { public Song() {
} }
@ -35,6 +39,13 @@ public class Song {
public Double getDuration() { return duration;} public Double getDuration() { return duration;}
public void setDuration(Double duration) { this.duration = duration; } public void setDuration(Double duration) { this.duration = duration; }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View File

@ -0,0 +1,83 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
}
}

View File

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.database.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -1,13 +1,13 @@
package ru.ulstu.is.sbapp.database.service; package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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 org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IAlbumRepository; import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.database.model.Album; import ru.ulstu.is.sbapp.database.model.*;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -21,11 +21,13 @@ public class AlbumService {
private final SongService songService; private final SongService songService;
private final ArtistService artistService; private final ArtistService artistService;
private final UserService userService;
public AlbumService(IAlbumRepository albumRepository, SongService songService, @Lazy ArtistService artistService) { public AlbumService(IAlbumRepository albumRepository, SongService songService, @Lazy ArtistService artistService, UserService userService) {
this.albumRepository = albumRepository; this.albumRepository = albumRepository;
this.songService = songService; this.songService = songService;
this.artistService = artistService; this.artistService = artistService;
this.userService = userService;
} }
@Transactional @Transactional
@ -34,6 +36,14 @@ public class AlbumService {
throw new IllegalArgumentException("Album name is null or empty"); throw new IllegalArgumentException("Album name is null or empty");
} }
final Album album = new Album(name); final Album album = new Album(name);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
album.setUser(user);
}
}
return albumRepository.save(album); return albumRepository.save(album);
} }

View File

@ -1,10 +1,12 @@
package ru.ulstu.is.sbapp.database.service; package ru.ulstu.is.sbapp.database.service;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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 org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IArtistRepository; import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.database.model.Artist; import ru.ulstu.is.sbapp.database.model.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -14,10 +16,12 @@ import java.util.Optional;
public class ArtistService { public class ArtistService {
private final IArtistRepository artistRepository; private final IArtistRepository artistRepository;
private final AlbumService albumService; private final AlbumService albumService;
private final UserService userService;
public ArtistService(IArtistRepository artistRepository, AlbumService albumService) { public ArtistService(IArtistRepository artistRepository, AlbumService albumService, UserService userService) {
this.artistRepository = artistRepository; this.artistRepository = artistRepository;
this.albumService = albumService; this.albumService = albumService;
this.userService = userService;
} }
@Transactional @Transactional
@ -26,6 +30,14 @@ public class ArtistService {
throw new IllegalArgumentException("Artist name or genre is null or empty"); throw new IllegalArgumentException("Artist name or genre is null or empty");
} }
final Artist artist = new Artist(artistName, genre); final Artist artist = new Artist(artistName, genre);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
artist.setUser(user);
}
}
return artistRepository.save(artist); return artistRepository.save(artist);
} }

View File

@ -0,0 +1,49 @@
package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class FindByNameService {
private final IAlbumRepository albumRepository;
private final ISongRepository songRepository;
private final IArtistRepository artistRepository;
public FindByNameService(@Lazy IAlbumRepository albumRepository, @Lazy ISongRepository songRepository, @Lazy IArtistRepository artistRepository) {
this.albumRepository = albumRepository;
this.songRepository = songRepository;
this.artistRepository = artistRepository;
}
@Transactional
public Map<String, List<Object>> GetByName(String name) {
Map<String, List<Object>> resultMap = new HashMap<>();
List<Song> songs = songRepository.getSongsByName(name).stream().toList();
List<Object> songsResult = new ArrayList<>(songs);
resultMap.put("songs", songsResult);
List<Album> albums = albumRepository.getAlbumsByName(name).stream().toList();
List<Object> albumsResult = new ArrayList<>(albums);
resultMap.put("albums", albumsResult);
List<Artist> artists = artistRepository.getArtistsByName(name).stream().toList();
List<Object> artistsResult = new ArrayList<>(artists);
resultMap.put("artists", artistsResult);
return resultMap;
}
}

View File

@ -1,11 +1,13 @@
package ru.ulstu.is.sbapp.database.service; package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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 org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.ISongRepository; import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.database.model.Song; import ru.ulstu.is.sbapp.database.model.*;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -15,10 +17,12 @@ public class SongService {
private final ISongRepository songRepository; private final ISongRepository songRepository;
private final AlbumService albumService; private final AlbumService albumService;
private final UserService userService;
public SongService(ISongRepository songRepository, @Lazy AlbumService albumService) { public SongService(ISongRepository songRepository, @Lazy AlbumService albumService, UserService userService) {
this.songRepository = songRepository; this.songRepository = songRepository;
this.albumService = albumService; this.albumService = albumService;
this.userService = userService;
} }
@Transactional @Transactional
@ -27,6 +31,14 @@ public class SongService {
throw new IllegalArgumentException("Song name or duration is null or empty"); throw new IllegalArgumentException("Song name or duration is null or empty");
} }
final Song song = new Song(songName, duration); final Song song = new Song(songName, duration);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
song.setUser(user);
}
}
return songRepository.save(song); return songRepository.save(song);
} }

View File

@ -0,0 +1,59 @@
package ru.ulstu.is.sbapp.database.service;
import jakarta.validation.ValidationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.Repository.IUserRepository;
import ru.ulstu.is.sbapp.database.model.User;
import ru.ulstu.is.sbapp.database.model.UserRole;
import java.util.Collections;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final IUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(IUserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
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) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
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)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -7,7 +7,7 @@
<h1 class="text-center mb-4">Альбомы</h1> <h1 class="text-center mb-4">Альбомы</h1>
<div> <div>
<a class="btn btn-success button-fixed" <a class="btn btn-success button-fixed"
th:href="@{/album/edit}"> th:href="@{/album/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить <i class="fa-solid fa-plus"></i> Добавить
</a> </a>
</div> </div>
@ -23,13 +23,13 @@
<tr th:each="album, iterator: ${albums}"> <tr th:each="album, iterator: ${albums}">
<td th:text="${album.albumName}"></td> <td th:text="${album.albumName}"></td>
<td> <td>
<div class="btn-album" role="group" aria-label="Basic example"> <div class="btn-album" role="album" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm" <a class="btn btn-warning button-fixed button-sm"
th:href="@{/album/edit/{id}(id=${album.id})}"> th:href="@{/album/edit/{id}(id=${album.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить <i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a> </a>
<button type="button" class="btn btn-danger button-fixed button-sm" <button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${album.id}').click()|"> th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${album.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить <i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button> </button>
<a class="btn btn-primary button-fixed button-sm" <a class="btn btn-primary button-fixed button-sm"
@ -41,7 +41,7 @@
<a class="btn btn-primary button-fixed button-sm" <a class="btn btn-primary button-fixed button-sm"
th:href="@{/album/artists/{id}(id=${album.id})}">Посмотреть исполнителей</a> th:href="@{/album/artists/{id}(id=${album.id})}">Посмотреть исполнителей</a>
</div> </div>
<form th:action="@{/album/delete/{id}(id=${album.id})}" method="post"> <form th:action="@{/album/delete/{id}(id=${album.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${album.id}" type="submit" style="display: none"> <button th:id="'remove-' + ${album.id}" type="submit" style="display: none">
Удалить Удалить
</button> </button>

View File

@ -7,7 +7,7 @@
<h1 class="text-center mb-4">Исполнители</h1> <h1 class="text-center mb-4">Исполнители</h1>
<div> <div>
<a class="btn btn-success button-fixed" <a class="btn btn-success button-fixed"
th:href="@{/artist/edit}"> th:href="@{/artist/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить <i class="fa-solid fa-plus"></i> Добавить
</a> </a>
</div> </div>
@ -27,15 +27,15 @@
<td> <td>
<div class="btn-album" role="group" aria-label="Basic example"> <div class="btn-album" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm" <a class="btn btn-warning button-fixed button-sm"
th:href="@{/artist/edit/{id}(id=${artist.id})}"> th:href="@{/artist/edit/{id}(id=${artist.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить <i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a> </a>
<button type="button" class="btn btn-danger button-fixed button-sm" <button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${artist.id}').click()|"> th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${artist.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить <i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button> </button>
</div> </div>
<form th:action="@{/artist/delete/{id}(id=${artist.id})}" method="post"> <form th:action="@{/artist/delete/{id}(id=${artist.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${artist.id}" type="submit" style="display: none"> <button th:id="'remove-' + ${artist.id}" type="submit" style="display: none">
Удалить Удалить
</button> </button>

View File

@ -10,7 +10,6 @@
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> <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/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/> <link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
</head> </head>
<body> <body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
@ -22,10 +21,13 @@
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav"> <ul class="navbar-nav">
<a class="nav-link">Стриминговый сервис</a> <a class="nav-link" href="/">Стриминговый сервис</a>
<a class="nav-link" href="/song" th:classappend="${#strings.equals(activeLink, '/song')} ? 'active' : ''">Песни</a> <a class="nav-link" href="/song" th:classappend="${#strings.equals(activeLink, '/song')} ? 'active' : ''">Песни</a>
<a class="nav-link" href="/album" th:classappend="${#strings.equals(activeLink, '/album')} ? 'active' : ''">Альбомы</a> <a class="nav-link" href="/album" th:classappend="${#strings.equals(activeLink, '/album')} ? 'active' : ''">Альбомы</a>
<a class="nav-link" href="/artist" th:classappend="${#strings.equals(activeLink, '/artist')} ? 'active' : ''">Исполнители</a> <a class="nav-link" href="/artist" th:classappend="${#strings.equals(activeLink, '/artist')} ? 'active' : ''">Исполнители</a>
<a class="nav-link" href="/find/get/" th:classappend="${#strings.equals(activeLink, '/find/get/')} ? 'active' : ''">Поиск</a>
<a class="nav-link" href="/users" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Выход</a>
</ul> </ul>
</div> </div>
</div> </div>

View File

@ -2,12 +2,12 @@
<html lang="en" <html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml"> layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body> <body>
<div layout:fragment="content"> <div class="container" layout:fragment="content">
<div><span th:text="${error}"></span></div> <div class="alert alert-danger">
<a href="/">На главную</a> <span th:text="${error}"></span>
</div>
<a href="/student">На главную</a>
</div> </div>
</body> </body>
</html> </html>

View File

@ -0,0 +1,39 @@
<!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">
<body>
<div layout:fragment="content">
<h1 class="mb-4">Поиск</h1>
<form th:action="@{/find/get/{name}(name=${name})}" method="get">
<input type="text" class="form-control" name="name" id="name" th:field="${name}" required>
<br>
<a class="btn btn-success button-fixed" type="submit" th:href="@{/find/get/{name}(name=${name})}" method="get">Поиск</a>
</form>
<br>
<div>
<h2>Результаты поиска <span th:text="${name}" th:block></span></h2>
<div th:if="searchResult">
<h3>Песни</h3>
<ul>
<li th:each="song : ${songs}">
<span th:text="${song.songName}" th:block></span>
</li>
</ul>
<h3>Альбомы</h3>
<ul>
<li th:each="album : ${albums}">
<span th:text="${album.albumName}" th:block></span>
</li>
</ul>
<h3>Исполнители</h3>
<ul>
<li th:each="artist : ${artists}">
<span th:text="${artist.artistName}" th:block></span>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,42 @@
<!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

@ -0,0 +1,29 @@
<!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

@ -9,7 +9,7 @@
<h1 class="text-center mb-4">Песни</h1> <h1 class="text-center mb-4">Песни</h1>
<div> <div>
<a class="btn btn-success button-fixed" <a class="btn btn-success button-fixed"
th:href="@{/song/edit}"> th:href="@{/song/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить <i class="fa-solid fa-plus"></i> Добавить
</a> </a>
</div> </div>
@ -31,15 +31,15 @@
<td> <td>
<div class="btn-album" role="group" aria-label="Basic example"> <div class="btn-album" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm" <a class="btn btn-warning button-fixed button-sm"
th:href="@{/song/edit/{id}(id=${song.id})}"> th:href="@{/song/edit/{id}(id=${song.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить <i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a> </a>
<button type="button" class="btn btn-danger button-fixed button-sm" <button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${song.id}').click()|"> th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${song.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить <i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button> </button>
</div> </div>
<form th:action="@{/song/delete/{id}(id=${song.id})}" method="post"> <form th:action="@{/song/delete/{id}(id=${song.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${song.id}" type="submit" style="display: none"> <button th:id="'remove-' + ${song.id}" type="submit" style="display: none">
Удалить Удалить
</button> </button>

View File

@ -0,0 +1,38 @@
<!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>