demo monolith
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package com.example.demo_monolith.DTOs;
|
||||
|
||||
import com.example.demo_monolith.model.ERole;
|
||||
import com.example.demo_monolith.model.Role;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
public class RoleDto {
|
||||
@JsonIgnore
|
||||
private Long id;
|
||||
private ERole name;
|
||||
|
||||
public RoleDto() {
|
||||
}
|
||||
|
||||
public RoleDto(Long id, ERole name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public ERole getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(ERole name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Mapping helpers
|
||||
public static RoleDto fromEntity(Role role) {
|
||||
if (role == null) return null;
|
||||
return new RoleDto(role.getId(), role.getName());
|
||||
}
|
||||
|
||||
public Role toEntity() {
|
||||
Role role = new Role();
|
||||
role.setId(this.id);
|
||||
role.setName(this.name);
|
||||
return role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.example.demo_monolith.DTOs;
|
||||
|
||||
import com.example.demo_monolith.model.User;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class UserDto {
|
||||
@JsonIgnore
|
||||
private Long id;
|
||||
private String username;
|
||||
private String email;
|
||||
|
||||
private String password; // typically you don't expose password in DTOs
|
||||
|
||||
private Set<RoleDto> roles; // typically you don't expose password in DTOs
|
||||
|
||||
|
||||
public UserDto() {
|
||||
}
|
||||
|
||||
public UserDto(Long id, String username, String email, String password, Set<RoleDto> roles) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Set<RoleDto> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(Set<RoleDto> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
// Mapping helpers
|
||||
public static UserDto fromEntity(User user) {
|
||||
if (user == null) return null;
|
||||
return new UserDto(
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
user.getEmail(),
|
||||
user.getPassword(),
|
||||
user.getRoles() == null ? null :
|
||||
user.getRoles().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(RoleDto::fromEntity)
|
||||
.collect(Collectors.toSet())
|
||||
);
|
||||
}
|
||||
|
||||
public User toEntity() {
|
||||
User user = new User();
|
||||
user.setId(this.id);
|
||||
user.setUsername(this.username);
|
||||
user.setEmail(this.email);
|
||||
user.setPassword(this.password); // Assuming password is already hashed
|
||||
if (this.roles != null) {
|
||||
user.setRoles(this.roles.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(RoleDto::toEntity)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.example.demo_monolith;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoMonolithApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoMonolithApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.example.demo_monolith.controllers;
|
||||
import com.example.demo_monolith.model.ERole;
|
||||
import com.example.demo_monolith.model.Role;
|
||||
import com.example.demo_monolith.model.User;
|
||||
import com.example.demo_monolith.payload.request.LoginRequest;
|
||||
import com.example.demo_monolith.payload.request.SignupRequest;
|
||||
import com.example.demo_monolith.payload.response.MessageResponse;
|
||||
import com.example.demo_monolith.payload.response.UserInfoResponse;
|
||||
import com.example.demo_monolith.repository.RoleRepository;
|
||||
import com.example.demo_monolith.repository.UserRepository;
|
||||
import com.example.demo_monolith.security.jwt.JwtUtils;
|
||||
import com.example.demo_monolith.security.services.UserDetailsImpl;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
//@CrossOrigin(origins = "*", maxAge = 3600)
|
||||
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600, allowCredentials="true")
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
@Autowired
|
||||
AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
RoleRepository roleRepository;
|
||||
|
||||
@Autowired
|
||||
PasswordEncoder encoder;
|
||||
|
||||
@Autowired
|
||||
JwtUtils jwtUtils;
|
||||
|
||||
@PostMapping("/signin")
|
||||
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
|
||||
|
||||
Authentication authentication = authenticationManager
|
||||
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
|
||||
|
||||
ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(userDetails);
|
||||
|
||||
List<String> roles = userDetails.getAuthorities().stream()
|
||||
.map(item -> item.getAuthority())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||
.body(new UserInfoResponse(
|
||||
userDetails.getId(),
|
||||
userDetails.getUsername(),
|
||||
userDetails.getEmail(),
|
||||
roles));
|
||||
}
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
|
||||
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
|
||||
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
|
||||
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email is already in use!"));
|
||||
}
|
||||
|
||||
// Create new user's account
|
||||
User user = new User(signUpRequest.getUsername(),
|
||||
signUpRequest.getEmail(),
|
||||
encoder.encode(signUpRequest.getPassword()));
|
||||
|
||||
Set<String> strRoles = signUpRequest.getRole();
|
||||
Set<Role> roles = new HashSet<>();
|
||||
|
||||
if (strRoles == null) {
|
||||
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
|
||||
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
|
||||
roles.add(userRole);
|
||||
} else {
|
||||
strRoles.forEach(role -> {
|
||||
switch (role) {
|
||||
case "admin":
|
||||
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
|
||||
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
|
||||
roles.add(adminRole);
|
||||
|
||||
break;
|
||||
case "mod":
|
||||
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
|
||||
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
|
||||
roles.add(modRole);
|
||||
|
||||
break;
|
||||
default:
|
||||
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
|
||||
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
|
||||
roles.add(userRole);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
user.setRoles(roles);
|
||||
userRepository.save(user);
|
||||
|
||||
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
|
||||
}
|
||||
|
||||
@PostMapping("/signout")
|
||||
public ResponseEntity<?> logoutUser() {
|
||||
ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
.body(new MessageResponse("You've been signed out!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.demo_monolith.initData;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
//@ConditionalOnProperty(name = "app.init.data.enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class InitDataConfiguration {
|
||||
|
||||
@Autowired
|
||||
private InitDataService _initDataService;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
|
||||
_initDataService.initData();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.example.demo_monolith.initData;
|
||||
|
||||
import com.example.demo_monolith.DTOs.RoleDto;
|
||||
import com.example.demo_monolith.DTOs.UserDto;
|
||||
import com.example.demo_monolith.model.ERole;
|
||||
import com.example.demo_monolith.model.Role;
|
||||
import com.example.demo_monolith.model.User;
|
||||
import com.example.demo_monolith.repository.RoleRepository;
|
||||
import com.example.demo_monolith.repository.UserRepository;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Primary
|
||||
public class InitDataService {
|
||||
|
||||
private static final Logger _logger = LoggerFactory.getLogger(InitDataService.class);
|
||||
|
||||
protected ObjectMapper _mapper;
|
||||
|
||||
@Autowired
|
||||
private ResourceLoader _resources;
|
||||
@Autowired
|
||||
private RoleRepository _roleRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository _userRepository;
|
||||
|
||||
|
||||
private final Path _initDataPath = Path.of("/jambotron_data/initData/");
|
||||
|
||||
public InitDataService(){
|
||||
|
||||
_mapper = new ObjectMapper();
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void extractInitData(){
|
||||
_logger.info("Extracting init data to {}", _initDataPath.toAbsolutePath());
|
||||
if(!_initDataPath.toFile().exists()) {
|
||||
_logger.info("Creating init data directory at {}", _initDataPath.toAbsolutePath());
|
||||
try {
|
||||
Files.createDirectories(_initDataPath);
|
||||
} catch (Exception e) {
|
||||
_logger.error("Failed to create init data directory", e);
|
||||
}
|
||||
}
|
||||
extractJsonFile("roles.json");
|
||||
extractJsonFile("users.json");
|
||||
}
|
||||
|
||||
private void extractJsonFile(String fileName) {
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource("initData/"+ fileName);
|
||||
|
||||
|
||||
Path targetPath = _initDataPath.resolve(fileName);
|
||||
if (!Files.exists(targetPath)) {
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
Files.copy(resource.getInputStream(), targetPath);
|
||||
}
|
||||
|
||||
_logger.info("Copied {} to {}", fileName, targetPath.toAbsolutePath());
|
||||
} else {
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
Files.copy(resource.getInputStream(), targetPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
_logger.warn("{} already exists, REPLACE", targetPath.toAbsolutePath());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
_logger.error("Failed to extract JSON file: {}", fileName, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void importRoles(Path jsonFile) throws Exception {
|
||||
_logger.info("Importing roles from {}", jsonFile.toAbsolutePath());
|
||||
List<RoleDto> items = readList(jsonFile, new TypeReference<List<RoleDto>>() {});
|
||||
for (RoleDto dto : items) {
|
||||
Role roleEntity = dto.toEntity();
|
||||
// If a role with same name exists, reuse its ID to upsert
|
||||
// _roleRepository.findByName(entity.getName())
|
||||
// .ifPresent(existing -> entity.setId(existing.getId()));
|
||||
|
||||
if(!_roleRepository.existsByName(roleEntity.getName())) {
|
||||
_roleRepository.save(roleEntity);
|
||||
_logger.info("Saving new role: {}", roleEntity.getName());
|
||||
} else {
|
||||
_logger.info("Role {} already exists, SKIPPING import", roleEntity.getName());
|
||||
}
|
||||
}
|
||||
_logger.info("Imported {} roles", items.stream()
|
||||
.map(RoleDto::getName).toList()
|
||||
.stream().map(ERole::toString).collect(Collectors.joining(", ")));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void importUsers(Path jsonFile) throws Exception {
|
||||
_logger.info("Importing users from {}", jsonFile.toAbsolutePath());
|
||||
// Preload roles map by name for quick lookup
|
||||
Map<ERole, Role> rolesByName = _roleRepository.findAll().stream()
|
||||
.collect(Collectors.toMap(Role::getName, r -> r));
|
||||
|
||||
List<UserDto> items = readList(jsonFile, new TypeReference<List<UserDto>>() {});
|
||||
for (UserDto dto : items) {
|
||||
if(!_userRepository.existsByUsername(dto.getUsername())) {
|
||||
|
||||
User user = new User();
|
||||
if (dto.getId() != null) user.setId(dto.getId());
|
||||
user.setUsername(dto.getUsername());
|
||||
user.setEmail(dto.getEmail());
|
||||
// Expecting already-hashed values; do not import plain text secrets
|
||||
user.setPassword(dto.getPassword());
|
||||
|
||||
// Resolve roles by enum name
|
||||
Set<Role> roles = new HashSet<>();
|
||||
if (dto.getRoles() != null) {
|
||||
for (RoleDto roleDto : dto.getRoles()) {
|
||||
ERole erole = ERole.valueOf(roleDto.getName().name());
|
||||
Role role = rolesByName.get(erole);
|
||||
if (role == null) {
|
||||
// Optionally create missing roles on the fly
|
||||
role = new Role();
|
||||
role.setName(erole);
|
||||
role = _roleRepository.save(role);
|
||||
rolesByName.put(erole, role);
|
||||
}
|
||||
roles.add(role);
|
||||
}
|
||||
}
|
||||
user.setRoles(roles);
|
||||
|
||||
_userRepository.save(user);
|
||||
|
||||
_logger.info("Imported user: {} with roles: {}", user.getUsername(), user.getRoles().stream()
|
||||
.map(Role::getName).collect(Collectors.toList()).stream().map(ERole::toString)
|
||||
.collect(Collectors.joining(", ")));
|
||||
} else {
|
||||
_logger.warn("User with username {} already exists, SKIPPING import", dto.getUsername());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected <T> List<T> readList(Path file, TypeReference<List<T>> type) throws Exception {
|
||||
String json = Files.readString(file);
|
||||
return _mapper.readValue(json, type);
|
||||
}
|
||||
|
||||
public void initData() {
|
||||
|
||||
extractInitData();
|
||||
|
||||
_logger.info("Initializing data import from {}", _initDataPath.toAbsolutePath());
|
||||
|
||||
try {
|
||||
|
||||
Path rolesFile = _initDataPath.resolve("roles.json");
|
||||
|
||||
if (rolesFile.toFile().exists()) {
|
||||
|
||||
importRoles(rolesFile);
|
||||
} else {
|
||||
|
||||
_logger.warn("Roles import file not found: {}", rolesFile.getFileName());
|
||||
}
|
||||
|
||||
Path usersFile = _initDataPath.resolve("users.json");
|
||||
|
||||
if (usersFile.toFile().exists()) {
|
||||
importUsers(usersFile);
|
||||
} else {
|
||||
|
||||
_logger.warn("Users import file not found: {}", usersFile.getFileName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
_logger.error("Error importing data", e);
|
||||
throw new RuntimeException("Failed to import data", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.example.demo_monolith.model;
|
||||
|
||||
public enum ERole {
|
||||
ROLE_USER,
|
||||
ROLE_MODERATOR,
|
||||
ROLE_ADMIN
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.demo_monolith.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "roles")
|
||||
public class Role {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(length = 20)
|
||||
private ERole name;
|
||||
|
||||
public Role() {
|
||||
|
||||
}
|
||||
|
||||
public Role(ERole name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public ERole getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(ERole name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.demo_monolith.model;
|
||||
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "settings")
|
||||
public class Setting {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(name = "useremaileUniq")
|
||||
private Boolean useremaileUniq;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.example.demo_monolith.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "tutorials")
|
||||
public class Tutorial {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
@Column(name = "description")
|
||||
private String description;
|
||||
|
||||
@Column(name = "published")
|
||||
private boolean published;
|
||||
|
||||
public Tutorial() {
|
||||
|
||||
}
|
||||
|
||||
public Tutorial(String title, String description, boolean published) {
|
||||
this.title = title;
|
||||
this.description = description;
|
||||
this.published = published;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public boolean isPublished() {
|
||||
return published;
|
||||
}
|
||||
|
||||
public void setPublished(boolean isPublished) {
|
||||
this.published = isPublished;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.example.demo_monolith.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
|
||||
@Entity
|
||||
@Table( name = "users",
|
||||
uniqueConstraints = {
|
||||
@UniqueConstraint(columnNames = "username"),
|
||||
@UniqueConstraint(columnNames = "email")
|
||||
})
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(name = "username")
|
||||
@NotBlank
|
||||
@Size(max = 20)
|
||||
private String username;
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 50)
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 120)
|
||||
private String password;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable( name = "user_roles",
|
||||
joinColumns = @JoinColumn(name = "user_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "role_id"))
|
||||
private Set<Role> roles = new HashSet<>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String username, String email, String password) {
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Set<Role> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(Set<Role> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
INSERT INTO roles (id, name) VALUES (1, 'ROLE_USER');
|
||||
INSERT INTO roles (id, name) VALUES (2, 'ROLE_MODERATOR');
|
||||
INSERT INTO roles (id, name) VALUES (3, 'ROLE_ADMIN');
|
||||
|
||||
INSERT INTO users (id, email, password, username)
|
||||
VALUES (1, ''liosha84@gmail.com'', ''$2a$10$qyoKXYSukha6XCjorTzoweF4Os1pwmwyzbaSsb3RCVB0LK6WLQKPC'', ''Admin'');
|
||||
INSERT INTO users (id, email, password, username)
|
||||
VALUES (4, ''Moderator@gmail.com'', ''$2a$10$zLo5th8Xbfq.MM7y/dCRQu3Ud7HHyAwm.7.yS08ytJtkHMKrbOJlu'', ''Moderator'');
|
||||
INSERT INTO users (id, email, password, username)
|
||||
VALUES (5, ''user@gmail.com'', ''$2a$10$2EcwYffteBF3GhVaf5qPB.I7XiHepDEauU5D4fx9fpBXMTZI/QnnC'', ''User'');
|
||||
|
||||
|
||||
INSERT INTO user_roles (user_id, role_id) VALUES (5, 1);
|
||||
INSERT INTO user_roles (user_id, role_id) VALUES (1, 3);
|
||||
INSERT INTO user_roles (user_id, role_id) VALUES (4, 2);
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.demo_monolith.payload.request;
|
||||
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class LoginRequest {
|
||||
@NotBlank
|
||||
private String username;
|
||||
|
||||
@NotBlank
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.example.demo_monolith.payload.request;
|
||||
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
|
||||
public class SignupRequest {
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String username;
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 50)
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
private Set<String> role;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 40)
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Set<String> getRole() {
|
||||
return this.role;
|
||||
}
|
||||
|
||||
public void setRole(Set<String> role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.demo_monolith.payload.response;
|
||||
|
||||
public class MessageResponse {
|
||||
private String message;
|
||||
|
||||
public MessageResponse(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.example.demo_monolith.payload.response;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class UserInfoResponse {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
private String email;
|
||||
private List<String> roles;
|
||||
|
||||
public UserInfoResponse(Long id, String username, String email, List<String> roles) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.example.demo_monolith.repository;
|
||||
|
||||
|
||||
import com.example.demo_monolith.model.ERole;
|
||||
import com.example.demo_monolith.model.Role;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RoleRepository extends JpaRepository<Role, Long> {
|
||||
Optional<Role> findByName(ERole name);
|
||||
boolean existsByName(ERole name);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.demo_monolith.repository;
|
||||
|
||||
|
||||
import com.example.demo_monolith.model.Setting;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface SettingsRepository extends JpaRepository<Setting, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.example.demo_monolith.repository;
|
||||
|
||||
|
||||
import com.example.demo_monolith.model.Tutorial;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface TutorialRepository extends JpaRepository<Tutorial, Long> {
|
||||
List<Tutorial> findByPublished(boolean published);
|
||||
List<Tutorial> findByTitleContaining(String title);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.demo_monolith.repository;
|
||||
|
||||
|
||||
import com.example.demo_monolith.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
Boolean existsByUsername(String username);
|
||||
|
||||
Boolean existsByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.example.demo_monolith.security;
|
||||
|
||||
import com.example.demo_monolith.security.jwt.AuthEntryPointJwt;
|
||||
import com.example.demo_monolith.security.jwt.AuthTokenFilter;
|
||||
import com.example.demo_monolith.security.services.UserDetailsServiceImpl;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
//@EnableWebSecurity
|
||||
//@EnableGlobalMethodSecurity(
|
||||
// securedEnabled = true,
|
||||
// jsr250Enabled = true,
|
||||
//prePostEnabled = true)
|
||||
public class WebSecurityConfig {// extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
UserDetailsServiceImpl userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private AuthEntryPointJwt unauthorizedHandler;
|
||||
|
||||
@Bean
|
||||
public AuthTokenFilter authenticationJwtTokenFilter() {
|
||||
return new AuthTokenFilter();
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
|
||||
// authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public DaoAuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(userDetailsService);
|
||||
|
||||
//authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// @Override
|
||||
// public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
// return super.authenticationManagerBean();
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
|
||||
return authConfig.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// @Override
|
||||
// protected void configure(HttpSecurity http) throws Exception {
|
||||
// http
|
||||
// .csrf()
|
||||
// .disable()
|
||||
// .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
|
||||
// .authorizeRequests()
|
||||
//
|
||||
//
|
||||
// // //Доступ только для пользователей с ролью Администратор
|
||||
// //.antMatchers("/api/users").hasRole("ADMIN")
|
||||
// // .antMatchers("/news").hasRole("USER")
|
||||
// //Доступ разрешен всем пользователей
|
||||
// .antMatchers("/*", "/home", "/resources/**").permitAll()
|
||||
// .antMatchers("/api/auth/**").permitAll()
|
||||
// .antMatchers("/api/tutorials").permitAll()
|
||||
// .antMatchers("/api/tutorials/**").permitAll()
|
||||
// //.antMatchers("/api/test/**").permitAll()
|
||||
// //Все остальные страницы требуют аутентификации
|
||||
// .anyRequest().authenticated()
|
||||
// .and()
|
||||
// .sessionManagement()
|
||||
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
// .and()
|
||||
// .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
//
|
||||
//
|
||||
// //http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf(csrf -> csrf.disable())
|
||||
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth ->
|
||||
auth.requestMatchers("/api/auth/**").permitAll()
|
||||
.requestMatchers("/*", "/home", "/resources/**").permitAll()
|
||||
.requestMatchers("/api/test/**").permitAll()
|
||||
.requestMatchers("/api/tutorials").permitAll()
|
||||
|
||||
.requestMatchers("/api/users").permitAll()
|
||||
.requestMatchers("/api/users/**").permitAll()
|
||||
|
||||
.requestMatchers("/api/roles").permitAll()
|
||||
.requestMatchers("/api/roles/**").permitAll()
|
||||
|
||||
.requestMatchers("/api/tutorials/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
);
|
||||
|
||||
http.authenticationProvider(authenticationProvider());
|
||||
|
||||
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.example.demo_monolith.security.jwt;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@Component
|
||||
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
|
||||
throws IOException, ServletException {
|
||||
logger.error("Unauthorized error: {}", authException.getMessage());
|
||||
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
final Map<String, Object> body = new HashMap<>();
|
||||
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
|
||||
body.put("error", "Unauthorized");
|
||||
body.put("message", authException.getMessage());
|
||||
body.put("path", request.getServletPath());
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writeValue(response.getOutputStream(), body);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.example.demo_monolith.security.jwt;
|
||||
|
||||
|
||||
|
||||
import com.example.demo_monolith.security.services.UserDetailsServiceImpl;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class AuthTokenFilter extends OncePerRequestFilter {
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsServiceImpl userDetailsService;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String jwt = parseJwt(request);
|
||||
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
|
||||
String username = jwtUtils.getUserNameFromJwtToken(jwt);
|
||||
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(userDetails,
|
||||
null,
|
||||
userDetails.getAuthorities());
|
||||
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Cannot set user authentication: {}", e);
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String parseJwt(HttpServletRequest request) {
|
||||
String jwt = jwtUtils.getJwtFromCookies(request);
|
||||
return jwt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.example.demo_monolith.security.jwt;
|
||||
|
||||
|
||||
|
||||
import com.example.demo_monolith.security.services.UserDetailsImpl;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
|
||||
|
||||
@Value("${app.jwtSecret}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Value("${app.jwtExpirationMs}")
|
||||
private int jwtExpirationMs;
|
||||
|
||||
@Value("${app.jwtCookieName}")
|
||||
private String jwtCookie;
|
||||
|
||||
public String getJwtFromCookies(HttpServletRequest request) {
|
||||
Cookie cookie = WebUtils.getCookie(request, jwtCookie);
|
||||
if (cookie != null) {
|
||||
return cookie.getValue();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseCookie generateJwtCookie(UserDetailsImpl userPrincipal) {
|
||||
String jwt = generateTokenFromUsername(userPrincipal.getUsername());
|
||||
ResponseCookie cookie = ResponseCookie.from(jwtCookie, jwt).path("/api").maxAge(24 * 60 * 60).httpOnly(true).build();
|
||||
return cookie;
|
||||
}
|
||||
|
||||
public ResponseCookie getCleanJwtCookie() {
|
||||
ResponseCookie cookie = ResponseCookie.from(jwtCookie, null).path("/api").build();
|
||||
return cookie;
|
||||
}
|
||||
|
||||
public String getUserNameFromJwtToken(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key()).build()
|
||||
.parseClaimsJws(token).getBody().getSubject();
|
||||
}
|
||||
|
||||
private Key key() {
|
||||
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret));//java.util.Base64.getDecoder().decode(jwtSecret.getBytes()));
|
||||
//Decoders.BASE64.decode(jwtSecret));
|
||||
}
|
||||
|
||||
public boolean validateJwtToken(String authToken) {
|
||||
try {
|
||||
Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken);
|
||||
return true;
|
||||
} catch (MalformedJwtException e) {
|
||||
logger.error("Invalid JWT token: {}", e.getMessage());
|
||||
} catch (ExpiredJwtException e) {
|
||||
logger.error("JWT token is expired: {}", e.getMessage());
|
||||
} catch (UnsupportedJwtException e) {
|
||||
logger.error("JWT token is unsupported: {}", e.getMessage());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("JWT claims string is empty: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public String generateTokenFromUsername(String username) {
|
||||
return Jwts.builder()
|
||||
.setSubject(username)
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
|
||||
.signWith(key(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.example.demo_monolith.security.services;
|
||||
|
||||
import com.example.demo_monolith.model.User;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class UserDetailsImpl implements UserDetails {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String email;
|
||||
|
||||
@JsonIgnore
|
||||
private String password;
|
||||
|
||||
private Collection<? extends GrantedAuthority> authorities;
|
||||
|
||||
public UserDetailsImpl(Long id, String username, String email, String password,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public static UserDetailsImpl build(User user) {
|
||||
List<GrantedAuthority> authorities = user.getRoles().stream()
|
||||
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new UserDetailsImpl(
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
user.getEmail(),
|
||||
user.getPassword(),
|
||||
authorities);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
UserDetailsImpl user = (UserDetailsImpl) o;
|
||||
return Objects.equals(id, user.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.demo_monolith.security.services;
|
||||
|
||||
|
||||
import com.example.demo_monolith.model.User;
|
||||
import com.example.demo_monolith.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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 org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
@Service
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
|
||||
|
||||
return UserDetailsImpl.build(user);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
spring:
|
||||
application:
|
||||
name: demo-monolith
|
||||
datasource:
|
||||
url: jdbc:postgresql://localhost:5432/springangulardb
|
||||
username: springangular_user
|
||||
password: postgrespw
|
||||
flyway:
|
||||
url: jdbc:postgresql://localhost:5432/jambotron_dev?options=-c%20timezone=UTC
|
||||
user: springangular_user
|
||||
password: postgrespw
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
lob:
|
||||
non_contextual_creation: true
|
||||
dialect: org.hibernate.dialect.PostgreSQLDialect
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
|
||||
app:
|
||||
jwtSecret: ======================spring=back====================
|
||||
jwtExpirationMs: 30000
|
||||
jwtCookieName: springangularts
|
||||
origin: http://localhost:4200
|
||||
@@ -0,0 +1,81 @@
|
||||
-- This script was generated by the ERD tool in pgAdmin 4.
|
||||
-- Please log an issue at https://github.com/pgadmin-org/pgadmin4/issues/new/choose if you find any bugs, including reproduction steps.
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.refreshtoken
|
||||
(
|
||||
id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
|
||||
user_id bigint NOT NULL,
|
||||
token character varying COLLATE pg_catalog."default" NOT NULL,
|
||||
expiry_date timestamp with time zone,
|
||||
CONSTRAINT refreshtoken_pkey PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.roles
|
||||
(
|
||||
id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
|
||||
name character varying(20) COLLATE pg_catalog."default",
|
||||
CONSTRAINT roles_pkey PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.tutorials
|
||||
(
|
||||
id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
|
||||
published boolean,
|
||||
tobepublished boolean,
|
||||
title character varying(255) COLLATE pg_catalog."default",
|
||||
userid bigint,
|
||||
created timestamp with time zone,
|
||||
modified timestamp with time zone,
|
||||
description character varying(255) COLLATE pg_catalog."default",
|
||||
titleimage text COLLATE pg_catalog."default",
|
||||
body text COLLATE pg_catalog."default",
|
||||
CONSTRAINT tutorials_title_key UNIQUE (title)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.user_roles
|
||||
(
|
||||
user_id bigint NOT NULL,
|
||||
role_id integer NOT NULL,
|
||||
CONSTRAINT user_roles_pkey PRIMARY KEY (user_id, role_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.users
|
||||
(
|
||||
id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
|
||||
email character varying(50) COLLATE pg_catalog."default",
|
||||
password character varying(120) COLLATE pg_catalog."default",
|
||||
username character varying(20) COLLATE pg_catalog."default",
|
||||
CONSTRAINT users_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT uk6dotkott2kjsp8vw4d0m25fb7 UNIQUE (email),
|
||||
CONSTRAINT ukr43af9ap4edm43mmtq01oddj6 UNIQUE (username)
|
||||
);
|
||||
|
||||
ALTER TABLE IF EXISTS public.refreshtoken
|
||||
ADD CONSTRAINT "FK_refreshtoken_users" FOREIGN KEY (user_id)
|
||||
REFERENCES public.users (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public.tutorials
|
||||
ADD CONSTRAINT "tutorial_user_FK" FOREIGN KEY (userid)
|
||||
REFERENCES public.users (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public.user_roles
|
||||
ADD CONSTRAINT fkh8ciramu9cc9q3qcqiv4ue8a6 FOREIGN KEY (role_id)
|
||||
REFERENCES public.roles (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public.user_roles
|
||||
ADD CONSTRAINT fkhfh9dx7w3ubf1co1vdev94g3f FOREIGN KEY (user_id)
|
||||
REFERENCES public.users (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION;
|
||||
|
||||
END;
|
||||
@@ -0,0 +1,10 @@
|
||||
[ {
|
||||
"id" : 1,
|
||||
"name" : "ROLE_USER"
|
||||
}, {
|
||||
"id" : 2,
|
||||
"name" : "ROLE_MODERATOR"
|
||||
}, {
|
||||
"id" : 3,
|
||||
"name" : "ROLE_ADMIN"
|
||||
} ]
|
||||
@@ -0,0 +1,34 @@
|
||||
[ {
|
||||
"id" : 1,
|
||||
"username" : "Admin",
|
||||
"email" : "liosha84@gmail.com",
|
||||
"password" : "$2a$10$qyoKXYSukha6XCjorTzoweF4Os1pwmwyzbaSsb3RCVB0LK6WLQKPC",
|
||||
"roles" : [ {
|
||||
"id" : 1,
|
||||
"name" : "ROLE_USER"
|
||||
}, {
|
||||
"id" : 2,
|
||||
"name" : "ROLE_MODERATOR"
|
||||
}, {
|
||||
"id" : 3,
|
||||
"name" : "ROLE_ADMIN"
|
||||
} ]
|
||||
}, {
|
||||
"id" : 2,
|
||||
"username" : "Moderator",
|
||||
"email" : "Moderator@gmail.com",
|
||||
"password" : "$2a$10$zLo5th8Xbfq.MM7y/dCRQu3Ud7HHyAwm.7.yS08ytJtkHMKrbOJlu",
|
||||
"roles" : [ {
|
||||
"id" : 2,
|
||||
"name" : "ROLE_MODERATOR"
|
||||
} ]
|
||||
}, {
|
||||
"id" : 3,
|
||||
"username" : "User",
|
||||
"email" : "user@gmail.com",
|
||||
"password" : "$2a$10$2EcwYffteBF3GhVaf5qPB.I7XiHepDEauU5D4fx9fpBXMTZI/QnnC",
|
||||
"roles" : [ {
|
||||
"id" : 1,
|
||||
"name" : "ROLE_USER"
|
||||
} ]
|
||||
} ]
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.example.demo_monolith;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class DemoMonolithApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user