basic auth

This commit is contained in:
Niktia 2025-02-19 12:52:18 +03:00
parent 2fe6907b94
commit e74c598235
7 changed files with 114 additions and 73 deletions

View File

@ -25,9 +25,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/api/user/register").permitAll()
.antMatchers("/api/user/email/{email}").permitAll()
.antMatchers("/api/user/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")
.antMatchers("/api/login/{login}").permitAll()
.antMatchers("/api/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")
.anyRequest().authenticated()
.and()
.httpBasic()

View File

@ -1,20 +1,26 @@
package com.example.nto.controller;
import com.example.nto.dto.EmployeeDto;
import com.example.nto.dto.EnterDto;
import com.example.nto.dto.RegisterDto;
import com.example.nto.entity.Code;
import com.example.nto.entity.Employee;
import com.example.nto.entity.Enter;
import com.example.nto.exception.NoRequestBodyException;
import com.example.nto.repository.CodeRepository;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.EmployeeService;
import com.example.nto.service.EnterService;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.List;
import java.util.Optional;
@RestController
@ -22,61 +28,40 @@ import java.util.Map;
@RequestMapping("/api")
public class EmployeeController {
private final EmployeeService employeeService;
private final EmployeeRepository employeeRepository;
private final CodeRepository codeRepository;
private final EnterService enterService;
@Getter
public static class UserData {
@JsonProperty("value")
private String value;
@GetMapping("/login/{login}")
public ResponseEntity<String> getByUsername(@PathVariable String login) {
if (login == null) {
throw new NoRequestBodyException("No or wrong request body!");
}
EmployeeDto employeeDto = employeeService.getByLogin(login);
return ResponseEntity.ok(employeeDto.getLogin());
}
@GetMapping("/{login}/auth")
public ResponseEntity<String> authEmployee(@PathVariable String login) {
try {
boolean loginExists = employeeService.checkLogin(login);
if (loginExists) {
return ResponseEntity.ok("данный логин существует");
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("логина не существует или неверный");
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("что-то пошло не так");
@GetMapping("/login")
public ResponseEntity<EmployeeDto> login(Authentication authentication) {
if (authentication == null) {
throw new NoRequestBodyException("No or wrong request body!");
}
return ResponseEntity.ok(employeeService.getByLogin(authentication.getName()));
}
@GetMapping("/{login}/info")
public ResponseEntity<?> infoEmployee(@PathVariable String login) {
try {
Employee user = employeeRepository.getEmployeeByLogin(login);
if (user != null) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("id", user.getId());
response.put("login", user.getLogin());
response.put("name", user.getName());
response.put("photo", user.getPhoto());
response.put("lastVisit", user.getLastVisit());
return ResponseEntity.ok(response);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("логина не существует или неверный");
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("что-то пошло не так");
}
public ResponseEntity<EmployeeDto> infoEmployee(@PathVariable String login) {
EmployeeDto employeeDto = employeeService.getByLogin(login);
return ResponseEntity.ok(employeeDto);
}
@PatchMapping("/{login}/open")
public ResponseEntity<?> openEmployee(@PathVariable String login, @RequestBody UserData userData) {
public ResponseEntity<String> openEmployee(@PathVariable String login, @RequestBody Code code) {
try {
long code = Long.parseLong(userData.getValue());
boolean loginExists = employeeService.checkLogin(login);
EmployeeDto employeeDto = employeeService.getByLogin(login);
if (loginExists) {
boolean codeExists = codeRepository.checkCode(code);
if (employeeDto != null) {
boolean codeExists = codeRepository.checkCode(code.getValue());
if (codeExists) {
return ResponseEntity.ok("дверь открылась");
@ -90,4 +75,10 @@ public class EmployeeController {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("что-то пошло не так");
}
}
@GetMapping("/{login}/enters")
public ResponseEntity<List<EnterDto>> infoEnters(@PathVariable String login) {
List<EnterDto> enters = enterService.getByLogin(login);
return ResponseEntity.ok(enters);
}
}

View File

@ -1,7 +1,11 @@
package com.example.nto.entity;
import com.example.nto.service.impl.UserDetailsServiceImpl;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import javax.persistence.*;
import java.sql.Timestamp;
@ -12,41 +16,55 @@ import java.util.Set;
@Entity
@Table(name = "employee")
public class Employee {
public class Employee implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="login", nullable = false, unique = true)
@Column(name="login")
private String login;
@Column(name="name", nullable = false)
@Column(name="name")
private String name;
@Column(name="password", nullable = false)
@Column(name="password")
private String password;
@Column(name="photo")
private String photo;
@Column(name = "description")
private String description;
@Column(name = "birth_date")
private String birthDate;
@Column(name = "position")
private String position;
@Column(name = "avatar_url")
private String avatarUrl;
@Column(name = "entered_at")
private Timestamp joinedAt;
@Column(name = "created_at", nullable = false)
private Timestamp createdAt;
@Column(name = "last_visit")
@Column(name = "last_enter")
private Timestamp lastVisit;
@OneToMany(fetch = FetchType.EAGER)
private Set<Authority> authorities;
@Override
public String getUsername() {
return login;
}
@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,10 @@
package com.example.nto.repository;
import com.example.nto.entity.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AuthorityRepository extends JpaRepository<Authority, Long> {
Optional<Authority> findByAuthority(String authority);
}

View File

@ -1,8 +1,9 @@
package com.example.nto.service;
import org.springframework.stereotype.Service;
import com.example.nto.dto.EmployeeDto;
import com.example.nto.dto.RegisterDto;
public interface EmployeeService {
boolean checkLogin(String login);
EmployeeDto getByLogin(String login);
}

View File

@ -1,19 +1,40 @@
package com.example.nto.service.impl;
import com.example.nto.dto.EmployeeDto;
import com.example.nto.dto.RegisterDto;
import com.example.nto.entity.Authority;
import com.example.nto.entity.Employee;
import com.example.nto.exception.*;
import com.example.nto.repository.AuthorityRepository;
import com.example.nto.service.EmployeeService;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.utils.EmployeeMapper;
import lombok.RequiredArgsConstructor;
import org.h2.jdbc.JdbcSQLDataException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
private final AuthorityRepository authorityRepository;
private final PasswordEncoder passwordEncoder;
@Override
public boolean checkLogin(String login) {
return employeeRepository.existsByLogin(login);
public EmployeeDto getByLogin(String username) {
Optional<Employee> employee = employeeRepository.findByLogin(username);
if (employee.isEmpty()) {
throw new UserNotFoundException("User with name " + username + " not found!");
}
return EmployeeMapper.convertToDto(employee.get());
}
}

View File

@ -16,9 +16,10 @@ public class UserDetailsServiceImpl implements UserDetailsService {
private final EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Employee optionalPerson = employeeRepository.findByLogin(s);
Optional<Employee> optionalPerson = employeeRepository.findByLogin(s);
if (optionalPerson.isEmpty()) {
throw new UsernameNotFoundException("User not found");
}