diff --git a/build.gradle b/build.gradle index a7dc0d0..d044239 100644 --- a/build.gradle +++ b/build.gradle @@ -24,11 +24,13 @@ dependencies { implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jetty' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf' + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa' - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux' + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security' implementation group: 'org.json', name: 'json', version: '20220320' implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect' + implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity6' implementation group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner' implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5' implementation group: 'com.h2database', name:'h2' diff --git a/src/main/java/ru/ulstu/fc/FuzzyControllerApplication.java b/src/main/java/ru/ulstu/fc/FuzzyControllerApplication.java index f490108..27dcbf9 100644 --- a/src/main/java/ru/ulstu/fc/FuzzyControllerApplication.java +++ b/src/main/java/ru/ulstu/fc/FuzzyControllerApplication.java @@ -2,11 +2,28 @@ package ru.ulstu.fc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.event.EventListener; +import ru.ulstu.fc.user.service.UserService; @SpringBootApplication +@EnableConfigurationProperties public class FuzzyControllerApplication { + private final UserService userService; + + public FuzzyControllerApplication(UserService userService) { + this.userService = userService; + } + public static void main(String[] args) { SpringApplication.run(FuzzyControllerApplication.class, args); } + + @EventListener(ApplicationReadyEvent.class) + public void doSomethingAfterStartup() { + System.out.println("hello world, I have just started up"); + userService.initDefaultAdmin(); + } } diff --git a/src/main/java/ru/ulstu/fc/config/Constants.java b/src/main/java/ru/ulstu/fc/config/Constants.java new file mode 100644 index 0000000..7d922bb --- /dev/null +++ b/src/main/java/ru/ulstu/fc/config/Constants.java @@ -0,0 +1,12 @@ +package ru.ulstu.fc.config; + +public class Constants { + public static final int MIN_PASSWORD_LENGTH = 6; + + public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$"; + + public static final String COOKIES_NAME = "JSESSIONID"; + public static final String LOGOUT_URL = "/login?logout"; + public static final String SESSION_ID_ATTR = "sessionId"; + public static final int SESSION_TIMEOUT_SECONDS = 30 * 60; +} diff --git a/src/main/java/ru/ulstu/fc/config/MvcConfiguration.java b/src/main/java/ru/ulstu/fc/config/MvcConfiguration.java index f4547a4..809147e 100644 --- a/src/main/java/ru/ulstu/fc/config/MvcConfiguration.java +++ b/src/main/java/ru/ulstu/fc/config/MvcConfiguration.java @@ -1,9 +1,3 @@ -/* - * Copyright (C) 2021 Anton Romanov - All Rights Reserved - * You may use, distribute and modify this code, please write to: romanov73@gmail.com. - * - */ - package ru.ulstu.fc.config; import org.springframework.context.annotation.Bean; @@ -11,12 +5,19 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class MvcConfiguration implements WebMvcConfigurer { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login"); + registry.addViewController("/loginError"); + registry.addViewController("/index"); + } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { diff --git a/src/main/java/ru/ulstu/fc/config/PasswordEncoderConfiguration.java b/src/main/java/ru/ulstu/fc/config/PasswordEncoderConfiguration.java new file mode 100644 index 0000000..4706fe8 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/config/PasswordEncoderConfiguration.java @@ -0,0 +1,13 @@ +package ru.ulstu.fc.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@Configuration +public class PasswordEncoderConfiguration { + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/ru/ulstu/fc/config/SecurityConfiguration.java b/src/main/java/ru/ulstu/fc/config/SecurityConfiguration.java new file mode 100644 index 0000000..6583cd0 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/config/SecurityConfiguration.java @@ -0,0 +1,52 @@ +package ru.ulstu.fc.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; +import org.springframework.security.web.SecurityFilterChain; +import ru.ulstu.fc.user.model.UserRoleConstants; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +public class SecurityConfiguration { + private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); + private final String[] permittedUrls = new String[]{ + "/login", "/index", + "/public/**", "/organizers", "/webjars/**", + "/h2-console/*", "/h2-console", + "/css/**", "/js/**", "/img/**", + "/templates/**", "/webjars/**"}; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + log.debug("Security enabled"); + + http + .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> + auth.requestMatchers("/").permitAll() + .requestMatchers(permittedUrls).permitAll() + .requestMatchers("/swagger-ui.html").hasAuthority(UserRoleConstants.ADMIN) + .anyRequest().authenticated()) + .formLogin(form -> + form.loginPage("/login") + .failureUrl("/loginError") + .permitAll()) + .logout(logout -> + logout + .logoutSuccessUrl(Constants.LOGOUT_URL) + .invalidateHttpSession(false) + .clearAuthentication(true) + .deleteCookies(Constants.COOKIES_NAME) + .permitAll()); + return http.build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/fc/config/WebClientConfiguration.java b/src/main/java/ru/ulstu/fc/config/WebClientConfiguration.java deleted file mode 100644 index 1761fc4..0000000 --- a/src/main/java/ru/ulstu/fc/config/WebClientConfiguration.java +++ /dev/null @@ -1,13 +0,0 @@ -package ru.ulstu.fc.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.function.client.WebClient; - -@Configuration -public class WebClientConfiguration { - @Bean - public WebClient webClient(WebClient.Builder webClientBuilder) { - return webClientBuilder.build(); - } -} diff --git a/src/main/java/ru/ulstu/fc/core/model/BaseEntity.java b/src/main/java/ru/ulstu/fc/core/model/BaseEntity.java new file mode 100644 index 0000000..bcc4c00 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/core/model/BaseEntity.java @@ -0,0 +1,84 @@ +package ru.ulstu.fc.core.model; + +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.Version; +import jakarta.validation.constraints.NotNull; + +import java.io.Serializable; + +@MappedSuperclass +public abstract class BaseEntity implements Serializable, Comparable { + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Integer id; + + @Version + private Integer version; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; + } + BaseEntity other = (BaseEntity) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (id == null ? 0 : id.hashCode()); + return result; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{" + + "id=" + id + + ", version=" + version + + '}'; + } + + @Override + public int compareTo(@NotNull BaseEntity o) { + return id != null ? id.compareTo(o.getId()) : -1; + } + + public void reset() { + this.id = null; + this.version = null; + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/fc/core/model/OffsetablePageRequest.java b/src/main/java/ru/ulstu/fc/core/model/OffsetablePageRequest.java new file mode 100644 index 0000000..abd3c06 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/core/model/OffsetablePageRequest.java @@ -0,0 +1,119 @@ +package ru.ulstu.fc.core.model; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; + +import java.io.Serializable; +import java.util.Optional; + +public class OffsetablePageRequest implements Pageable, Serializable { + private final int offset; + private final int count; + private final Sort sort; + + public OffsetablePageRequest(int page, long pageSize) { + this(pageSize * page, pageSize, Sort.by("id")); + } + + public OffsetablePageRequest(long offset, long count, Sort sort) { + if (offset < 0) { + throw new IllegalArgumentException("Offset value must not be less than zero!"); + } + if (count < 1) { + throw new IllegalArgumentException("Count value must not be less than one!"); + } + this.offset = (int) offset; + this.count = (int) count; + this.sort = sort; + } + + @Override + public Sort getSort() { + return sort; + } + + @Override + public Sort getSortOr(Sort sort) { + return Pageable.super.getSortOr(sort); + } + + @Override + public int getPageSize() { + return count; + } + + @Override + public boolean isPaged() { + return Pageable.super.isPaged(); + } + + @Override + public boolean isUnpaged() { + return Pageable.super.isUnpaged(); + } + + @Override + public int getPageNumber() { + return offset / count; + } + + @Override + public long getOffset() { + return offset; + } + + @Override + public boolean hasPrevious() { + return offset > 0; + } + + @Override + public Optional toOptional() { + return Pageable.super.toOptional(); + } + + @Override + public Pageable next() { + return new OffsetablePageRequest(getOffset() + getPageSize(), getPageSize(), getSort()); + } + + @Override + public Pageable previousOrFirst() { + return hasPrevious() ? previous() : first(); + } + + public Pageable previous() { + return getOffset() == 0 ? this : new OffsetablePageRequest(getOffset() - getPageSize(), getPageSize(), getSort()); + } + + @Override + public Pageable first() { + return new OffsetablePageRequest(0, getPageSize(), getSort()); + } + + @Override + public Pageable withPage(int pageNumber) { + return null; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final OffsetablePageRequest other = (OffsetablePageRequest) obj; + return this.offset == other.offset && this.count == other.count; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + offset; + result = prime * result + count; + return result; + } +} diff --git a/src/main/java/ru/ulstu/fc/project/controller/ProjectController.java b/src/main/java/ru/ulstu/fc/project/controller/ProjectController.java new file mode 100644 index 0000000..85c28a8 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/controller/ProjectController.java @@ -0,0 +1,55 @@ +package ru.ulstu.fc.project.controller; + +import io.swagger.v3.oas.annotations.Hidden; +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.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import ru.ulstu.fc.project.model.Project; +import ru.ulstu.fc.project.model.ProjectForm; +import ru.ulstu.fc.project.service.ProjectService; +import ru.ulstu.fc.user.model.UserRoleConstants; + +@Controller +@Hidden +@RequestMapping("project") +@Secured({UserRoleConstants.ADMIN}) +public class ProjectController { + private final ProjectService projectService; + + public ProjectController(ProjectService projectService) { + this.projectService = projectService; + } + + @GetMapping("list") + public String getProjects(Model model) { + model.addAttribute("projects", projectService.getCurrentUserProjects()); + return "project/list"; + } + + @GetMapping("/edit/{projectId}") + public String edit(@PathVariable(value = "projectId") Integer id, Model model) { + model.addAttribute("project", + new ProjectForm((id != null && id != 0) + ? projectService.getById(id) + : new Project())); + return "project/edit"; + } + + @PostMapping(value = "save", params = "save") + public String save(ProjectForm projectForm, Model model) { + model.addAttribute("project", projectService.save(projectForm)); + return "redirect:/project/list"; + } + + @PostMapping(value = "save", params = "delete") + public String delete(ProjectForm projectForm) { + if (projectForm != null && projectForm.getId() != null) { + projectService.delete(projectForm); + } + return "redirect:/project/list"; + } +} diff --git a/src/main/java/ru/ulstu/fc/project/controller/ProjectRestController.java b/src/main/java/ru/ulstu/fc/project/controller/ProjectRestController.java new file mode 100644 index 0000000..7fcce20 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/controller/ProjectRestController.java @@ -0,0 +1,41 @@ +package ru.ulstu.fc.project.controller; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.fc.project.model.Project; +import ru.ulstu.fc.project.model.ProjectForm; +import ru.ulstu.fc.project.service.ProjectService; +import ru.ulstu.fc.user.model.UserRoleConstants; + +import java.util.List; + +@RestController +@RequestMapping("projectRest") +@Secured({UserRoleConstants.ADMIN}) +public class ProjectRestController { + private final ProjectService projectService; + + public ProjectRestController(ProjectService projectService) { + this.projectService = projectService; + } + + @GetMapping("list") + public List getProjects() { + return projectService.getCurrentUserProjects(); + } + + @PostMapping("save") + public Project save(Project project) { + return projectService.save(project); + } + + @DeleteMapping("delete") + public String delete(ProjectForm projectForm) { + projectService.delete(projectForm); + return "redirect:/list"; + } +} diff --git a/src/main/java/ru/ulstu/fc/project/model/Project.java b/src/main/java/ru/ulstu/fc/project/model/Project.java new file mode 100644 index 0000000..4725550 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/model/Project.java @@ -0,0 +1,52 @@ +package ru.ulstu.fc.project.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import jakarta.validation.constraints.NotEmpty; +import ru.ulstu.fc.core.model.BaseEntity; +import ru.ulstu.fc.user.model.User; + +import java.util.Date; + +@Entity +public class Project extends BaseEntity { + @NotEmpty(message = "Текст новости не может быть пустым") + private String name; + private Date createDate = new Date(); + @ManyToOne + private User user; + + public Project() { + } + + public Project(ProjectForm projectForm) { + if (projectForm.getId() != null) { + setId(projectForm.getId()); + } + this.name = projectForm.getName(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/src/main/java/ru/ulstu/fc/project/model/ProjectForm.java b/src/main/java/ru/ulstu/fc/project/model/ProjectForm.java new file mode 100644 index 0000000..a03532b --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/model/ProjectForm.java @@ -0,0 +1,38 @@ +package ru.ulstu.fc.project.model; + +import java.util.Date; + +public class ProjectForm { + private Integer id; + private String name; + private Date createDate; + + public ProjectForm() { + } + + public ProjectForm(Project project) { + this.id = project.getId(); + this.name = project.getName(); + this.createDate = project.getCreateDate(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreateDate() { + return createDate; + } +} diff --git a/src/main/java/ru/ulstu/fc/project/repository/ProjectRepository.java b/src/main/java/ru/ulstu/fc/project/repository/ProjectRepository.java new file mode 100644 index 0000000..547ac15 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/repository/ProjectRepository.java @@ -0,0 +1,14 @@ +package ru.ulstu.fc.project.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import ru.ulstu.fc.project.model.Project; + +import java.util.List; + +@Repository +public interface ProjectRepository extends JpaRepository { + + List findAllByUserId(@Param("userId") Integer userId); +} diff --git a/src/main/java/ru/ulstu/fc/project/service/ProjectService.java b/src/main/java/ru/ulstu/fc/project/service/ProjectService.java new file mode 100644 index 0000000..39a9cb5 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/project/service/ProjectService.java @@ -0,0 +1,64 @@ +package ru.ulstu.fc.project.service; + +import org.springframework.stereotype.Service; +import ru.ulstu.fc.project.model.Project; +import ru.ulstu.fc.project.model.ProjectForm; +import ru.ulstu.fc.project.repository.ProjectRepository; +import ru.ulstu.fc.user.model.User; +import ru.ulstu.fc.user.service.UserService; + +import java.util.List; + +@Service +public class ProjectService { + private final ProjectRepository projectRepository; + private final UserService userService; + + public ProjectService(ProjectRepository projectRepository, + UserService userService) { + this.projectRepository = projectRepository; + this.userService = userService; + } + + public List getCurrentUserProjects() { + return projectRepository.findAllByUserId(userService.getCurrentUser().getId()); + } + + public Project getById(Integer id) { + Project project = projectRepository + .findById(id) + .orElseThrow(() -> new RuntimeException("Project not found by id")); + checkUserProjectWithThrow(project, userService.getCurrentUser()); + return project; + } + + public Project save(ProjectForm projectForm) { + return save(new Project(projectForm)); + } + + public Project save(Project projectToSave) { + User currentUser = userService.getCurrentUser(); + if (projectToSave.getId() == null) { + projectToSave.setUser(currentUser); + return projectRepository.save(projectToSave); + } + Project dbProject = getById(projectToSave.getId()); + dbProject.setName(projectToSave.getName()); + return projectRepository.save(dbProject); + } + + public void delete(ProjectForm projectForm) { + getById(projectForm.getId()); + projectRepository.deleteById(projectForm.getId()); + } + + private void checkUserProjectWithThrow(Project project, User currentUser) { + if (!isUserProject(project, currentUser)) { + throw new RuntimeException("User can not get access to project"); + } + } + + private boolean isUserProject(Project project, User currentUser) { + return (currentUser.equals(project.getUser())); + } +} diff --git a/src/main/java/ru/ulstu/fc/rule/controller/InferenceRestController.java b/src/main/java/ru/ulstu/fc/rule/controller/InferenceRestController.java index 0f3fb7e..dcb0a8f 100644 --- a/src/main/java/ru/ulstu/fc/rule/controller/InferenceRestController.java +++ b/src/main/java/ru/ulstu/fc/rule/controller/InferenceRestController.java @@ -11,7 +11,7 @@ import ru.ulstu.fc.rule.service.FuzzyInferenceService; import java.util.List; @RestController -@RequestMapping("rest") +@RequestMapping("inferenceRest") public class InferenceRestController { private final FuzzyInferenceService fuzzyInferenceService; diff --git a/src/main/java/ru/ulstu/fc/user/model/User.java b/src/main/java/ru/ulstu/fc/user/model/User.java new file mode 100644 index 0000000..11b3162 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/model/User.java @@ -0,0 +1,72 @@ +package ru.ulstu.fc.user.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import ru.ulstu.fc.config.Constants; +import ru.ulstu.fc.core.model.BaseEntity; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table(name = "is_users") +public class User extends BaseEntity { + @NotNull + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + @Column(length = 50, unique = true, nullable = false) + private String login; + + @NotNull + @Size(min = 60, max = 60) + @Column(name = "password_hash", length = 60, nullable = false) + private String password; + + @ManyToMany + @JoinTable( + name = "is_user_role", + joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, + inverseJoinColumns = {@JoinColumn(name = "user_role_name", referencedColumnName = "name")}) + private Set roles; + + public User() { + roles = new HashSet<>(); + } + + public User(String login, String password, Set roles) { + this.login = login; + this.password = password; + this.roles = roles; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login.toLowerCase(); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } +} diff --git a/src/main/java/ru/ulstu/fc/user/model/UserNotFoundException.java b/src/main/java/ru/ulstu/fc/user/model/UserNotFoundException.java new file mode 100644 index 0000000..7840fc6 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/model/UserNotFoundException.java @@ -0,0 +1,7 @@ +package ru.ulstu.fc.user.model; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/fc/user/model/UserRole.java b/src/main/java/ru/ulstu/fc/user/model/UserRole.java new file mode 100644 index 0000000..c6375cd --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/model/UserRole.java @@ -0,0 +1,50 @@ +package ru.ulstu.fc.user.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +@Entity +@Table(name = "is_user_roles") +public class UserRole { + @Id + @NotNull + @Size(max = 50) + @Column(length = 50, nullable = false) + private String name; + + public UserRole() { + } + + public UserRole(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserRole role = (UserRole) o; + return !(name != null ? !name.equals(role.name) : role.name != null); + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return name != null ? name.hashCode() : 0; + } +} diff --git a/src/main/java/ru/ulstu/fc/user/model/UserRoleConstants.java b/src/main/java/ru/ulstu/fc/user/model/UserRoleConstants.java new file mode 100644 index 0000000..4eae200 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/model/UserRoleConstants.java @@ -0,0 +1,6 @@ +package ru.ulstu.fc.user.model; + +public class UserRoleConstants { + public static final String ADMIN = "ROLE_ADMIN"; + public static final String USER = "ROLE_USER"; +} diff --git a/src/main/java/ru/ulstu/fc/user/model/UserSession.java b/src/main/java/ru/ulstu/fc/user/model/UserSession.java new file mode 100644 index 0000000..354402d --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/model/UserSession.java @@ -0,0 +1,105 @@ +package ru.ulstu.fc.user.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.validation.constraints.NotNull; +import ru.ulstu.fc.core.model.BaseEntity; + +import java.util.Date; + +@Entity +@Table(name = "is_user_sessions") +public class UserSession extends BaseEntity { + @NotNull + @Column(name = "session_id", nullable = false, unique = true) + private String sessionId; + + @NotNull + @Column(name = "ip_address", nullable = false) + private String ipAddress; + + @NotNull + @Column(nullable = false) + private String host; + + @NotNull + @Column(name = "login_time", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date loginTime; + + @Column(name = "logout_time") + @Temporal(TemporalType.TIMESTAMP) + private Date logoutTime; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_id") + private User user; + + public UserSession() { + } + + public UserSession(String sessionId, String ipAddress, String host, User user) { + this.sessionId = sessionId; + this.ipAddress = ipAddress; + this.host = host; + this.loginTime = new Date(); + this.user = user; + } + + public String getSessionId() { + return sessionId; + } + + public String getIpAddress() { + return ipAddress; + } + + public String getHost() { + return host; + } + + public Date getLoginTime() { + return loginTime; + } + + public Date getLogoutTime() { + return logoutTime; + } + + public User getUser() { + return user; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public void setHost(String host) { + this.host = host; + } + + public void setLoginTime(Date loginTime) { + this.loginTime = loginTime; + } + + public void setLogoutTime(Date logoutTime) { + this.logoutTime = logoutTime; + } + + public void setUser(User user) { + this.user = user; + } + + public void close() { + this.logoutTime = new Date(); + } +} diff --git a/src/main/java/ru/ulstu/fc/user/repository/UserRepository.java b/src/main/java/ru/ulstu/fc/user/repository/UserRepository.java new file mode 100644 index 0000000..808bac5 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/repository/UserRepository.java @@ -0,0 +1,15 @@ +package ru.ulstu.fc.user.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.fc.user.model.User; + +public interface UserRepository extends JpaRepository { + User findOneByLoginIgnoreCase(String login); + + @EntityGraph(attributePaths = "roles") + User findOneWithRolesById(int id); + + @EntityGraph(attributePaths = "roles") + User findOneWithRolesByLogin(String login); +} diff --git a/src/main/java/ru/ulstu/fc/user/repository/UserRoleRepository.java b/src/main/java/ru/ulstu/fc/user/repository/UserRoleRepository.java new file mode 100644 index 0000000..3f03a8d --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/repository/UserRoleRepository.java @@ -0,0 +1,7 @@ +package ru.ulstu.fc.user.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.fc.user.model.UserRole; + +public interface UserRoleRepository extends JpaRepository { +} diff --git a/src/main/java/ru/ulstu/fc/user/repository/UserSessionRepository.java b/src/main/java/ru/ulstu/fc/user/repository/UserSessionRepository.java new file mode 100644 index 0000000..f4a6de4 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/repository/UserSessionRepository.java @@ -0,0 +1,13 @@ +package ru.ulstu.fc.user.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.fc.user.model.UserSession; + +import java.util.Date; +import java.util.List; + +public interface UserSessionRepository extends JpaRepository { + UserSession findOneBySessionId(String sessionId); + + List findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); +} diff --git a/src/main/java/ru/ulstu/fc/user/service/IpAddressResolver.java b/src/main/java/ru/ulstu/fc/user/service/IpAddressResolver.java new file mode 100644 index 0000000..51a0f36 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/service/IpAddressResolver.java @@ -0,0 +1,22 @@ +package ru.ulstu.fc.user.service; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.util.StringUtils; + +public final class IpAddressResolver { + private static final String CLIENT_IP_HEADER = "Client-IP"; + private static final String FORWARDED_FOR_HEADER = "X-Forwarded-For"; + + public static String getRemoteAddr(HttpServletRequest request) { + String headerClientIp = request.getHeader(""); + String headerXForwardedFor = request.getHeader(HttpServletRequest.FORM_AUTH); + if (StringUtils.isEmpty(request.getRemoteAddr()) && !StringUtils.isEmpty(headerClientIp)) { + return headerClientIp; + } + if (!StringUtils.isEmpty(headerXForwardedFor)) { + return headerXForwardedFor; + } + return request.getRemoteAddr(); + } + +} diff --git a/src/main/java/ru/ulstu/fc/user/service/UserService.java b/src/main/java/ru/ulstu/fc/user/service/UserService.java new file mode 100644 index 0000000..b94a49c --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/service/UserService.java @@ -0,0 +1,93 @@ +package ru.ulstu.fc.user.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.fc.user.model.User; +import ru.ulstu.fc.user.model.UserNotFoundException; +import ru.ulstu.fc.user.model.UserRole; +import ru.ulstu.fc.user.model.UserRoleConstants; +import ru.ulstu.fc.user.repository.UserRepository; +import ru.ulstu.fc.user.repository.UserRoleRepository; +import ru.ulstu.fc.user.utils.UserUtils; + +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@Transactional +public class UserService implements UserDetailsService { + private final Logger log = LoggerFactory.getLogger(UserService.class); + private final PasswordEncoder passwordEncoder; + private final UserRepository userRepository; + private final UserRoleRepository userRoleRepository; + @Value("${admin-password}") + private String adminPassword; + + public UserService(PasswordEncoder passwordEncoder, + UserRepository userRepository, + UserRoleRepository userRoleRepository) { + this.passwordEncoder = passwordEncoder; + this.userRepository = userRepository; + this.userRoleRepository = userRoleRepository; + } + + public User getUserByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Override + public UserDetails loadUserByUsername(String username) { + final User user = userRepository.findOneByLoginIgnoreCase(username); + if (user == null) { + throw new UserNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User(user.getLogin(), + user.getPassword(), + Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() + .map(role -> new SimpleGrantedAuthority(role.getName())) + .collect(Collectors.toList())); + } + + public User createUser(User user) { + if (getUserByLogin(user.getLogin()) != null) { + throw new RuntimeException(user.getLogin()); + } + User dbUser = (user.getId() == null) + ? user + : getUserById(user.getId()); + //user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); + dbUser.setPassword(passwordEncoder.encode(user.getPassword())); + dbUser.setLogin(user.getLogin()); + dbUser = userRepository.save(dbUser); + log.debug("Created Information for User: {}", dbUser.getLogin()); + return dbUser; + } + + public User getUserById(Integer id) { + return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found by id")); + } + + private void createDefaultUser(String login, String userRole) { + if (getUserByLogin(login) == null) { + UserRole role = userRoleRepository.save(new UserRole(userRole.toString())); + createUser(new User(login, login.equals("admin") ? adminPassword : login, Set.of(role))); + } + } + + public void initDefaultAdmin() { + createDefaultUser("admin", UserRoleConstants.ADMIN); + } + + public User getCurrentUser() { + return getUserByLogin(UserUtils.getCurrentUserLogin()); + } +} diff --git a/src/main/java/ru/ulstu/fc/user/service/UserSessionLoginHandler.java b/src/main/java/ru/ulstu/fc/user/service/UserSessionLoginHandler.java new file mode 100644 index 0000000..b05710d --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/service/UserSessionLoginHandler.java @@ -0,0 +1,44 @@ +package ru.ulstu.fc.user.service; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.stereotype.Component; +import ru.ulstu.fc.config.Constants; + +import java.io.IOException; + +@Component +public class UserSessionLoginHandler extends SavedRequestAwareAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + private final Logger log = LoggerFactory.getLogger(UserSessionLoginHandler.class); + private final UserSessionService userSessionService; + + public UserSessionLoginHandler(UserSessionService userSessionService) { + super(); + this.userSessionService = userSessionService; + } + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, + HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + super.onAuthenticationSuccess(request, response, authentication); + final String login = authentication.getName(); + final String ipAddress = IpAddressResolver.getRemoteAddr(request); + final String host = request.getRemoteHost(); + log.debug("Authentication Success for {}@{} ({})", login, ipAddress, host); + HttpSession session = request.getSession(false); + if (session != null) { + final String sessionId = session.getId(); + userSessionService.createUserSession(sessionId, login, ipAddress, host); + session.setAttribute(Constants.SESSION_ID_ATTR, sessionId); + session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_SECONDS); + } + } +} diff --git a/src/main/java/ru/ulstu/fc/user/service/UserSessionLogoutHandler.java b/src/main/java/ru/ulstu/fc/user/service/UserSessionLogoutHandler.java new file mode 100644 index 0000000..98d50fe --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/service/UserSessionLogoutHandler.java @@ -0,0 +1,48 @@ +package ru.ulstu.fc.user.service; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; +import org.springframework.stereotype.Component; +import ru.ulstu.fc.config.Constants; + +import java.io.IOException; + +@Component +public class UserSessionLogoutHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler { + private final Logger log = LoggerFactory.getLogger(UserSessionLogoutHandler.class); + private final UserSessionService userSessionService; + + public UserSessionLogoutHandler(UserSessionService userSessionService) { + this.userSessionService = userSessionService; + setDefaultTargetUrl(Constants.LOGOUT_URL); + } + + @Override + public void onLogoutSuccess(HttpServletRequest request, + HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + if (authentication == null) { + super.onLogoutSuccess(request, response, authentication); + return; + } + final String login = authentication.getName(); + final String ipAddress = IpAddressResolver.getRemoteAddr(request); + final String host = request.getRemoteHost(); + log.debug("Logout Success for {}@{} ({})", login, ipAddress, host); + HttpSession session = request.getSession(false); + if (session != null) { + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + userSessionService.closeUserSession(sessionId); + session.removeAttribute(Constants.SESSION_ID_ATTR); + session.invalidate(); + } + super.onLogoutSuccess(request, response, authentication); + } +} diff --git a/src/main/java/ru/ulstu/fc/user/service/UserSessionService.java b/src/main/java/ru/ulstu/fc/user/service/UserSessionService.java new file mode 100644 index 0000000..037957c --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/service/UserSessionService.java @@ -0,0 +1,42 @@ +package ru.ulstu.fc.user.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.fc.user.model.User; +import ru.ulstu.fc.user.model.UserNotFoundException; +import ru.ulstu.fc.user.model.UserSession; +import ru.ulstu.fc.user.repository.UserSessionRepository; + +@Service +@Transactional +public class UserSessionService { + private final Logger log = LoggerFactory.getLogger(UserSessionService.class); + private final UserSessionRepository userSessionRepository; + private final UserService userService; + + public UserSessionService(UserSessionRepository userSessionRepository, UserService userService) { + this.userSessionRepository = userSessionRepository; + this.userService = userService; + } + + public void createUserSession(String sessionId, String login, String ipAddress, String host) { + final User user = userService.getUserByLogin(login); + if (user == null) { + throw new UserNotFoundException(login); + } + userSessionRepository.save(new UserSession(sessionId, ipAddress, host, user)); + log.debug("User session {} created for user {}@{} ({})", sessionId, login, ipAddress, host); + } + + public void closeUserSession(String sessionId) { + final UserSession userSession = userSessionRepository.findOneBySessionId(sessionId); + if (userSession == null) { + throw new IllegalArgumentException(String.format("User session %s not found", sessionId)); + } + userSession.close(); + userSessionRepository.save(userSession); + log.debug("User session {} closed", sessionId); + } +} diff --git a/src/main/java/ru/ulstu/fc/user/utils/UserUtils.java b/src/main/java/ru/ulstu/fc/user/utils/UserUtils.java new file mode 100644 index 0000000..fc610b7 --- /dev/null +++ b/src/main/java/ru/ulstu/fc/user/utils/UserUtils.java @@ -0,0 +1,24 @@ +package ru.ulstu.fc.user.utils; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; + +public class UserUtils { + public static String getCurrentUserLogin() { + final SecurityContext securityContext = SecurityContextHolder.getContext(); + if (securityContext == null) { + return null; + } + final Authentication authentication = securityContext.getAuthentication(); + if (authentication.getPrincipal() instanceof UserDetails) { + final UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); + return springSecurityUser.getUsername(); + } + if (authentication.getPrincipal() instanceof String) { + return (String) authentication.getPrincipal(); + } + return null; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index bb03f7e..261c422 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,6 +1,7 @@ spring.main.banner-mode=off server.port=8080 server.jetty.connection-idle-timeout=1000s +admin-password=admin # Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF logging.level.ru.ulstu=DEBUG logging.level.sun.rmi.transport=off diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index f3c03ed..e6a830d 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -21,11 +21,15 @@ diff --git a/src/main/resources/templates/error/403.html b/src/main/resources/templates/error/403.html new file mode 100644 index 0000000..9eb069c --- /dev/null +++ b/src/main/resources/templates/error/403.html @@ -0,0 +1,13 @@ + + + + + +
+
Доступ запрещён
+
Вернуться на главную
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/error/404.html b/src/main/resources/templates/error/404.html new file mode 100644 index 0000000..d599650 --- /dev/null +++ b/src/main/resources/templates/error/404.html @@ -0,0 +1,13 @@ + + + + + +
+
Страница не найдена
+
Вернуться на главную
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/error/500.html b/src/main/resources/templates/error/500.html new file mode 100644 index 0000000..b77a6cf --- /dev/null +++ b/src/main/resources/templates/error/500.html @@ -0,0 +1,13 @@ + + + + + +
+
Ошибка сервера
+
Вернуться на главную
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html new file mode 100644 index 0000000..d84a8aa --- /dev/null +++ b/src/main/resources/templates/login.html @@ -0,0 +1,34 @@ + + + + + + +
+
+
+
+
+
+ +
+
+ +
+ +
+
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/loginError.html b/src/main/resources/templates/loginError.html new file mode 100644 index 0000000..1d08df3 --- /dev/null +++ b/src/main/resources/templates/loginError.html @@ -0,0 +1,40 @@ + + + + + + +
+
+ +
+
+
+
+
+
+ +
+
+ +
+ +
+
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/project/edit.html b/src/main/resources/templates/project/edit.html new file mode 100644 index 0000000..18aefd0 --- /dev/null +++ b/src/main/resources/templates/project/edit.html @@ -0,0 +1,39 @@ + + + + Редактирование проекта + + +
+

Редактирование проекта:

+
+ +
+ + +

+ Не может быть пустым +

+
+
+ +
+ + + Отмена +
+
+ diff --git a/src/main/resources/templates/project/list.html b/src/main/resources/templates/project/list.html new file mode 100644 index 0000000..69e049c --- /dev/null +++ b/src/main/resources/templates/project/list.html @@ -0,0 +1,22 @@ + + + + Список правил + + + +