Lab06 (mvc) готово

This commit is contained in:
Ismailov_Rovshan 2023-05-24 18:35:07 +04:00
parent 0e637791ef
commit 9b3faa72e2
28 changed files with 818 additions and 235 deletions

View File

@ -27,6 +27,9 @@ dependencies {
implementation 'org.hibernate.validator:hibernate-validator' implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5' implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'

Binary file not shown.

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,68 @@
package ru.ulstu.is.sbapp.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import ru.ulstu.is.sbapp.socialNetwork.controller.UserSignupMvcController;
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
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);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/css/**")
.antMatchers("/js/**")
.antMatchers("/templates/**")
.antMatchers("/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;
@ -20,6 +20,7 @@ public class WebConfiguration implements WebMvcConfigurer {
registry.addViewController("users"); registry.addViewController("users");
registry.addViewController("contacts"); registry.addViewController("contacts");
registry.addViewController("catalogs"); registry.addViewController("catalogs");
registry.addViewController("login");
} }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {

View File

@ -1,7 +1,7 @@
package ru.ulstu.is.sbapp.socialNetwork.controller; package ru.ulstu.is.sbapp.socialNetwork.controller;
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.socialNetwork.dto.CommunityDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.CommunityDTO;
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService; import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;

View File

@ -2,11 +2,9 @@ package ru.ulstu.is.sbapp.socialNetwork.controller;
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.socialNetwork.dto.MusicDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.MusicDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService; import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List; import java.util.List;

View File

@ -1,10 +1,10 @@
package ru.ulstu.is.sbapp.socialNetwork.controller; package ru.ulstu.is.sbapp.socialNetwork.controller;
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.socialNetwork.dto.UserDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.MyUserDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService; import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
import javax.validation.Valid; import javax.validation.Valid;
@ -14,55 +14,55 @@ import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/users") @RequestMapping(WebConfiguration.REST_API + "/users")
public class UserController { public class UserController {
private final UserService userService; private final MyUserService userService;
public UserController(UserService userService){ public UserController(MyUserService userService){
this.userService = userService; this.userService = userService;
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) { public MyUserDTO getUser(@PathVariable Long id) {
return new UserDTO(userService.findUser(id)); return new MyUserDTO(userService.findUser(id));
} }
@GetMapping("") @GetMapping("")
public List<UserDTO> getUsers() { public List<MyUserDTO> getUsers() {
return userService.findAllUsers().stream().map(UserDTO::new).toList(); return userService.findAllUsers().stream().map(MyUserDTO::new).toList();
} }
@PostMapping("") @PostMapping("")
public UserDTO createUser(@RequestBody @Valid UserDTO user) { public MyUserDTO createUser(@RequestBody @Valid MyUserDTO user) {
UserModel result = userService.addUser(user.getName(), user.getCity()); UserModel result = userService.addUser(user.getName(), user.getCity());
userService.updateCommunities(result.getId(), user.getCommunity()); userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic())); return new MyUserDTO(userService.updateMusics(result.getId(), user.getMusic()));
} }
@PatchMapping("/{id}") @PatchMapping("/{id}")
public UserDTO updateUser(@PathVariable Long id, public MyUserDTO updateUser(@PathVariable Long id,
@RequestBody @Valid UserDTO user) { @RequestBody @Valid MyUserDTO user) {
UserModel result = userService.updateUser(id, user.getName()); UserModel result = userService.updateUser(id, user.getName());
userService.updateCommunities(result.getId(), user.getCommunity()); userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic())); return new MyUserDTO(userService.updateMusics(result.getId(), user.getMusic()));
} }
@PatchMapping("/add_music/{id}") @PatchMapping("/add_music/{id}")
public UserDTO addMusic(@PathVariable Long id, @RequestParam Long music_id) { public MyUserDTO addMusic(@PathVariable Long id, @RequestParam Long music_id) {
return new UserDTO(userService.addMusic(id, music_id)); return new MyUserDTO(userService.addMusic(id, music_id));
} }
@PatchMapping("/add_community/{id}") @PatchMapping("/add_community/{id}")
public UserDTO addCommunity(@PathVariable Long id, @RequestParam Long community_id) { public MyUserDTO addCommunity(@PathVariable Long id, @RequestParam Long community_id) {
return new UserDTO(userService.addCommunity(id, community_id)); return new MyUserDTO(userService.addCommunity(id, community_id));
} }
@GetMapping("/search") @GetMapping("/search")
public List<UserDTO> searchUsers(@RequestParam("city") String city) { public List<MyUserDTO> searchUsers(@RequestParam("city") String city) {
List<UserModel> users = userService.findUserByCity(city); List<UserModel> users = userService.findUserByCity(city);
return users.stream().map(UserDTO::new).toList(); return users.stream().map(MyUserDTO::new).toList();
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public UserDTO deleteUser(@PathVariable Long id) { public MyUserDTO deleteUser(@PathVariable Long id) {
return new UserDTO(userService.deleteUser(id)); return new MyUserDTO(userService.deleteUser(id));
} }
} }

View File

@ -0,0 +1,42 @@
package ru.ulstu.is.sbapp.socialNetwork.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.ulstu.is.sbapp.socialNetwork.dto.UserDto;
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
import ru.ulstu.is.sbapp.socialNetwork.services.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,51 @@
package ru.ulstu.is.sbapp.socialNetwork.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.ulstu.is.sbapp.socialNetwork.models.User;
import ru.ulstu.is.sbapp.socialNetwork.models.UserSignupDto;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
import javax.validation.Valid;
@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

@ -6,14 +6,14 @@ import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import java.util.List; import java.util.List;
public class UserDTO { public class MyUserDTO {
private Long id; private Long id;
private String name; private String name;
private String city; private String city;
public UserDTO(){} public MyUserDTO(){}
public UserDTO(UserModel user){ public MyUserDTO(UserModel user){
this.id = user.getId(); this.id = user.getId();
this.name = user.getName(); this.name = user.getName();
@ -25,7 +25,7 @@ public class UserDTO {
this.community = user.getGroups().stream().map(Community::getName).toList(); this.community = user.getGroups().stream().map(Community::getName).toList();
} }
} }
public UserDTO(Long id, String name) { public MyUserDTO(Long id, String name) {
this.id = id; this.id = id;
this.name = name; this.name = name;
} }

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.sbapp.socialNetwork.dto;
import ru.ulstu.is.sbapp.socialNetwork.models.User;
import ru.ulstu.is.sbapp.socialNetwork.models.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,73 @@
package ru.ulstu.is.sbapp.socialNetwork.models;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.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);
}
}

View File

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.socialNetwork.models;
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

@ -0,0 +1,40 @@
package ru.ulstu.is.sbapp.socialNetwork.models;
import javax.validation.constraints.NotBlank;
import javax.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,10 @@
package ru.ulstu.is.sbapp.socialNetwork.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import java.util.List;
public interface MyUserRepository extends JpaRepository<UserModel, Long> {
List<UserModel> findByCity(String city);
}

View File

@ -1,10 +1,8 @@
package ru.ulstu.is.sbapp.socialNetwork.repository; package ru.ulstu.is.sbapp.socialNetwork.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.User;
import java.util.List; public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
public interface UserRepository extends JpaRepository<UserModel, Long> {
List<UserModel> findByCity(String city);
} }

View File

@ -0,0 +1,211 @@
package ru.ulstu.is.sbapp.socialNetwork.services;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.repository.MyUserRepository;
import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
@Service
public class MyUserService {
private MyUserRepository repo;
private CommunityService communityService;
private MusicService musicService;
public MyUserService(MyUserRepository repo, MusicService musicService, CommunityService communityService) {
this.repo = repo;
this.musicService = musicService;
this.communityService = communityService;
}
@Transactional
public UserModel addUser(String name, String city) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
UserModel user = new UserModel(name, city);
return repo.save(user);
}
@Transactional
public UserModel addUser(String name, String city, List<String> musics, List<String> communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Name is null or empty");
}
UserModel user = new UserModel(name, city);
UserModel result = repo.save(user);
updateMusics(result.getId(), musics);
return updateCommunities(user.getId(), communities);
}
@Transactional
public UserModel addMusic(Long userId, Long musicId) {
final Optional<UserModel> userOpt= repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("User with id [%s] is not found", musicId));
}
UserModel user = userOpt.get();
final Music music = musicService.findMusic(musicId);
if (music == null) {
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", musicId));
}
user.addMusic(music);
return repo.save(user);
}
@Transactional
public UserModel addCommunity(Long userId, Long communityId) {
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("User with id [%s] is not found", userId));
}
UserModel user = userOpt.get();
final Community community = communityService.findCommunity(communityId);
if (community == null) {
throw new EntityNotFoundException(String.format("Community with id [%s] is not found", communityId));
}
user.addCommunity(community);
return repo.save(user);
}
@Transactional(readOnly = true)
public UserModel findUser(Long id) {
final Optional<UserModel> user = repo.findById(id);
if (user.isEmpty()) {
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", id));
}
return user.get();
}
// @Transactional(readOnly = true)
// public List<UserModel> findUserByCity(String city){
// Query query = repo.createQuery("select u from UserModel u where u.city = :city",
// UserModel.class).setParameter("city", city);
// List<UserModel> result = query.getResultList();
// return result;
// }
@Transactional(readOnly = true)
public List<UserModel> findUserByCity(String city){
List<UserModel> result = repo.findByCity(city);
return result;
}
@Transactional(readOnly = true)
public List<UserModel> findAllUsers() {
return repo.findAll();
}
@Transactional
public UserModel updateUser(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
final Optional<UserModel> currentUserOpt = repo.findById(id);
if(currentUserOpt.isEmpty()) {
return null;
}
final UserModel currentUser = currentUserOpt.get();
currentUser.setName(name);
return repo.save(currentUser);
}
//update community, musics
@Transactional
public UserModel updateUser(Long id, String name,String city, List<String> musics, List<String> Communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
final Optional<UserModel> currentUserOpt = repo.findById(id);
if(currentUserOpt.isEmpty()) {
return null;
}
final UserModel currentUser = currentUserOpt.get();
currentUser.setName(name);
currentUser.setCity(city);
repo.save(currentUser);
updateMusics(id, musics);
return updateCommunities(id, Communities);
}
@Transactional
public UserModel updateCommunities(Long userId , List<String> communities) {
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", userId));
}
UserModel user = userOpt.get();
user.deleteCommunities();
for(String c : communities) {
Community community = communityService.findByName(c);
user.addCommunity(community);
}
return repo.save(user);
}
@Transactional
public UserModel updateMusics(Long userId , List<String> musics) {
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", userId));
}
UserModel user = userOpt.get();
user.deleteMusics();
for(String m : musics) {
Music music = musicService.findByName(m);
user.addMusic(music);
}
return repo.save(user);
}
@Transactional
public UserModel deleteUser(Long id) {
final Optional<UserModel> currentUser = repo.findById(id);
if(currentUser.isEmpty()) {
return null;
}
repo.deleteById(id);
return currentUser.get();
}
@Transactional
public void deleteAllUsers() {
repo.deleteAll();
}
}

View File

@ -1,212 +1,67 @@
package ru.ulstu.is.sbapp.socialNetwork.services; package ru.ulstu.is.sbapp.socialNetwork.services;
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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import ru.ulstu.is.sbapp.socialNetwork.models.User;
import org.springframework.util.StringUtils; import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.repository.UserRepository; import ru.ulstu.is.sbapp.socialNetwork.repository.UserRepository;
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidatorUtil;
import javax.persistence.EntityNotFoundException; import java.util.Collections;
import javax.persistence.Query; import java.util.Objects;
import java.util.List;
import java.util.Optional;
@Service @Service
public class UserService { public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private UserRepository repo; public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
private CommunityService communityService; ValidatorUtil validatorUtil) {
private MusicService musicService; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
public UserService(UserRepository repo, MusicService musicService, CommunityService communityService) { this.validatorUtil = validatorUtil;
this.repo = repo;
this.musicService = musicService;
this.communityService = communityService;
} }
@Transactional public Page<User> findAllPages(int page, int size) {
public UserModel addUser(String name, String city) { return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
UserModel user = new UserModel(name, city);
return repo.save(user);
}
@Transactional
public UserModel addUser(String name, String city, List<String> musics, List<String> communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Name is null or empty");
} }
UserModel user = new UserModel(name, city); public User findByLogin(String login) {
UserModel result = repo.save(user); return userRepository.findOneByLoginIgnoreCase(login);
updateMusics(result.getId(), musics);
return updateCommunities(user.getId(), communities);
} }
@Transactional public User createUser(String login, String password, String passwordConfirm) {
public UserModel addMusic(Long userId, Long musicId) { return createUser(login, password, passwordConfirm, UserRole.USER);
final Optional<UserModel> userOpt= repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("User with id [%s] is not found", musicId));
} }
UserModel user = userOpt.get(); public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
final Music music = musicService.findMusic(musicId); throw new ValidationException(String.format("User '%s' already exists", login));
if (music == null) { }
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", musicId)); final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
} }
user.addMusic(music); @Override
return repo.save(user); public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
} }
@Transactional return new org.springframework.security.core.userdetails.User(
public UserModel addCommunity(Long userId, Long communityId) { userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("User with id [%s] is not found", userId));
} }
UserModel user = userOpt.get();
final Community community = communityService.findCommunity(communityId);
if (community == null) {
throw new EntityNotFoundException(String.format("Community with id [%s] is not found", communityId));
}
user.addCommunity(community);
return repo.save(user);
}
@Transactional(readOnly = true)
public UserModel findUser(Long id) {
final Optional<UserModel> user = repo.findById(id);
if (user.isEmpty()) {
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", id));
}
return user.get();
}
// @Transactional(readOnly = true)
// public List<UserModel> findUserByCity(String city){
// Query query = repo.createQuery("select u from UserModel u where u.city = :city",
// UserModel.class).setParameter("city", city);
// List<UserModel> result = query.getResultList();
// return result;
// }
@Transactional(readOnly = true)
public List<UserModel> findUserByCity(String city){
List<UserModel> result = repo.findByCity(city);
return result;
}
@Transactional(readOnly = true)
public List<UserModel> findAllUsers() {
return repo.findAll();
}
@Transactional
public UserModel updateUser(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
final Optional<UserModel> currentUserOpt = repo.findById(id);
if(currentUserOpt.isEmpty()) {
return null;
}
final UserModel currentUser = currentUserOpt.get();
currentUser.setName(name);
return repo.save(currentUser);
}
//update community, musics
@Transactional
public UserModel updateUser(Long id, String name,String city, List<String> musics, List<String> Communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
final Optional<UserModel> currentUserOpt = repo.findById(id);
if(currentUserOpt.isEmpty()) {
return null;
}
final UserModel currentUser = currentUserOpt.get();
currentUser.setName(name);
currentUser.setCity(city);
repo.save(currentUser);
updateMusics(id, musics);
return updateCommunities(id, Communities);
}
@Transactional
public UserModel updateCommunities(Long userId , List<String> communities) {
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", userId));
}
UserModel user = userOpt.get();
user.deleteCommunities();
for(String c : communities) {
Community community = communityService.findByName(c);
user.addCommunity(community);
}
return repo.save(user);
}
@Transactional
public UserModel updateMusics(Long userId , List<String> musics) {
final Optional<UserModel> userOpt = repo.findById(userId);
if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", userId));
}
UserModel user = userOpt.get();
user.deleteMusics();
for(String m : musics) {
Music music = musicService.findByName(m);
user.addMusic(music);
}
return repo.save(user);
}
@Transactional
public UserModel deleteUser(Long id) {
final Optional<UserModel> currentUser = repo.findById(id);
if(currentUser.isEmpty()) {
return null;
}
repo.deleteById(id);
return currentUser.get();
}
@Transactional
public void deleteAllUsers() {
repo.deleteAll();
}
} }

View File

@ -0,0 +1,37 @@
package ru.ulstu.is.sbapp.socialNetwork.util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
public class AdviceController {
@ExceptionHandler({
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.sbapp.socialNetwork.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
public <T> ValidationException(String error) {
super(error);
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.sbapp.socialNetwork.util.validation;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
this.validator = Validation.buildDefaultValidatorFactory().getValidator();
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -0,0 +1,30 @@
<!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 class="container" layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
Пользователь не найден или пароль указан не верно
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Выход успешно произведен
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
Пользователь '<span th:text="${param.created}"></span>' успешно создан
</div>
<form th:action="@{/login}" method="post" class="container-padding">
<div class="mb-3">
<input type="text" name="username" id="username" class="form-control"
placeholder="Логин" required="true" autofocus="true"/>
</div>
<div class="mb-3">
<input type="password" name="password" id="password" class="form-control"
placeholder="Пароль" required="true"/>
</div>
<button type="submit" class="btn btn-success button-fixed">Войти</button>
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container container-padding" 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="mb-3">
<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

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

View File

@ -7,10 +7,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.socialNetwork.models.Community; import ru.ulstu.is.sbapp.socialNetwork.models.Community;
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService; import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService; import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import java.util.List; import java.util.List;
@ -19,7 +18,7 @@ import java.util.List;
public class JpaCommunityTest { public class JpaCommunityTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class); private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired @Autowired
UserService userService; MyUserService userService;
@Autowired @Autowired
CommunityService communityService; CommunityService communityService;

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.socialNetwork.models.Music; import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService; import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService; import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import java.util.List; import java.util.List;
@ -17,7 +17,7 @@ import java.util.List;
public class JpaMusicTest { public class JpaMusicTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class); private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired @Autowired
UserService userService; MyUserService userService;
@Autowired @Autowired
MusicService musicService; MusicService musicService;

View File

@ -11,7 +11,7 @@ import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService; import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService; import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService; import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import java.util.List; import java.util.List;
@ -20,7 +20,7 @@ import java.util.List;
public class JpaUserTest { public class JpaUserTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class); private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired @Autowired
UserService userService; MyUserService userService;
@Autowired @Autowired
MusicService musicService; MusicService musicService;