Работает админка длч пользователей
This commit is contained in:
parent
d0b555880b
commit
e88f712c8c
@ -6,8 +6,8 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
// import com.example.nekontakte.users.model.UserEntity;
|
||||
// import com.example.nekontakte.users.model.UserRole;
|
||||
import com.example.nekontakte.users.model.UserEntity;
|
||||
import com.example.nekontakte.users.model.UserRole;
|
||||
import com.example.nekontakte.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
@ -27,11 +27,8 @@ public class NekontakteApplication implements CommandLineRunner {
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
// _logger.info("Create default user values");
|
||||
// final var admin = new UserEntity(
|
||||
// "admin",
|
||||
// "admin",
|
||||
// UserRole.ADMIN);
|
||||
_logger.info("Create default user values");
|
||||
// UserEntity admin = new UserEntity("admin", "admin", UserRole.ADMIN);
|
||||
// userService.create(admin);
|
||||
_logger.info(String.format("users count: %s", userService.getAll().size()));
|
||||
}
|
||||
|
@ -20,10 +20,11 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserController.URL)
|
||||
public class UserController {
|
||||
@RequestMapping(AdminUserController.URL)
|
||||
public class AdminUserController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/user";
|
||||
private static final String USER_VIEW = "user";
|
||||
private static final String USER_EDIT_VIEW = "user-edit";
|
||||
@ -33,7 +34,7 @@ public class UserController {
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
public AdminUserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.userService = userService;
|
||||
}
|
||||
@ -55,49 +56,36 @@ public class UserController {
|
||||
return USER_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserDTO());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
@GetMapping("/create")
|
||||
public String getCreateView(Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserEditDTO());
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDTO user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
public String getEditView(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(USER_ATTRIBUTE, toDTO(userService.get(id)));
|
||||
|
||||
UserEntity userEntity = userService.get(id);
|
||||
UserEditDTO userEditDTO = new UserEditDTO();
|
||||
userEditDTO.setId(userEntity.getId());
|
||||
userEditDTO.setUsername(userEntity.getUsername());
|
||||
userEditDTO.setRole(userEntity.getRole());
|
||||
|
||||
model.addAttribute(USER_ATTRIBUTE, userEditDTO);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@PostMapping("/edit")
|
||||
public String postEditView(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDTO user,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserEditDTO userEditDTO,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
@ -105,11 +93,59 @@ public class UserController {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
if (userEditDTO.getId() == null && (userEditDTO.getPassword() == null || userEditDTO.getPassword() == "")) {
|
||||
bindingResult.rejectValue("password", "userEdit:passwords", "Укажите пароль");
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userEditDTO.setPasswordConfirm(null);
|
||||
model.addAttribute(USER_ATTRIBUTE, userEditDTO);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
if (!Objects.equals(userEditDTO.getPassword(), userEditDTO.getPasswordConfirm())) {
|
||||
bindingResult.rejectValue("password", "userEdit:passwords", "Пароли не совпадают");
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userEditDTO.setPasswordConfirm(null);
|
||||
model.addAttribute(USER_ATTRIBUTE, userEditDTO);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
UserEntity userEntity;
|
||||
|
||||
if (userEditDTO.getId() == null) {
|
||||
userEntity = new UserEntity();
|
||||
} else {
|
||||
userEntity = userService.get(userEditDTO.getId());
|
||||
}
|
||||
|
||||
userEntity.setUsername(userEditDTO.getUsername());
|
||||
userEntity.setRole(userEditDTO.getRole());
|
||||
|
||||
if (userEditDTO.getPassword() != null && userEditDTO.getPassword() != "") {
|
||||
userEntity.setPassword(userEditDTO.getPassword());
|
||||
}
|
||||
|
||||
if (userEditDTO.getId() == null) {
|
||||
userService.create(userEntity);
|
||||
} else {
|
||||
userService.update(userEntity);
|
||||
}
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String postDeleteView(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
userService.delete(id);
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.update(id, toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -36,6 +36,7 @@ public class UserDTO {
|
||||
|
||||
private String status;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
@ -0,0 +1,59 @@
|
||||
package com.example.nekontakte.users.api;
|
||||
|
||||
import com.example.nekontakte.users.model.UserRole;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserEditDTO {
|
||||
private Integer id;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
private String passwordConfirm;
|
||||
|
||||
private UserRole role;
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(UserRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
@ -36,7 +36,10 @@ public class UserSignupController {
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserSignupDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
UserEntity userEntity = new UserEntity();
|
||||
userEntity.setUsername(dto.getUsername());
|
||||
userEntity.setPassword(dto.getPassword());
|
||||
return userEntity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@ -61,5 +64,4 @@ public class UserSignupController {
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup";
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -5,6 +5,9 @@ import java.util.Objects;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import com.example.nekontakte.core.model.BaseEntity;
|
||||
import com.example.nekontakte.posts.model.PostEntity;
|
||||
|
||||
@ -140,7 +143,15 @@ public class UserEntity extends BaseEntity {
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
setPassword(password, true);
|
||||
}
|
||||
|
||||
public void setPassword(String password, boolean encode) {
|
||||
if (encode) {
|
||||
this.password = new BCryptPasswordEncoder().encode(password);
|
||||
} else {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -3,10 +3,19 @@ package com.example.nekontakte.users.model;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
ADMIN("Администратор"),
|
||||
USER("Пользователь");
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
private final String displayName;
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
private UserRole(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
|
@ -5,7 +5,6 @@ import org.springframework.data.domain.PageRequest;
|
||||
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 com.example.nekontakte.core.errors.NotFoundException;
|
||||
@ -21,15 +20,18 @@ import java.util.stream.StreamSupport;
|
||||
@Service
|
||||
public class UserService implements UserDetailsService {
|
||||
private final UserRepository repository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private boolean checkUsernameIsExist(String username) {
|
||||
private boolean checkUserWithSameUsernameExist(String username) {
|
||||
return repository.findByUsernameIgnoreCase(username).isPresent();
|
||||
}
|
||||
|
||||
public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
|
||||
private boolean checkUserWithSameUsernameExist(UserEntity user) {
|
||||
var existUser = repository.findByUsernameIgnoreCase(user.getUsername());
|
||||
return existUser.isPresent() && (int) existUser.get().getId() != (int) user.getId();
|
||||
}
|
||||
|
||||
public UserService(UserRepository repository) {
|
||||
this.repository = repository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
@ -58,32 +60,21 @@ public class UserService implements UserDetailsService {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
if (checkUsernameIsExist(entity.getUsername())) {
|
||||
if (checkUserWithSameUsernameExist(entity.getUsername())) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with username %s is already exists", entity.getUsername()));
|
||||
}
|
||||
entity.setPassword(passwordEncoder.encode(entity.getPassword()));
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity update(Integer id, UserEntity entity) {
|
||||
final UserEntity existsentity = get(id);
|
||||
var usersWithSameUsername = repository.findByUsernameIgnoreCase(entity.getUsername());
|
||||
if (usersWithSameUsername.get().getId() != existsentity.getId()) {
|
||||
public UserEntity update(UserEntity entity) {
|
||||
final UserEntity existsentity = get(entity.getId());
|
||||
if (checkUserWithSameUsernameExist(entity)) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with username %s is already exists", entity.getUsername()));
|
||||
}
|
||||
existsentity.setUsername(entity.getUsername());
|
||||
existsentity.setPassword(entity.getPassword());
|
||||
existsentity.setRole(entity.getRole());
|
||||
existsentity.setName(entity.getName());
|
||||
existsentity.setSurname(entity.getSurname());
|
||||
existsentity.setStatus(entity.getStatus());
|
||||
existsentity.setBirthday(entity.getBirthday());
|
||||
existsentity.setCity(entity.getCity());
|
||||
existsentity.setStatus(entity.getStatus());
|
||||
repository.save(existsentity);
|
||||
repository.save(entity);
|
||||
return existsentity;
|
||||
}
|
||||
|
||||
|
BIN
nekontakte/src/main/resources/public/favicon.ico
Normal file
BIN
nekontakte/src/main/resources/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 134 KiB |
BIN
nekontakte/src/main/resources/public/img/favicon.ico
Normal file
BIN
nekontakte/src/main/resources/public/img/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 134 KiB |
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{index}">
|
||||
|
||||
<head>
|
||||
<title>Ошибка</title>
|
||||
|
@ -12,7 +12,7 @@
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/5.3.3/dist/css/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="/webjars/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
|
||||
<link rel="stylesheet" href="/css/style.css" />
|
||||
<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">
|
||||
<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">
|
||||
<meta http-equiv="Pragma" content="no-cache">
|
||||
<meta http-equiv="Expires" content="0">
|
||||
</head>
|
||||
@ -36,18 +36,8 @@
|
||||
th:classappend="${activeLink.startsWith('/admin/user') ? 'active' : ''}">
|
||||
Пользователи
|
||||
</a>
|
||||
<a class="nav-link" href="/admin/type"
|
||||
th:classappend="${activeLink.startsWith('/admin/type') ? 'active' : ''}">
|
||||
Типы заказов
|
||||
</a>
|
||||
<a class="nav-link" href="/admin/subscription"
|
||||
th:classappend="${activeLink.startsWith('/admin/subscription') ? 'active' : ''}">
|
||||
Списки рассылки
|
||||
</a>
|
||||
<a class="nav-link" href="/h2-console/" target="_blank">Консоль H2</a>
|
||||
</th:block>
|
||||
<a class="nav-link" href="/123" target="_blank">Ошибка 1</a>
|
||||
<a class="nav-link" href="/admin/123" target="_blank">Ошибка 2</a>
|
||||
</ul>
|
||||
<ul class="navbar-nav" th:if="${not #strings.isEmpty(userName)}">
|
||||
<form th:action="@{/logout}" method="post">
|
||||
@ -55,10 +45,6 @@
|
||||
Выход ([[${userName}]])
|
||||
</button>
|
||||
</form>
|
||||
<a class="navbar-brand" href="/cart">
|
||||
<i class="bi bi-cart2 d-inline-block align-top me-1 logo"></i>
|
||||
[[${#numbers.formatDecimal(totalCart, 1, 2)}]] ₽
|
||||
</a>
|
||||
</ul>
|
||||
</div>
|
||||
</th:block>
|
@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{index}">
|
||||
|
||||
<head>
|
||||
<title>Вход</title>
|
||||
|
@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{index}">
|
||||
|
||||
<head>
|
||||
<title>Вход</title>
|
||||
|
@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{index}">
|
||||
|
||||
<head>
|
||||
<title>Редакторовать пользователя</title>
|
||||
@ -7,21 +7,35 @@
|
||||
|
||||
<body>
|
||||
<main layout:fragment="content">
|
||||
<form action="#" th:action="@{/admin/user/edit/{id}(id=${user.id},page=${page})}" th:object="${user}"
|
||||
method="post">
|
||||
<div class="mb-3">
|
||||
<label for="id" class="form-label">ID</label>
|
||||
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
|
||||
</div>
|
||||
<form action="#" th:action="@{/admin/user/edit(page=${page})}" th:object="${user}" method="post">
|
||||
<input type="hidden" th:field="*{id}" id="id" class="form-control" readonly>
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Имя пользователя</label>
|
||||
<input type="text" th:field="*{username}" id="username" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('username')}" th:errors="*{username}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3 d-flex flex-row">
|
||||
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
|
||||
<a class="btn btn-secondary button-fixed-width" th:href="@{/admin/user(page=${page})}">Отмена</a>
|
||||
<div class="mb-3">
|
||||
<label for="userRole" class="form-label">Роль в системе</label>
|
||||
<select th:field="*{role}" id="userRole" class="form-control">
|
||||
<option
|
||||
th:each="userRoleOpt : ${T(com.example.nekontakte.users.model.UserRole).values()}"
|
||||
th:value="${userRoleOpt}"
|
||||
th:text="${userRoleOpt.displayName}">
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Пароль</label>
|
||||
<input type="password" th:field="*{password}" id="password" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="passwordConfirm" class="form-label">Пароль (подтверждение)</label>
|
||||
<input type="password" th:field="*{passwordConfirm}" id="passwordConfirm" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<button class="btn btn-success me-3" type="submit">Применить</button>
|
||||
<a th:href="@{/admin/user(page=${page})}" class="btn btn-danger" >Отмена</a>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
|
@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{index}">
|
||||
|
||||
<head>
|
||||
<title>Пользователи</title>
|
||||
@ -12,7 +12,7 @@
|
||||
<th:block th:case="*">
|
||||
<h2>Пользователи</h2>
|
||||
<div>
|
||||
<a th:href="@{/admin/user/edit/(page=${page})}" class="btn btn-primary">Добавить пользователя</a>
|
||||
<a th:href="@{/admin/user/create}" class="btn btn-primary">Добавить пользователя</a>
|
||||
</div>
|
||||
<table class="table">
|
||||
<caption></caption>
|
||||
@ -31,14 +31,18 @@
|
||||
<td>
|
||||
<form th:action="@{/admin/user/edit/{id}(id=${user.id})}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-link button-link">Редактировать</button>
|
||||
<button type="submit" class="btn btn-link button-link">
|
||||
<i class="bi bi-pencil text-warning-emphasis"></i>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form th:action="@{/admin/user/delete/{id}(id=${user.id})}" method="post">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-link button-link"
|
||||
onclick="return confirm('Вы уверены?')">Удалить</button>
|
||||
onclick="return confirm('Вы уверены?')">
|
||||
<i class="bi bi-trash text-danger-emphasis"></i>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
|
@ -1,148 +0,0 @@
|
||||
package com.example.nekontakte;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.apache.coyote.BadRequestException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.nekontakte.core.errors.NotFoundException;
|
||||
import com.example.nekontakte.posts.model.PostEntity;
|
||||
import com.example.nekontakte.posts.service.PostService;
|
||||
import com.example.nekontakte.users.model.UserEntity;
|
||||
import com.example.nekontakte.users.service.UserService;
|
||||
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class PostServiceTests {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private PostService postService;
|
||||
|
||||
private UserEntity firstUser;
|
||||
private UserEntity secondUser;
|
||||
|
||||
private PostEntity firstPost;
|
||||
private PostEntity secondPost;
|
||||
private PostEntity thirdPost;
|
||||
|
||||
@BeforeEach
|
||||
void createData() throws ParseException, BadRequestException {
|
||||
removeData();
|
||||
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
|
||||
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.ENGLISH);
|
||||
|
||||
firstUser = new UserEntity();
|
||||
firstUser.setUsername("nspotapov");
|
||||
firstUser.setPassword("pass123456");
|
||||
firstUser.setName("Никита");
|
||||
firstUser.setSurname("Потапов");
|
||||
firstUser.setCity("Ульяновск");
|
||||
firstUser.setStatus("Я здесь админ");
|
||||
firstUser.setBirthday(dateFormatter.parse("17.02.2003"));
|
||||
|
||||
secondUser = new UserEntity();
|
||||
secondUser.setUsername("ekallin");
|
||||
secondUser.setPassword("pass87654321");
|
||||
secondUser.setName("Елена");
|
||||
secondUser.setSurname("Каллин");
|
||||
secondUser.setCity("Новоульяновск");
|
||||
secondUser.setBirthday(dateFormatter.parse("14.06.2005"));
|
||||
|
||||
firstUser = userService.create(firstUser);
|
||||
secondUser = userService.create(secondUser);
|
||||
|
||||
firstPost = new PostEntity();
|
||||
firstPost.setUser(firstUser);
|
||||
firstPost.setPubDate(dateFormatter.parse("01.04.2024"));
|
||||
firstPost.setHtml("Первый тестовый пост");
|
||||
|
||||
firstPost = postService.create(firstPost);
|
||||
|
||||
secondPost = new PostEntity();
|
||||
secondPost.setUser(firstUser);
|
||||
secondPost.setPubDate(dateTimeFormatter.parse("22.03.2024, 09:34:01"));
|
||||
secondPost.setImage("myimage.jpg");
|
||||
secondPost.setHtml("Второй тестовый пост");
|
||||
|
||||
secondPost = postService.create(secondPost);
|
||||
|
||||
thirdPost = new PostEntity();
|
||||
thirdPost.setUser(secondUser);
|
||||
thirdPost.setPubDate(dateTimeFormatter.parse("13.02.2024, 18:01:01"));
|
||||
thirdPost.setImage("ohmypost.jpg");
|
||||
thirdPost.setHtml("Третий постовый пост");
|
||||
|
||||
thirdPost = postService.create(thirdPost);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
postService.getAll().forEach(item -> postService.delete(item.getId()));
|
||||
userService.getAll().forEach(item -> userService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> postService.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() throws ParseException, BadRequestException {
|
||||
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.ENGLISH);
|
||||
|
||||
PostEntity fourthPost = new PostEntity();
|
||||
fourthPost.setUser(secondUser);
|
||||
fourthPost.setPubDate(dateTimeFormatter.parse("13.02.2024, 18:01:01"));
|
||||
|
||||
Assertions.assertThrows(BadRequestException.class,
|
||||
() -> postService.create(fourthPost));
|
||||
|
||||
PostEntity test = postService.get(firstPost.getId());
|
||||
|
||||
Assertions.assertEquals(firstPost, test);
|
||||
Assertions.assertEquals(firstUser, postService.get(firstPost.getId()).getUser());
|
||||
Assertions.assertEquals(secondUser, postService.get(thirdPost.getId()).getUser());
|
||||
Assertions.assertEquals(3, postService.getAll().size());
|
||||
Assertions.assertEquals(2, postService.getAllByUserId(firstUser.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void update() throws BadRequestException, ParseException {
|
||||
Integer postId = firstPost.getId();
|
||||
PostEntity oldPost = postService.get(postId);
|
||||
String oldImage = oldPost.getImage();
|
||||
|
||||
PostEntity newPost = new PostEntity();
|
||||
newPost.setId(oldPost.getId());
|
||||
newPost.setUser(oldPost.getUser());
|
||||
newPost.setPubDate(oldPost.getPubDate());
|
||||
newPost.setImage("new image");
|
||||
newPost.setHtml(oldPost.getHtml());
|
||||
|
||||
postService.update(postId, newPost);
|
||||
Assertions.assertNotEquals(postService.get(postId).getImage(), oldImage);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void delete() {
|
||||
final int oldCount = postService.getAll().size();
|
||||
postService.delete(firstPost.getId());
|
||||
Assertions.assertEquals(oldCount - 1, postService.getAll().size());
|
||||
}
|
||||
}
|
@ -1,136 +0,0 @@
|
||||
package com.example.nekontakte;
|
||||
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.apache.coyote.BadRequestException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.nekontakte.core.errors.NotFoundException;
|
||||
import com.example.nekontakte.subscribes.model.SubscribeEntity;
|
||||
import com.example.nekontakte.subscribes.service.SubscribeService;
|
||||
import com.example.nekontakte.users.service.UserService;
|
||||
import com.example.nekontakte.users.model.UserEntity;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class SubscribeServiceTests {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private SubscribeService subscribeService;
|
||||
private UserEntity firstUser;
|
||||
private UserEntity secondUser;
|
||||
private UserEntity thirdUser;
|
||||
|
||||
private SubscribeEntity secondSubscribe;
|
||||
|
||||
@BeforeEach
|
||||
void createData() throws ParseException, BadRequestException {
|
||||
removeData();
|
||||
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
|
||||
|
||||
UserEntity firstUserEntity = new UserEntity();
|
||||
firstUserEntity.setUsername("nspotapov");
|
||||
firstUserEntity.setPassword("pass123456");
|
||||
firstUserEntity.setName("Никита");
|
||||
firstUserEntity.setSurname("Потапов");
|
||||
firstUserEntity.setCity("Ульяновск");
|
||||
firstUserEntity.setStatus("Я здесь админ");
|
||||
firstUserEntity.setBirthday(dateFormatter.parse("17.02.2003"));
|
||||
|
||||
UserEntity secondUserEntity = new UserEntity();
|
||||
secondUserEntity.setUsername("ekallin");
|
||||
secondUserEntity.setPassword("pass87654321");
|
||||
secondUserEntity.setName("Елена");
|
||||
secondUserEntity.setSurname("Каллин");
|
||||
secondUserEntity.setCity("Новоульяновск");
|
||||
secondUserEntity.setBirthday(dateFormatter.parse("14.06.2005"));
|
||||
|
||||
UserEntity thirdUserEntity = new UserEntity();
|
||||
thirdUserEntity.setUsername("olegulya");
|
||||
thirdUserEntity.setPassword("passOleg");
|
||||
thirdUserEntity.setName("Олег");
|
||||
thirdUserEntity.setSurname("Тинькофф");
|
||||
thirdUserEntity.setCity("Полысаево");
|
||||
thirdUserEntity.setStatus(
|
||||
"Вчера я потерял $250 млн за день, были дни и похуже, миллиарды в день терял. Поэтому это позитивный очень день");
|
||||
thirdUserEntity.setBirthday(dateFormatter.parse("25.12.1967"));
|
||||
|
||||
firstUser = userService.create(firstUserEntity);
|
||||
secondUser = userService.create(secondUserEntity);
|
||||
thirdUser = userService.create(thirdUserEntity);
|
||||
|
||||
SubscribeEntity subscribeEntity = new SubscribeEntity();
|
||||
subscribeEntity.setUser(firstUser);
|
||||
subscribeEntity.setSubscriber(secondUser);
|
||||
|
||||
subscribeService.create(subscribeEntity);
|
||||
|
||||
subscribeEntity = new SubscribeEntity();
|
||||
subscribeEntity.setUser(firstUser);
|
||||
subscribeEntity.setSubscriber(thirdUser);
|
||||
|
||||
secondSubscribe = subscribeService.create(subscribeEntity);
|
||||
|
||||
subscribeEntity = new SubscribeEntity();
|
||||
subscribeEntity.setUser(secondUser);
|
||||
subscribeEntity.setSubscriber(thirdUser);
|
||||
|
||||
subscribeService.create(subscribeEntity);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
subscribeService.getAll().forEach(item -> subscribeService.delete(item.getId()));
|
||||
userService.getAll().forEach(item -> userService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> subscribeService.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() throws ParseException, BadRequestException {
|
||||
Assertions.assertEquals(secondSubscribe, subscribeService.get(secondSubscribe.getId()));
|
||||
Assertions.assertEquals(3, subscribeService.getAll().size());
|
||||
Assertions.assertEquals(2, subscribeService.getAllByUserId(firstUser.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void update() throws BadRequestException, ParseException {
|
||||
Integer subscribeId = secondSubscribe.getId();
|
||||
SubscribeEntity oldSubscribeEntity = subscribeService.get(subscribeId);
|
||||
UserEntity oldSubscriber = oldSubscribeEntity.getSubscriber();
|
||||
|
||||
SubscribeEntity newSubscribeEntity = new SubscribeEntity();
|
||||
newSubscribeEntity.setId(oldSubscribeEntity.getId());
|
||||
newSubscribeEntity.setUser(oldSubscribeEntity.getUser());
|
||||
newSubscribeEntity.setSubscriber(secondUser);
|
||||
|
||||
subscribeService.update(subscribeId, newSubscribeEntity);
|
||||
Assertions.assertNotEquals(subscribeService.get(subscribeId).getSubscriber(), oldSubscriber);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void delete() {
|
||||
Integer oldCount = subscribeService.getAll().size();
|
||||
subscribeService.delete(secondSubscribe.getId());
|
||||
Assertions.assertEquals(oldCount - 1, subscribeService.getAll().size());
|
||||
}
|
||||
}
|
@ -1,113 +0,0 @@
|
||||
package com.example.nekontakte;
|
||||
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.nekontakte.core.errors.NotFoundException;
|
||||
import com.example.nekontakte.users.service.UserService;
|
||||
import com.example.nekontakte.users.model.UserEntity;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class UserServiceTests {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
private UserEntity firstUser;
|
||||
|
||||
@BeforeEach
|
||||
void createData() throws ParseException {
|
||||
removeData();
|
||||
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
|
||||
|
||||
UserEntity firstUserEntity = new UserEntity();
|
||||
firstUserEntity.setUsername("nspotapov");
|
||||
firstUserEntity.setPassword("pass123456");
|
||||
firstUserEntity.setName("Никита");
|
||||
firstUserEntity.setSurname("Потапов");
|
||||
firstUserEntity.setCity("Ульяновск");
|
||||
firstUserEntity.setStatus("Я здесь админ");
|
||||
firstUserEntity.setBirthday(dateFormatter.parse("17.02.2003"));
|
||||
|
||||
UserEntity secondUserEntity = new UserEntity();
|
||||
secondUserEntity.setUsername("ekallin");
|
||||
secondUserEntity.setPassword("pass87654321");
|
||||
secondUserEntity.setName("Елена");
|
||||
secondUserEntity.setSurname("Каллин");
|
||||
secondUserEntity.setCity("Новоульяновск");
|
||||
secondUserEntity.setBirthday(dateFormatter.parse("14.06.2005"));
|
||||
|
||||
UserEntity thirdUserEntity = new UserEntity();
|
||||
thirdUserEntity.setUsername("olegulya");
|
||||
thirdUserEntity.setPassword("passOleg");
|
||||
thirdUserEntity.setName("Олег");
|
||||
thirdUserEntity.setSurname("Тинькофф");
|
||||
thirdUserEntity.setCity("Полысаево");
|
||||
thirdUserEntity.setStatus(
|
||||
"Вчера я потерял $250 млн за день, были дни и похуже, миллиарды в день терял. Поэтому это позитивный очень день");
|
||||
thirdUserEntity.setBirthday(dateFormatter.parse("25.12.1967"));
|
||||
|
||||
firstUser = userService.create(firstUserEntity);
|
||||
userService.create(secondUserEntity);
|
||||
userService.create(thirdUserEntity);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
userService.getAll().forEach(item -> userService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() throws ParseException {
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void update() {
|
||||
final String newPassword = "newpassword";
|
||||
final UserEntity existEntity = userService.get(firstUser.getId());
|
||||
final String oldPassword = existEntity.getPassword();
|
||||
|
||||
final UserEntity entity = new UserEntity();
|
||||
entity.setUsername(existEntity.getUsername());
|
||||
entity.setPassword(newPassword);
|
||||
entity.setName(existEntity.getName());
|
||||
entity.setSurname(existEntity.getSurname());
|
||||
entity.setBirthday(existEntity.getBirthday());
|
||||
entity.setCity(existEntity.getCity());
|
||||
entity.setAvatarImg(existEntity.getAvatarImg());
|
||||
entity.setStatus(existEntity.getStatus());
|
||||
entity.setRole(existEntity.getRole());
|
||||
|
||||
final UserEntity newEntity = userService.update(firstUser.getId(), entity);
|
||||
Assertions.assertEquals(newPassword, newEntity.getPassword());
|
||||
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void delete() {
|
||||
userService.delete(firstUser.getId());
|
||||
Assertions.assertEquals(2, userService.getAll().size());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user