add users

This commit is contained in:
DozorovaA.A 2023-06-13 13:19:50 +04:00
parent 3604cd3fe5
commit 8396e20146
21 changed files with 529 additions and 20 deletions

View File

@ -16,6 +16,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.security:spring-security-config:6.0.2'
implementation 'org.springframework.security:spring-security-web:6.1.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'io.springfox:springfox-swagger-ui:3.0.0'
@ -23,9 +25,16 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE'
implementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
jar {
manifest {

Binary file not shown.

View File

@ -11,7 +11,7 @@ public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("appointment");
registry.addViewController("login");
}
@Override

View File

@ -0,0 +1,14 @@
package com.example.demo.speaker;
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,69 @@
package com.example.demo.speaker;
import com.example.demo.speaker.model.UserRole;
import com.example.demo.speaker.service.UserService;
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 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@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("/images/**")
.antMatchers("/js/**")
.antMatchers("/templates/**")
.antMatchers("/webjars/**");
}
}

View File

@ -0,0 +1,24 @@
package com.example.demo.speaker.controller.DTO;
import com.example.demo.speaker.model.User;
import com.example.demo.speaker.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,31 @@
package com.example.demo.speaker.controller.DTO;
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,40 @@
package com.example.demo.speaker.controller.MVCController;
import com.example.demo.speaker.controller.DTO.UserDTO;
import com.example.demo.speaker.model.UserRole;
import com.example.demo.speaker.service.UserService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
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,44 @@
package com.example.demo.speaker.controller.MVCController;
import com.example.demo.speaker.controller.DTO.UserSignupDTO;
import com.example.demo.speaker.model.User;
import com.example.demo.speaker.service.UserService;
import org.springframework.web.bind.annotation.ModelAttribute;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@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") 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 (Exception e) {
//model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -0,0 +1,83 @@
package com.example.demo.speaker.model;
import jakarta.persistence.*;
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,17 @@
package com.example.demo.speaker.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

@ -0,0 +1,8 @@
package com.example.demo.speaker.repository;
import com.example.demo.speaker.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface IUserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,62 @@
package com.example.demo.speaker.service;
import com.example.demo.speaker.model.User;
import com.example.demo.speaker.model.UserRole;
import com.example.demo.speaker.repository.IUserRepository;
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 java.util.Collections;
import java.util.Objects;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final IUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
//private final ValidatorUtil validatorUtil;
public UserService(IUserRepository userRepository,
PasswordEncoder passwordEncoder
/*ValidatorUtil validatorUtil*/) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
//this.validatorUtil = validatorUtil;
}
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);
//validatorUtil.validate(user);
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

@ -10,10 +10,10 @@
<form action="#" th:action="@{/appointment/create}" th:object="${appointmentDTO}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${appointmentDTO.name}" required="true">
<input type="text" class="form-control" id="name" th:field="${appointmentDTO.name}" required="true" style="width: 20%">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<button type="submit" class="btn btn-info">
<span >Добавить</span>
</button>
</div>
@ -34,12 +34,12 @@
<td ><!--<td th:text="${appointment.name}"/>-->
<form th:action="@{/appointment/edit/{id}(id=${appointment.id})}" th:object="${appointmentDTO}" th:method="post">
<input type="text" class="form-control" id="nameAppointment" th:field="${appointmentDTO.name}" th:placeholder="${appointment.name}" style="width: 60%; display: inline-block" >
<button class="btn btn-warning button-fixed button-sm"
<button class="btn btn-info"
type="submit" style="display: inline-block"> Изменить
</button>
<button type="button" class="btn btn-danger button-fixed button-sm" style="display: inline-block"
<button type="button" class="btn btn-info" style="display: inline-block"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${appointment.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
Удалить
</button>
</form></td>
<!--<td th:text="${appointment.name}" style="width: 60%"/>-->

View File

@ -12,7 +12,7 @@
<input type="text" class="form-control" id="legalAdressCompanyNew" th:field="*{legalAdressCompany}" style="width: 15%; display: inline-block" >
<input type="text" class="form-control" id="adressCompanyNew" th:field="*{adressCompany}" style="width: 15%; display: inline-block" >
<input type="text" class="form-control" id="contactEmailNew" th:field="*{contactEmail}" style="width: 15%; display: inline-block" >
<button class="btn btn-warning button-fixed button-sm"
<button class="btn btn-info"
type="submit" style="display: inline-block"> Создать
</button>
</form>
@ -35,12 +35,12 @@
<input type="text" class="form-control" id="legalAdressCompany" th:placeholder="${company.legalAdressCompany}" th:field="*{legalAdressCompany}" style="width: 15%; display: inline-block" >
<input type="text" class="form-control" id="adressCompany" th:placeholder="${company.adressCompany}" th:field="*{adressCompany}" style="width: 15%; display: inline-block" >
<input type="text" class="form-control" id="contactEmail" th:placeholder="${company.contactEmail}" th:field="*{contactEmail}" style="width: 15%; display: inline-block" >
<button class="btn btn-warning button-fixed button-sm"
<button class="btn btn-info"
type="submit" style="display: inline-block"> Изменить
</button>
<button type="button" class="btn btn-danger button-fixed button-sm" style="display: inline-block"
<button type="button" class="btn btn-info" style="display: inline-block"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${company.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
Удалить
</button>
</form></td>
<!--<td th:text="${appointment.name}" style="width: 60%"/>-->

View File

@ -1,7 +1,8 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8"/>
<title>Site of Company</title>
@ -36,6 +37,8 @@
th:classappend="${#strings.equals(activeLink, '/employee')} ? 'active' : ''">Employee</a>
<a class="nav-link" href="/request"
th:classappend="${#strings.equals(activeLink, '/request')} ? 'active' : ''">Request</a>
<a class="nav-link" href="/users" sec:authorize="hasRole('ROLE_ADMIN')" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Выход</a>
</ul>
</div>
</div>

View File

@ -18,7 +18,7 @@
</option>
</select>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<button type="submit" class="btn btn-info">
<span >Добавить</span>
</button>
</div>
@ -47,12 +47,12 @@
</option>
</select>
<button class="btn btn-warning button-fixed button-sm"
<button class="btn btn-info"
type="submit" style="display: inline-block"> Изменить
</button>
<button type="button" class="btn btn-danger button-fixed button-sm" style="display: inline-block"
<button type="button" class="btn btn-info" style="display: inline-block"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${employee.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
Удалить
</button>
</form></td>
<!--<td th:text="${appointment.name}" style="width: 60%"/>-->

View File

@ -0,0 +1,34 @@
<!DOCTYPE html>
<!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}">
<head>
</head>
<body>
<div 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

@ -41,19 +41,19 @@
</option>
</select>
<button class="btn btn-warning button-fixed button-sm"
<button class="btn btn-info"
type="submit" style="display: inline-block"> Изменить
</button>
<button type="button" class="btn btn-danger button-fixed button-sm" style="display: inline-block"
<button type="button" class="btn btn-info" style="display: inline-block"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${employee.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
Удалить
</button>
</form></td>
<!--<td th:text="${appointment.name}" style="width: 60%"/>-->
<td style="width: 10%">
<form th:action="@{/employee/delete/{id}(id=${employee.id})}" method="post">
<button th:id="'remove-' + ${employee.id}" type="submit" style="display: none">
<form th:action="@{/employee/delete/{id}(id=${request.id})}" method="post">
<button th:id="'remove-' + ${request.id}" type="submit" style="display: none">
Удалить
</button>
</form>

View File

@ -0,0 +1,31 @@
<!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}">
<head>
</head>
<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,40 @@
<!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}">
<head>
</head>
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table text-light">
<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 text-light">
<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>