19.02.2025 - Spring Security, main functions

This commit is contained in:
IgraMaga 2025-02-19 16:28:20 +03:00
parent 7497c4a93f
commit 400c6744aa
47 changed files with 1106 additions and 32 deletions

35
pom.xml
View File

@ -58,6 +58,41 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.14</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package com.example.nto.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.nto"))
.paths(PathSelectors.any())
.build();
}
}

View File

@ -0,0 +1,62 @@
package com.example.nto.config;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.support.ErrorPageFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.servlet.Filter;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/api/employees/register").permitAll()
.antMatchers("/api/employees/{login}").permitAll()
.antMatchers("/api/employees/paginated").permitAll()
.antMatchers("/api/employees/unoccupied").permitAll()
.antMatchers("/api/authority/").permitAll()
.antMatchers("/api/employees/**").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers("/api/employees/login").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.headers().frameOptions().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public ErrorPageFilter errorPageFilter() {
return new ErrorPageFilter();
}
}

View File

@ -0,0 +1,41 @@
package com.example.nto.controller;
import com.example.nto.entity.Authority;
import com.example.nto.service.AuthorityService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;
@RestController
@RequestMapping("/api/authority")
@RequiredArgsConstructor
public class AuthorityController {
private final AuthorityService authorityService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Authority add(@RequestBody Authority authority) {
return authorityService.add(authority);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<Authority> getAll() {
return authorityService.getAll();
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> idRole(@PathVariable Long id) {
String idn = authorityService.isAdmin(id);
if (Objects.equals(idn, "ROLE_ADMIN")) {
return ResponseEntity.ok("Является администратором");}
else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Не является администратором");
}
}
}

View File

@ -14,6 +14,8 @@ public class CodeController {
@PatchMapping("/api/{login}/open")
public Employee update(@PathVariable String login, @RequestBody Code newCode) {
return codeService.openDoor(login, newCode.getValue());
// return codeService.openDoor(login, newCode.getValue());
return null;
//TODO Service доделать и открыть тут коммент
}
}

View File

@ -0,0 +1,43 @@
package com.example.nto.controller;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.service.CredentialsService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/credentials")
@RequiredArgsConstructor
public class CredentialsController {
private final CredentialsService credentialsService;
@GetMapping
public List<CredentialsDTO> getAllCredentials() {
return credentialsService.getAllCredentials();
}
@GetMapping("/{id}")
public ResponseEntity<CredentialsDTO> getCredentialsById(@PathVariable long id) {
return ResponseEntity.ok(credentialsService.getCredentialsById(id));
}
@PostMapping
public ResponseEntity<CredentialsDTO> createCredentials(@RequestBody CredentialsDTO dto) {
return ResponseEntity.ok(credentialsService.createCredentials(dto));
}
@PutMapping("/{id}")
public ResponseEntity<CredentialsDTO> updateCredentials(@PathVariable long id, @RequestBody CredentialsDTO dto) {
return ResponseEntity.ok(credentialsService.updateCredentials(id, dto));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCredentials(@PathVariable long id) {
credentialsService.deleteCredentials(id);
return ResponseEntity.noContent().build();
}
}

View File

@ -1,25 +1,35 @@
package com.example.nto.controller;
import com.example.nto.dto.EmployeeDTO;
import com.example.nto.dto.UserRegisterDTO;
import com.example.nto.entity.Employee;
import com.example.nto.service.EmployeeService;
import io.swagger.models.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/employees")
@RequiredArgsConstructor
public class EmployeeController {
private final EmployeeService employeeService;
@GetMapping("api/{login}/info")
public Employee findByLogin(@PathVariable String login) {
return employeeService.findByLogin(login);
@GetMapping("/{login}")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> findByLogin(@PathVariable String login) {
if (employeeService.findExistByLogin(login)) {
return ResponseEntity.ok("Done");
} else return ResponseEntity.badRequest().body("User is not found");
}
@GetMapping("api/{login}/auth")
public void findExistByLogin(@PathVariable String login) {
employeeService.findExistByLogin(login);
@GetMapping("/login")
public ResponseEntity<EmployeeDTO> login(Authentication authentication) {
System.out.println("out" + authentication.getAuthorities());
return ResponseEntity.ok(employeeService.getUserByUsername(authentication.getName()));
}
}

View File

@ -0,0 +1,33 @@
package com.example.nto.controller;
import com.example.nto.dto.PassDTO;
import com.example.nto.dto.TerminalDTO;
import com.example.nto.service.PassService;
import com.example.nto.service.TerminalService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/passes")
@RequiredArgsConstructor
public class PassController {
private final PassService passService;
@GetMapping("/paginated/")
public ResponseEntity<List<PassDTO>> getAllPassesAtUser(
@RequestParam long userId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size
) {
Pageable pageable = PageRequest.of(page, size);
return ResponseEntity.ok(passService.getAllPassesPaginated(pageable, userId));
}
}

View File

@ -0,0 +1,24 @@
package com.example.nto.controller;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.dto.TerminalDTO;
import com.example.nto.service.CredentialsService;
import com.example.nto.service.TerminalService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/terminal")
@RequiredArgsConstructor
public class TerminalController {
private final TerminalService terminalService;
@GetMapping("/{id}")
public ResponseEntity<TerminalDTO> getCredentialsById(@PathVariable long id) {
return ResponseEntity.ok(terminalService.getTerminalbyId(id));
}
}

View File

@ -0,0 +1,9 @@
package com.example.nto.dto;
import lombok.Data;
@Data
public class AuthorityDTO {
private long id;
private String authority;
}

View File

@ -0,0 +1,11 @@
package com.example.nto.dto;
import lombok.Data;
@Data
public class CredentialsDTO {
private long id;
private String login;
private String hashedPassword;
}

View File

@ -0,0 +1,19 @@
package com.example.nto.dto;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class EmployeeDTO {
private long id;
private String login;
private String name;
private String password;
private long authority_id;
private long credentials;
private String photo;
private String position;
private LocalDateTime lastVisit;
}

View File

@ -0,0 +1,13 @@
package com.example.nto.dto;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class PassDTO {
private long id;
private long employee;
private LocalDateTime localDateTime;
private long terminal;
}

View File

@ -0,0 +1,12 @@
package com.example.nto.dto;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class TerminalDTO {
private long id;
private String type;
private String name;
}

View File

@ -0,0 +1,11 @@
package com.example.nto.dto;
import lombok.Data;
@Data
public class UserRegisterDTO {
private String login;
private String password;
private String name;
private String lastname;
}

View File

@ -0,0 +1,28 @@
package com.example.nto.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Authority")
public class Authority implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "authority")
private String authority;
@Override
public String getAuthority() {
return "";
}
}

View File

@ -0,0 +1,25 @@
package com.example.nto.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Data
@Entity
@Table(name = "credentials")
public class Credentials {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "login")
private String login;
@Column(name = "hashed_password")
private String hashedPassword;
@OneToMany(mappedBy = "credentials")
@JsonIgnore
private List<Employee> employees;
}

View File

@ -1,12 +1,18 @@
package com.example.nto.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@Data
@Entity
@ -14,7 +20,7 @@ import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Employee")
public class Employee {
public class Employee implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ -22,10 +28,52 @@ public class Employee {
private String login;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@ManyToOne
@JoinColumn(name = "authority_id")
@JsonIgnore
private Authority authority;
@ManyToOne
@JoinColumn(name = "credentials")
@JsonIgnore
private Credentials credentials;
@Column(name = "photo")
private String photo;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Authority> authorities;
@Column(name = "position")
private String position;
@Column(name = "lastVisit")
private LocalDateTime lastVisit;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}
@Override
public String getUsername() {
return "";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@ -0,0 +1,30 @@
package com.example.nto.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Entity
@Table(name = "pass")
public class Pass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "employee")
@JsonIgnore
private Employee employee;
@Column(name = "time")
private LocalDateTime time;
@ManyToOne
@JoinColumn(name="terminal")
@JsonIgnore
private Terminal terminal;
}

View File

@ -0,0 +1,22 @@
package com.example.nto.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "terminal")
public class Terminal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "type")
private String type;
@Column(name="name")
private String name;
}

View File

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class PersonAlreadyExistsException extends RuntimeException {
public PersonAlreadyExistsException(String message) {
super(message);
}
}

View File

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class PersonNotFoundException extends RuntimeException {
public PersonNotFoundException(String message) {
super(message);
}
}

View File

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class RoleisNotAdmin extends RuntimeException {
public RoleisNotAdmin(String message) {
super(message);
}
}

View File

@ -0,0 +1,26 @@
package com.example.nto.exception.handler;
import com.example.nto.exception.PersonAlreadyExistsException;
import com.example.nto.exception.PersonNotFoundException;
import com.example.nto.exception.RoleisNotAdmin;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RoleisNotAdmin.class)
public ResponseEntity<String> handleRoleisNotAdmin(RoleisNotAdmin e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(PersonNotFoundException.class)
public ResponseEntity<String> handlePersonNotFound(PersonNotFoundException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(PersonAlreadyExistsException.class)
public ResponseEntity<String> handlePersonAlreadyExists(PersonAlreadyExistsException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_GATEWAY);
}
}

View File

@ -0,0 +1,13 @@
package com.example.nto.repository;
import com.example.nto.dto.AuthorityDTO;
import com.example.nto.entity.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AuthorityRepository extends JpaRepository<Authority, Long> {
Optional<Authority> findByAuthority(String Authority);
}

View File

@ -0,0 +1,12 @@
package com.example.nto.repository;
import com.example.nto.entity.Credentials;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface CredentialsRepository extends JpaRepository<Credentials, Long> {
Optional<Credentials> findByLogin(String login);
}

View File

@ -5,12 +5,16 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@Query("select e from Employee e where e.login = ?1")
Employee findByLogin(String login);
Optional<Employee> findByLogin(String login);
@Query("select e from Employee e where e.id = ?1")
Employee findById(long id);
@Query("select count(e) = 1 from Employee e where login = ?1")
Boolean findExistByLogin(String login);
}

View File

@ -0,0 +1,13 @@
package com.example.nto.repository;
import com.example.nto.entity.Pass;
import com.example.nto.entity.Terminal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface PassRepository extends JpaRepository<Pass, Long> {
Optional<Pass> findById(long id);
}

View File

@ -0,0 +1,12 @@
package com.example.nto.repository;
import com.example.nto.entity.Terminal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface TerminalRepository extends JpaRepository<Terminal, Long> {
Optional<Terminal> findByName(String name);
}

View File

@ -0,0 +1,14 @@
package com.example.nto.service;
import com.example.nto.entity.Authority;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface AuthorityService {
Authority add(Authority authority);
List<Authority> getAll();
String isAdmin(Long id);
}

View File

@ -3,8 +3,10 @@ package com.example.nto.service;
import com.example.nto.entity.Employee;
import java.util.Optional;
public interface CodeService {
Boolean findExistByValue(Long value);
Employee openDoor(String login, Long value);
Optional<Employee> openDoor(String login, Long value);
}

View File

@ -0,0 +1,16 @@
package com.example.nto.service;
import com.example.nto.dto.CredentialsDTO;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface CredentialsService {
List<CredentialsDTO> getAllCredentials();
CredentialsDTO getCredentialsById(Long id);
CredentialsDTO createCredentials(CredentialsDTO dto);
CredentialsDTO updateCredentials(Long id, CredentialsDTO dto);
void deleteCredentials(Long id);
}

View File

@ -1,10 +1,23 @@
package com.example.nto.service;
import com.example.nto.dto.EmployeeDTO;
import com.example.nto.dto.UserRegisterDTO;
import com.example.nto.entity.Employee;
import java.util.Optional;
public interface EmployeeService {
Employee updateEmployee(long id, Employee newEmployee);
Employee findByLogin(String login);
Optional<Employee> findByLogin(String login);
EmployeeDTO findById(Long id);
boolean findExistByLogin(String login);
EmployeeDTO createUser(UserRegisterDTO dto);
EmployeeDTO getUserByUsername(String login);
EmployeeDTO get(String name);
}

View File

@ -0,0 +1,18 @@
package com.example.nto.service;
import com.example.nto.dto.PassDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface PassService {
List<PassDTO> getPassAtUser(long id);
List<PassDTO> getAllPassesPaginated(Pageable pageable, long id);
}

View File

@ -0,0 +1,13 @@
package com.example.nto.service;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.dto.TerminalDTO;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface TerminalService {
TerminalDTO getTerminalbyId(Long id);
}

View File

@ -0,0 +1,36 @@
package com.example.nto.service.impl;
import com.example.nto.entity.Authority;
import com.example.nto.repository.AuthorityRepository;
import com.example.nto.service.AuthorityService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class AuthorityServiceImpl implements AuthorityService {
private final AuthorityRepository authorityRepository;
@Override
public Authority add(Authority authority) {
Optional<Authority> optionalAuthority = authorityRepository.findByAuthority(authority.getAuthority());
return optionalAuthority.orElseGet(() -> authorityRepository.save(authority));
}
@Override
public List<Authority> getAll() {
return authorityRepository.findAll();
}
@Override
public String isAdmin(Long id) {
Optional<Authority> optionalAuthority = authorityRepository.findById(id);
Authority existingsAuthority = optionalAuthority.get();
return existingsAuthority.getAuthority();
}
}

View File

@ -0,0 +1,67 @@
package com.example.nto.service.impl;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.entity.Credentials;
import com.example.nto.repository.CredentialsRepository;
import com.example.nto.service.CredentialsService;
import com.example.nto.utils.CredentialsMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class CredentialsServiceImpl implements CredentialsService {
private final CredentialsRepository credentialsRepository;
@Override
public List<CredentialsDTO> getAllCredentials() {
return credentialsRepository.findAll().stream()
.map(CredentialsMapper::convertDTO)
.collect(Collectors.toList());
}
@Override
public CredentialsDTO getCredentialsById(Long id) {
Optional<Credentials> credentials = credentialsRepository.findById(id);
return credentials.map(CredentialsMapper::convertDTO).orElse(null);
}
@Override
public CredentialsDTO createCredentials(CredentialsDTO dto) {
Credentials credentials = new Credentials();
credentials.setLogin(dto.getLogin());
credentials.setHashedPassword(dto.getHashedPassword());
Credentials savedCredentials = credentialsRepository.save(credentials);
CredentialsDTO responseDto = new CredentialsDTO();
responseDto.setLogin(savedCredentials.getLogin());
responseDto.setHashedPassword(savedCredentials.getHashedPassword());
return responseDto;
}
@Override
public CredentialsDTO updateCredentials(Long id, CredentialsDTO dto) {
Optional<Credentials> existingCredentialsOptional = credentialsRepository.findById(id);
if (existingCredentialsOptional.isPresent()) {
Credentials existingCredentials = existingCredentialsOptional.get();
existingCredentials.setLogin(dto.getLogin());
existingCredentials.setHashedPassword(dto.getHashedPassword());
Credentials updatedCredentials = credentialsRepository.save(existingCredentials);
return CredentialsMapper.convertDTO(updatedCredentials);
}
return null;
}
@Override
public void deleteCredentials(Long id) {
credentialsRepository.deleteById(id);
}
}

View File

@ -1,17 +1,28 @@
package com.example.nto.service.impl;
import com.example.nto.dto.EmployeeDTO;
import com.example.nto.dto.UserRegisterDTO;
import com.example.nto.entity.Authority;
import com.example.nto.entity.Credentials;
import com.example.nto.entity.Employee;
import com.example.nto.exception.PersonAlreadyExistsException;
import com.example.nto.exception.PersonNotFoundException;
import com.example.nto.repository.AuthorityRepository;
import com.example.nto.repository.CodeRepository;
import com.example.nto.repository.CredentialsRepository;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.CodeService;
import com.example.nto.service.EmployeeService;
import com.example.nto.utils.EmployeeMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.Set;
@Service
@RequiredArgsConstructor
@ -19,15 +30,18 @@ public class EmployeeCodeServiceImpl implements EmployeeService, CodeService {
private final EmployeeRepository employeeRepository;
private final CodeRepository codeRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
private final CredentialsRepository credentialsRepository;
@Override
public Employee updateEmployee(long id, Employee newEmployee) {
Optional<Employee> optionalEmployee = employeeRepository.findById(id);
Optional<Employee> optionalEmployee = Optional.ofNullable(employeeRepository.findById(id));
if (optionalEmployee.isEmpty()) throw new RuntimeException("No such user with id " + id);
Employee employee = optionalEmployee.get();
employee.setName(newEmployee.getName());
employee.setLogin(newEmployee.getLogin());
employee.setLogin(newEmployee.getUsername());
employee.setPhoto(newEmployee.getPhoto());
employee.setPosition(newEmployee.getPosition());
employee.setLastVisit(newEmployee.getLastVisit());
@ -36,13 +50,22 @@ public class EmployeeCodeServiceImpl implements EmployeeService, CodeService {
}
@Override
public Employee findByLogin(String login) {
public Optional<Employee> findByLogin(String login) {
if (employeeRepository.findExistByLogin(login))
return employeeRepository.findByLogin(login);
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,
"There is no account with login " + login + " or it is incorrect");
}
@Override
public EmployeeDTO findById(Long id) {
return employeeRepository.findById(id)
.map(EmployeeMapper::convertDTO)
.orElseThrow(() -> new PersonNotFoundException("Person not found!"));
}
@Override
public boolean findExistByLogin(String login) {
if (employeeRepository.findExistByLogin(login))
@ -52,15 +75,20 @@ public class EmployeeCodeServiceImpl implements EmployeeService, CodeService {
}
@Override
public Employee openDoor(String login, Long value) {
if (findByLogin(login) != null && findExistByValue(value)) {
Employee employee = findByLogin(login);
employee.setLastVisit(LocalDateTime.now());
return updateEmployee(employee.getId(), employee);
}
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
@Override
public Optional<Employee> openDoor(String login, Long value) {
// if (findByLogin(login) != null && findExistByValue(value)) {
// Optional<Employee> employee = findByLogin(login);
// employee.ifPresent(employee1 -> employee1.setLastVisit(LocalDateTime.now()));
// employee.setLastVisit(LocalDateTime.now());
//
// return updateEmployee(employee.getId(), employee);
// }
//
// throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
return null;
// TODO Доделать элемент с OpenDoor
}
@Override
@ -69,4 +97,44 @@ public class EmployeeCodeServiceImpl implements EmployeeService, CodeService {
return codeRepository.findExistByValue(value);
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
@Override
public EmployeeDTO createUser(UserRegisterDTO dto) {
Optional<Authority> roleUser = authorityRepository.findByAuthority("ROlE_USER");
System.out.println(roleUser);
if (roleUser.isEmpty()) throw new RuntimeException("Roles not found");
Credentials credentials = new Credentials();
credentials.setLogin(dto.getLogin());
credentials.setHashedPassword(passwordEncoder.encode(dto.getPassword()));
Credentials credentialSave = credentialsRepository.save(credentials);
Employee employee = new Employee();
employee.setLogin(dto.getLogin());
employee.setName(dto.getName());
employee.setPassword(passwordEncoder.encode(dto.getPassword()));
employee.setAuthorities(Set.of(roleUser.get()));
employee.setCredentials(credentials);
employee.setAuthority(roleUser.get());
Employee savedUser = employeeRepository.save(employee);
return EmployeeMapper.convertDTO(savedUser);
}
@Override
public EmployeeDTO getUserByUsername(String login) {
System.out.println(login);
Optional<Employee> optionalUsers = employeeRepository.findByLogin(login);
System.out.println(optionalUsers);
if (optionalUsers.isEmpty()) {
throw new PersonNotFoundException("User with username " + login + "not found");
}
return EmployeeMapper.convertDTO(optionalUsers.get());
}
@Override
public EmployeeDTO get(String name) {
return null;
}
}

View File

@ -0,0 +1,35 @@
package com.example.nto.service.impl;
import com.example.nto.dto.PassDTO;
import com.example.nto.repository.PassRepository;
import com.example.nto.service.PassService;
import com.example.nto.utils.PassMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PassServiceImpl implements PassService {
private final PassRepository passRepository;
@Override
public List<PassDTO> getPassAtUser(long id) {
return passRepository.findAll().stream()
.filter(pass -> pass.getEmployee().toString().equals(id))
.map(PassMapper::convertDTO)
.collect(Collectors.toList());
}
@Override
public List<PassDTO> getAllPassesPaginated(Pageable pageable, long id) {
return passRepository.findAll(pageable)
.filter(pass -> pass.getEmployee().toString().equals(id))
.map(PassMapper::convertDTO).toList();
}
}

View File

@ -0,0 +1,32 @@
package com.example.nto.service.impl;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.dto.TerminalDTO;
import com.example.nto.entity.Credentials;
import com.example.nto.entity.Terminal;
import com.example.nto.repository.CredentialsRepository;
import com.example.nto.repository.TerminalRepository;
import com.example.nto.service.CredentialsService;
import com.example.nto.service.TerminalService;
import com.example.nto.utils.CredentialsMapper;
import com.example.nto.utils.TerminalMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class TerminalServiceimpl implements TerminalService {
private final TerminalRepository terminalRepository;
@Override
public TerminalDTO getTerminalbyId(Long id) {
Optional<Terminal> terminal = terminalRepository.findById(id);
return terminal.map(TerminalMapper::convertDTO).orElse(null);
}
}

View File

@ -0,0 +1,27 @@
package com.example.nto.service.impl;
import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final EmployeeRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<Employee> optionalUsers = usersRepository.findByLogin(s);
if(optionalUsers.isEmpty()) {
throw new UsernameNotFoundException("User not found");
}
return optionalUsers.get();
}
}

View File

@ -0,0 +1,14 @@
package com.example.nto.utils;
import com.example.nto.entity.Authority;
import com.example.nto.dto.AuthorityDTO;
import lombok.experimental.UtilityClass;
@UtilityClass
public class AuthorityMapper {
public static AuthorityDTO convertDTO(Authority role) {
AuthorityDTO authorityDTO = new AuthorityDTO();
authorityDTO.setId(role.getId());
authorityDTO.setAuthority(role.getAuthority());
return authorityDTO;
}
}

View File

@ -0,0 +1,18 @@
package com.example.nto.utils;
import com.example.nto.dto.AuthorityDTO;
import com.example.nto.dto.CredentialsDTO;
import com.example.nto.entity.Authority;
import com.example.nto.entity.Credentials;
import lombok.experimental.UtilityClass;
@UtilityClass
public class CredentialsMapper {
public static CredentialsDTO convertDTO(Credentials credentials) {
CredentialsDTO credentialsDTO = new CredentialsDTO();
credentialsDTO.setId(credentials.getId());
credentialsDTO.setLogin(credentials.getLogin());
credentialsDTO.setHashedPassword(credentials.getHashedPassword());
return credentialsDTO;
}
}

View File

@ -0,0 +1,28 @@
package com.example.nto.utils;
import com.example.nto.dto.EmployeeDTO;
import com.example.nto.entity.Employee;
import lombok.experimental.UtilityClass;
@UtilityClass
public class EmployeeMapper {
public static EmployeeDTO convertDTO(Employee user) {
EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setId(user.getId());
employeeDTO.setLogin(user.getLogin());
employeeDTO.setName(user.getName());
if (user.getAuthority() != null) {
employeeDTO.setAuthority_id(user.getAuthority().getId());
}
if (user.getCredentials() != null) {
employeeDTO.setCredentials(user.getCredentials().getId());
}
employeeDTO.setPassword(user.getPassword());
employeeDTO.setPhoto(user.getPhoto());
employeeDTO.setPosition(user.getPosition());
employeeDTO.setLastVisit(user.getLastVisit());
return employeeDTO;
}
}

View File

@ -0,0 +1,25 @@
package com.example.nto.utils;
import com.example.nto.dto.PassDTO;
import com.example.nto.entity.Pass;
import lombok.experimental.UtilityClass;
@UtilityClass
public class PassMapper {
public static PassDTO convertDTO(Pass pass) {
PassDTO passDTO = new PassDTO();
passDTO.setId(pass.getId());
if (pass.getEmployee() != null) {
passDTO.setEmployee(pass.getEmployee().getId());
}
passDTO.setLocalDateTime(pass.getTime());
if (pass.getTerminal() != null) {
passDTO.setTerminal(pass.getTerminal().getId());
}
return passDTO;
}
}

View File

@ -0,0 +1,21 @@
package com.example.nto.utils;
import com.example.nto.dto.TerminalDTO;
import com.example.nto.entity.Terminal;
import lombok.experimental.UtilityClass;
@UtilityClass
public class TerminalMapper {
public static TerminalDTO convertDTO(Terminal terminal) {
TerminalDTO terminalDTO = new TerminalDTO();
terminalDTO.setId(terminal.getId());
terminalDTO.setType(terminal.getType());
terminalDTO.setName(terminal.getName());
return terminalDTO;
}
}

View File

@ -1,9 +1,15 @@
INSERT INTO employee (id, login, name, photo, position, last_visit)
INSERT into credentials (username, hashed_password)
VALUES
(1, 'pivanov', 'Иванов Петр Федорович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-12T08:30'),
(2, 'ipetrov', 'Петров Иван Константинович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Аналитик', '2024-02-13T08:35'),
(3, 'asemenov', 'Семенов Анатолий Анатольевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-13T08:31'),
(4, 'afedorov', 'Федоров Александр Сергеевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Тестировщик', '2024-02-12T08:36');
('pivanov','$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e'),
('ipetrov','$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e'),
('asemenov','$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e'),
('afedorov','$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e');
INSERT INTO employee (username, credentials, name, password, photo, position, last_visit)
VALUES
('pivanov', 1, 'Иванов Петр Федорович', '$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-12T08:30'),
('ipetrov', 2, 'Петров Иван Константинович', '$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Аналитик', '2024-02-13T08:35'),
('asemenov', 3, 'Семенов Анатолий Анатольевич', '$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-13T08:31'),
('afedorov', 4, 'Федоров Александр Сергеевич', '$2a$10$mq/UrB0MPG6.Fw2h.4gRauGYa7Zy37dveEU3U1mn22oHxCK7km24e', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Тестировщик', '2024-02-12T08:36');
INSERT INTO code (value)
VALUES
@ -11,4 +17,25 @@ VALUES
(9223372036854775807),
(1122334455667788990),
(998877665544332211),
(5566778899001122334);
(5566778899001122334);
INSERT into authority (authority)
VALUES
('ROlE_USER'),
('ROLE_ADMIN');
UPDATE employee SET authority_id = (1);
INSERT into terminal (type, name)
VALUES
('qr', 'name1'),
('nfc', 'name2');
INSERT into pass (employee, time)
VALUES
('1', '2023-05-29T10:15:30'),
('2', '2021-05-29T10:15:30'),
('3', '2022-05-29T10:15:30'),
('4', '2025-05-29T10:15:30');
UPDATE pass SET terminal = (1);