Generate JHipster 9.3.0 baseline application
This commit is contained in:
1 parent
0a9b7b923f
commit
1d97cc4e31
345 files changed
+25563
No files matched your search
@@ -0,0 +1,13 @@
|
||||
package com.example.questionbank.service;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
public class EmailAlreadyUsedException extends RuntimeException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public EmailAlreadyUsedException() {
|
||||
super("Email is already in use!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.example.questionbank.service;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
public class InvalidPasswordException extends RuntimeException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public InvalidPasswordException() {
|
||||
super("Incorrect password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.example.questionbank.service;
|
||||
|
||||
import com.example.questionbank.domain.User;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import tech.jhipster.config.JHipsterProperties;
|
||||
|
||||
/**
|
||||
* Service for sending emails asynchronously.
|
||||
* <p>
|
||||
* We use the {@link Async} annotation to send emails asynchronously.
|
||||
*/
|
||||
@Service
|
||||
public class MailService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MailService.class);
|
||||
|
||||
private static final String USER = "user";
|
||||
|
||||
private static final String BASE_URL = "baseUrl";
|
||||
|
||||
private final JHipsterProperties jHipsterProperties;
|
||||
|
||||
private final JavaMailSender javaMailSender;
|
||||
|
||||
private final MessageSource messageSource;
|
||||
|
||||
private final SpringTemplateEngine templateEngine;
|
||||
|
||||
public MailService(
|
||||
JHipsterProperties jHipsterProperties,
|
||||
JavaMailSender javaMailSender,
|
||||
MessageSource messageSource,
|
||||
SpringTemplateEngine templateEngine
|
||||
) {
|
||||
this.jHipsterProperties = jHipsterProperties;
|
||||
this.javaMailSender = javaMailSender;
|
||||
this.messageSource = messageSource;
|
||||
this.templateEngine = templateEngine;
|
||||
}
|
||||
|
||||
@Async
|
||||
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
|
||||
sendEmailSync(to, subject, content, isMultipart, isHtml);
|
||||
}
|
||||
|
||||
private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
|
||||
LOG.debug(
|
||||
"Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
|
||||
isMultipart,
|
||||
isHtml,
|
||||
to,
|
||||
subject,
|
||||
content
|
||||
);
|
||||
|
||||
// Prepare message using a Spring helper
|
||||
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
|
||||
try {
|
||||
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
|
||||
message.setTo(to);
|
||||
message.setFrom(jHipsterProperties.getMail().getFrom());
|
||||
message.setSubject(subject);
|
||||
message.setText(content, isHtml);
|
||||
javaMailSender.send(mimeMessage);
|
||||
LOG.debug("Sent email to User '{}'", to);
|
||||
} catch (MailException | MessagingException e) {
|
||||
LOG.warn("Email could not be sent to user '{}'", to, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Async
|
||||
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
|
||||
sendEmailFromTemplateSync(user, templateName, titleKey);
|
||||
}
|
||||
|
||||
private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) {
|
||||
if (user.getEmail() == null) {
|
||||
LOG.debug("Email doesn't exist for user '{}'", user.getLogin());
|
||||
return;
|
||||
}
|
||||
Locale locale = Locale.forLanguageTag(user.getLangKey());
|
||||
Context context = new Context(locale);
|
||||
context.setVariable(USER, user);
|
||||
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
|
||||
String content = templateEngine.process(templateName, context);
|
||||
String subject = messageSource.getMessage(titleKey, null, locale);
|
||||
sendEmailSync(user.getEmail(), subject, content, false, true);
|
||||
}
|
||||
|
||||
@Async
|
||||
public void sendActivationEmail(User user) {
|
||||
LOG.debug("Sending activation email to '{}'", user.getEmail());
|
||||
sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title");
|
||||
}
|
||||
|
||||
@Async
|
||||
public void sendCreationEmail(User user) {
|
||||
LOG.debug("Sending creation email to '{}'", user.getEmail());
|
||||
sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title");
|
||||
}
|
||||
|
||||
@Async
|
||||
public void sendPasswordResetMail(User user) {
|
||||
LOG.debug("Sending password reset email to '{}'", user.getEmail());
|
||||
sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package com.example.questionbank.service;
|
||||
|
||||
import com.example.questionbank.config.Constants;
|
||||
import com.example.questionbank.domain.Authority;
|
||||
import com.example.questionbank.domain.User;
|
||||
import com.example.questionbank.repository.AuthorityRepository;
|
||||
import com.example.questionbank.repository.UserRepository;
|
||||
import com.example.questionbank.security.AuthoritiesConstants;
|
||||
import com.example.questionbank.security.SecurityUtils;
|
||||
import com.example.questionbank.service.dto.AdminUserDTO;
|
||||
import com.example.questionbank.service.dto.UserDTO;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.jhipster.security.RandomUtil;
|
||||
|
||||
/**
|
||||
* Service class for managing users.
|
||||
*/
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final AuthorityRepository authorityRepository;
|
||||
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authorityRepository = authorityRepository;
|
||||
}
|
||||
|
||||
public Optional<User> activateRegistration(String key) {
|
||||
LOG.debug("Activating user for activation key {}", key);
|
||||
return userRepository.findOneByActivationKey(key).map(user -> {
|
||||
// activate given user for the registration key.
|
||||
user.setActivated(true);
|
||||
user.setActivationKey(null);
|
||||
LOG.debug("Activated user: {}", user);
|
||||
return user;
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<User> completePasswordReset(String newPassword, String key) {
|
||||
LOG.debug("Reset user password for reset key {}", key);
|
||||
return userRepository
|
||||
.findOneByResetKey(key)
|
||||
.filter(user -> user.getResetDate().isAfter(Instant.now().minus(1, ChronoUnit.DAYS)))
|
||||
.map(user -> {
|
||||
user.setPassword(passwordEncoder.encode(newPassword));
|
||||
user.setResetKey(null);
|
||||
user.setResetDate(null);
|
||||
return user;
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<User> requestPasswordReset(String mail) {
|
||||
return userRepository
|
||||
.findOneByEmailIgnoreCase(mail)
|
||||
.filter(User::isActivated)
|
||||
.map(user -> {
|
||||
user.setResetKey(RandomUtil.generateResetKey());
|
||||
user.setResetDate(Instant.now());
|
||||
return user;
|
||||
});
|
||||
}
|
||||
|
||||
public User registerUser(AdminUserDTO userDTO, String password) {
|
||||
userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> {
|
||||
boolean removed = removeNonActivatedUser(existingUser);
|
||||
if (!removed) {
|
||||
throw new UsernameAlreadyUsedException();
|
||||
}
|
||||
});
|
||||
userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> {
|
||||
boolean removed = removeNonActivatedUser(existingUser);
|
||||
if (!removed) {
|
||||
throw new EmailAlreadyUsedException();
|
||||
}
|
||||
});
|
||||
User newUser = new User();
|
||||
String encryptedPassword = passwordEncoder.encode(password);
|
||||
newUser.setLogin(userDTO.getLogin().toLowerCase());
|
||||
// new user gets initially a generated password
|
||||
newUser.setPassword(encryptedPassword);
|
||||
newUser.setFirstName(userDTO.getFirstName());
|
||||
newUser.setLastName(userDTO.getLastName());
|
||||
if (userDTO.getEmail() != null) {
|
||||
newUser.setEmail(userDTO.getEmail().toLowerCase());
|
||||
}
|
||||
newUser.setImageUrl(userDTO.getImageUrl());
|
||||
newUser.setLangKey(userDTO.getLangKey());
|
||||
// new user is not active
|
||||
newUser.setActivated(false);
|
||||
// new user gets registration key
|
||||
newUser.setActivationKey(RandomUtil.generateActivationKey());
|
||||
Set<Authority> authorities = new HashSet<>();
|
||||
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
|
||||
newUser.setAuthorities(authorities);
|
||||
userRepository.save(newUser);
|
||||
LOG.debug("Created Information for User: {}", newUser);
|
||||
return newUser;
|
||||
}
|
||||
|
||||
private boolean removeNonActivatedUser(User existingUser) {
|
||||
if (existingUser.isActivated()) {
|
||||
return false;
|
||||
}
|
||||
userRepository.delete(existingUser);
|
||||
userRepository.flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
public User createUser(AdminUserDTO userDTO) {
|
||||
User user = new User();
|
||||
user.setLogin(userDTO.getLogin().toLowerCase());
|
||||
user.setFirstName(userDTO.getFirstName());
|
||||
user.setLastName(userDTO.getLastName());
|
||||
if (userDTO.getEmail() != null) {
|
||||
user.setEmail(userDTO.getEmail().toLowerCase());
|
||||
}
|
||||
user.setImageUrl(userDTO.getImageUrl());
|
||||
if (userDTO.getLangKey() == null) {
|
||||
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
|
||||
} else {
|
||||
user.setLangKey(userDTO.getLangKey());
|
||||
}
|
||||
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
|
||||
user.setPassword(encryptedPassword);
|
||||
user.setResetKey(RandomUtil.generateResetKey());
|
||||
user.setResetDate(Instant.now());
|
||||
user.setActivated(true);
|
||||
if (userDTO.getAuthorities() != null) {
|
||||
Set<Authority> authorities = userDTO
|
||||
.getAuthorities()
|
||||
.stream()
|
||||
.map(authorityRepository::findById)
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.collect(Collectors.toSet());
|
||||
user.setAuthorities(authorities);
|
||||
}
|
||||
userRepository.save(user);
|
||||
LOG.debug("Created Information for User: {}", user);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update all information for a specific user, and return the modified user.
|
||||
*
|
||||
* @param userDTO user to update.
|
||||
* @return updated user.
|
||||
*/
|
||||
public Optional<AdminUserDTO> updateUser(AdminUserDTO userDTO) {
|
||||
return Optional.of(userRepository.findById(userDTO.getId()))
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.map(user -> {
|
||||
user.setLogin(userDTO.getLogin().toLowerCase());
|
||||
user.setFirstName(userDTO.getFirstName());
|
||||
user.setLastName(userDTO.getLastName());
|
||||
if (userDTO.getEmail() != null) {
|
||||
user.setEmail(userDTO.getEmail().toLowerCase());
|
||||
}
|
||||
user.setImageUrl(userDTO.getImageUrl());
|
||||
user.setActivated(userDTO.isActivated());
|
||||
user.setLangKey(userDTO.getLangKey());
|
||||
Set<Authority> managedAuthorities = user.getAuthorities();
|
||||
managedAuthorities.clear();
|
||||
userDTO
|
||||
.getAuthorities()
|
||||
.stream()
|
||||
.map(authorityRepository::findById)
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.forEach(managedAuthorities::add);
|
||||
userRepository.save(user);
|
||||
LOG.debug("Changed Information for User: {}", user);
|
||||
return user;
|
||||
})
|
||||
.map(AdminUserDTO::new);
|
||||
}
|
||||
|
||||
public void deleteUser(String login) {
|
||||
userRepository.findOneByLogin(login).ifPresent(user -> {
|
||||
userRepository.delete(user);
|
||||
LOG.debug("Deleted User: {}", user);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update basic information (first name, last name, email, language) for the current user.
|
||||
*
|
||||
* @param firstName first name of user.
|
||||
* @param lastName last name of user.
|
||||
* @param email email id of user.
|
||||
* @param langKey language key.
|
||||
* @param imageUrl image URL of user.
|
||||
*/
|
||||
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
|
||||
SecurityUtils.getCurrentUserLogin()
|
||||
.flatMap(userRepository::findOneByLogin)
|
||||
.ifPresent(user -> {
|
||||
user.setFirstName(firstName);
|
||||
user.setLastName(lastName);
|
||||
if (email != null) {
|
||||
user.setEmail(email.toLowerCase());
|
||||
}
|
||||
user.setLangKey(langKey);
|
||||
user.setImageUrl(imageUrl);
|
||||
userRepository.save(user);
|
||||
LOG.debug("Changed Information for User: {}", user);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void changePassword(String currentClearTextPassword, String newPassword) {
|
||||
SecurityUtils.getCurrentUserLogin()
|
||||
.flatMap(userRepository::findOneByLogin)
|
||||
.ifPresent(user -> {
|
||||
String currentEncryptedPassword = user.getPassword();
|
||||
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
String encryptedPassword = passwordEncoder.encode(newPassword);
|
||||
user.setPassword(encryptedPassword);
|
||||
LOG.debug("Changed password for User: {}", user);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
|
||||
return userRepository.findAll(pageable).map(AdminUserDTO::new);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UserDTO> getAllPublicUsers(Pageable pageable) {
|
||||
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
|
||||
return userRepository.findOneWithAuthoritiesByLogin(login);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> getUserWithAuthorities() {
|
||||
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Not activated users should be automatically deleted after 3 days.
|
||||
* <p>
|
||||
* This is scheduled to get fired every day, at 01:00 (am).
|
||||
*/
|
||||
@Scheduled(cron = "0 0 1 * * ?")
|
||||
public void removeNotActivatedUsers() {
|
||||
userRepository
|
||||
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
|
||||
.forEach(user -> {
|
||||
LOG.debug("Deleting not activated user {}", user.getLogin());
|
||||
userRepository.delete(user);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all the authorities.
|
||||
* @return a list of all the authorities.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<String> getAuthorities() {
|
||||
return authorityRepository.findAll().stream().map(Authority::getName).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.example.questionbank.service;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
public class UsernameAlreadyUsedException extends RuntimeException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UsernameAlreadyUsedException() {
|
||||
super("Login name already used!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.example.questionbank.service.dto;
|
||||
|
||||
import com.example.questionbank.config.Constants;
|
||||
import com.example.questionbank.domain.Authority;
|
||||
import com.example.questionbank.domain.User;
|
||||
import jakarta.validation.constraints.*;
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A DTO representing a user, with his authorities.
|
||||
*/
|
||||
public class AdminUserDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
|
||||
@NotBlank
|
||||
@Pattern(regexp = Constants.LOGIN_REGEX)
|
||||
@Size(min = 1, max = 50)
|
||||
private String login;
|
||||
|
||||
@Size(max = 50)
|
||||
private String firstName;
|
||||
|
||||
@Size(max = 50)
|
||||
private String lastName;
|
||||
|
||||
@Email
|
||||
@Size(min = 5, max = 254)
|
||||
private String email;
|
||||
|
||||
@Size(max = 256)
|
||||
private String imageUrl;
|
||||
|
||||
private boolean activated = false;
|
||||
|
||||
@Size(min = 2, max = 10)
|
||||
private String langKey;
|
||||
|
||||
private String createdBy;
|
||||
|
||||
private Instant createdDate;
|
||||
|
||||
private String lastModifiedBy;
|
||||
|
||||
private Instant lastModifiedDate;
|
||||
|
||||
private Set<String> authorities;
|
||||
|
||||
public AdminUserDTO() {
|
||||
// Empty constructor needed for Jackson.
|
||||
}
|
||||
|
||||
public AdminUserDTO(User user) {
|
||||
this.id = user.getId();
|
||||
this.login = user.getLogin();
|
||||
this.firstName = user.getFirstName();
|
||||
this.lastName = user.getLastName();
|
||||
this.email = user.getEmail();
|
||||
this.activated = user.isActivated();
|
||||
this.imageUrl = user.getImageUrl();
|
||||
this.langKey = user.getLangKey();
|
||||
this.createdBy = user.getCreatedBy();
|
||||
this.createdDate = user.getCreatedDate();
|
||||
this.lastModifiedBy = user.getLastModifiedBy();
|
||||
this.lastModifiedDate = user.getLastModifiedDate();
|
||||
this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getImageUrl() {
|
||||
return imageUrl;
|
||||
}
|
||||
|
||||
public void setImageUrl(String imageUrl) {
|
||||
this.imageUrl = imageUrl;
|
||||
}
|
||||
|
||||
public boolean isActivated() {
|
||||
return activated;
|
||||
}
|
||||
|
||||
public void setActivated(boolean activated) {
|
||||
this.activated = activated;
|
||||
}
|
||||
|
||||
public String getLangKey() {
|
||||
return langKey;
|
||||
}
|
||||
|
||||
public void setLangKey(String langKey) {
|
||||
this.langKey = langKey;
|
||||
}
|
||||
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public Instant getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(Instant createdDate) {
|
||||
this.createdDate = createdDate;
|
||||
}
|
||||
|
||||
public String getLastModifiedBy() {
|
||||
return lastModifiedBy;
|
||||
}
|
||||
|
||||
public void setLastModifiedBy(String lastModifiedBy) {
|
||||
this.lastModifiedBy = lastModifiedBy;
|
||||
}
|
||||
|
||||
public Instant getLastModifiedDate() {
|
||||
return lastModifiedDate;
|
||||
}
|
||||
|
||||
public void setLastModifiedDate(Instant lastModifiedDate) {
|
||||
this.lastModifiedDate = lastModifiedDate;
|
||||
}
|
||||
|
||||
public Set<String> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public void setAuthorities(Set<String> authorities) {
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AdminUserDTO{" +
|
||||
"login='" + login + '\'' +
|
||||
", firstName='" + firstName + '\'' +
|
||||
", lastName='" + lastName + '\'' +
|
||||
", email='" + email + '\'' +
|
||||
", imageUrl='" + imageUrl + '\'' +
|
||||
", activated=" + activated +
|
||||
", langKey='" + langKey + '\'' +
|
||||
", createdBy=" + createdBy +
|
||||
", createdDate=" + createdDate +
|
||||
", lastModifiedBy='" + lastModifiedBy + '\'' +
|
||||
", lastModifiedDate=" + lastModifiedDate +
|
||||
", authorities=" + authorities +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.questionbank.service.dto;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* A DTO representing a password change required data - current and new password.
|
||||
*/
|
||||
public class PasswordChangeDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String currentPassword;
|
||||
private String newPassword;
|
||||
|
||||
public PasswordChangeDTO() {
|
||||
// Empty constructor needed for Jackson.
|
||||
}
|
||||
|
||||
public PasswordChangeDTO(String currentPassword, String newPassword) {
|
||||
this.currentPassword = currentPassword;
|
||||
this.newPassword = newPassword;
|
||||
}
|
||||
|
||||
public String getCurrentPassword() {
|
||||
return currentPassword;
|
||||
}
|
||||
|
||||
public void setCurrentPassword(String currentPassword) {
|
||||
this.currentPassword = currentPassword;
|
||||
}
|
||||
|
||||
public String getNewPassword() {
|
||||
return newPassword;
|
||||
}
|
||||
|
||||
public void setNewPassword(String newPassword) {
|
||||
this.newPassword = newPassword;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.example.questionbank.service.dto;
|
||||
|
||||
import com.example.questionbank.domain.User;
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A DTO representing a user, with only the public attributes.
|
||||
*/
|
||||
public class UserDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
|
||||
private String login;
|
||||
|
||||
public UserDTO() {
|
||||
// Empty constructor needed for Jackson.
|
||||
}
|
||||
|
||||
public UserDTO(User user) {
|
||||
this.id = user.getId();
|
||||
// Customize it here if you need, or not, firstName/lastName/etc
|
||||
this.login = user.getLogin();
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UserDTO userDTO = (UserDTO) o;
|
||||
if (userDTO.getId() == null || getId() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Objects.equals(getId(), userDTO.getId()) && Objects.equals(getLogin(), userDTO.getLogin());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getId(), getLogin());
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserDTO{" +
|
||||
"id='" + id + '\'' +
|
||||
", login='" + login + '\'' +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Data transfer objects for rest mapping.
|
||||
*/
|
||||
package com.example.questionbank.service.dto;
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.example.questionbank.service.mapper;
|
||||
|
||||
import com.example.questionbank.domain.Authority;
|
||||
import com.example.questionbank.domain.User;
|
||||
import com.example.questionbank.service.dto.AdminUserDTO;
|
||||
import com.example.questionbank.service.dto.UserDTO;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import org.mapstruct.BeanMapping;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.Named;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
|
||||
*
|
||||
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
|
||||
* support is still in beta, and requires a manual step with an IDE.
|
||||
*/
|
||||
@Service
|
||||
public class UserMapper {
|
||||
|
||||
public List<UserDTO> usersToUserDTOs(List<User> users) {
|
||||
return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList();
|
||||
}
|
||||
|
||||
public UserDTO userToUserDTO(User user) {
|
||||
return new UserDTO(user);
|
||||
}
|
||||
|
||||
public List<AdminUserDTO> usersToAdminUserDTOs(List<User> users) {
|
||||
return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).toList();
|
||||
}
|
||||
|
||||
public AdminUserDTO userToAdminUserDTO(User user) {
|
||||
return new AdminUserDTO(user);
|
||||
}
|
||||
|
||||
public List<User> userDTOsToUsers(List<AdminUserDTO> userDTOs) {
|
||||
return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).toList();
|
||||
}
|
||||
|
||||
public User userDTOToUser(AdminUserDTO userDTO) {
|
||||
if (userDTO == null) {
|
||||
return null;
|
||||
} else {
|
||||
User user = new User();
|
||||
user.setId(userDTO.getId());
|
||||
user.setLogin(userDTO.getLogin());
|
||||
user.setFirstName(userDTO.getFirstName());
|
||||
user.setLastName(userDTO.getLastName());
|
||||
user.setEmail(userDTO.getEmail());
|
||||
user.setImageUrl(userDTO.getImageUrl());
|
||||
user.setCreatedBy(userDTO.getCreatedBy());
|
||||
user.setCreatedDate(userDTO.getCreatedDate());
|
||||
user.setLastModifiedBy(userDTO.getLastModifiedBy());
|
||||
user.setLastModifiedDate(userDTO.getLastModifiedDate());
|
||||
user.setActivated(userDTO.isActivated());
|
||||
user.setLangKey(userDTO.getLangKey());
|
||||
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
|
||||
user.setAuthorities(authorities);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
|
||||
Set<Authority> authorities = new HashSet<>();
|
||||
|
||||
if (authoritiesAsString != null) {
|
||||
authorities = authoritiesAsString
|
||||
.stream()
|
||||
.map(string -> {
|
||||
Authority auth = new Authority();
|
||||
auth.setName(string);
|
||||
return auth;
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public User userFromId(Long id) {
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
User user = new User();
|
||||
user.setId(id);
|
||||
return user;
|
||||
}
|
||||
|
||||
@Named("id")
|
||||
@BeanMapping(ignoreByDefault = true)
|
||||
@Mapping(target = "id", source = "id")
|
||||
public UserDTO toDtoId(User user) {
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
UserDTO userDto = new UserDTO();
|
||||
userDto.setId(user.getId());
|
||||
return userDto;
|
||||
}
|
||||
|
||||
@Named("idSet")
|
||||
@BeanMapping(ignoreByDefault = true)
|
||||
@Mapping(target = "id", source = "id")
|
||||
public Set<UserDTO> toDtoIdSet(Set<User> users) {
|
||||
if (users == null) {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
Set<UserDTO> userSet = new HashSet<>();
|
||||
for (User userEntity : users) {
|
||||
userSet.add(this.toDtoId(userEntity));
|
||||
}
|
||||
|
||||
return userSet;
|
||||
}
|
||||
|
||||
@Named("login")
|
||||
@BeanMapping(ignoreByDefault = true)
|
||||
@Mapping(target = "id", source = "id")
|
||||
@Mapping(target = "login", source = "login")
|
||||
public UserDTO toDtoLogin(User user) {
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
UserDTO userDto = new UserDTO();
|
||||
userDto.setId(user.getId());
|
||||
userDto.setLogin(user.getLogin());
|
||||
return userDto;
|
||||
}
|
||||
|
||||
@Named("loginSet")
|
||||
@BeanMapping(ignoreByDefault = true)
|
||||
@Mapping(target = "id", source = "id")
|
||||
@Mapping(target = "login", source = "login")
|
||||
public Set<UserDTO> toDtoLoginSet(Set<User> users) {
|
||||
if (users == null) {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
Set<UserDTO> userSet = new HashSet<>();
|
||||
for (User userEntity : users) {
|
||||
userSet.add(this.toDtoLogin(userEntity));
|
||||
}
|
||||
|
||||
return userSet;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Data transfer objects mappers.
|
||||
*/
|
||||
package com.example.questionbank.service.mapper;
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Service layer.
|
||||
*/
|
||||
package com.example.questionbank.service;
|
||||
Reference in new issue
Block a user