Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
09843e49ad
@ -1,19 +0,0 @@
|
|||||||
package org.baeldung.event;
|
|
||||||
|
|
||||||
import org.springframework.context.ApplicationEvent;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class OnRegistrationComplete extends ApplicationEvent {
|
|
||||||
|
|
||||||
public final Registration registration;
|
|
||||||
|
|
||||||
public OnRegistrationComplete(Registration source) {
|
|
||||||
super(source);
|
|
||||||
this.registration=source;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Registration getRegistration() {
|
|
||||||
return registration;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,34 @@
|
|||||||
|
package org.baeldung.event;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.baeldung.persistence.model.User;
|
||||||
|
import org.springframework.context.ApplicationEvent;
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class OnRegistrationCompleteEvent extends ApplicationEvent {
|
||||||
|
|
||||||
|
private final String appUrl;
|
||||||
|
private final Locale locale;
|
||||||
|
private final User user;
|
||||||
|
|
||||||
|
public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
|
||||||
|
super(user);
|
||||||
|
this.user = user;
|
||||||
|
this.locale = locale;
|
||||||
|
this.appUrl = appUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAppUrl() {
|
||||||
|
return appUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Locale getLocale() {
|
||||||
|
return locale;
|
||||||
|
}
|
||||||
|
|
||||||
|
public User getUser() {
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,57 +0,0 @@
|
|||||||
package org.baeldung.event;
|
|
||||||
|
|
||||||
import java.util.Locale;
|
|
||||||
import org.baeldung.persistence.model.User;
|
|
||||||
import org.springframework.context.ApplicationEventPublisher;
|
|
||||||
import org.springframework.context.ApplicationEventPublisherAware;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class Registration implements ApplicationEventPublisherAware {
|
|
||||||
|
|
||||||
private ApplicationEventPublisher eventPublisher;
|
|
||||||
|
|
||||||
public String getAppUrl() {
|
|
||||||
return appUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Locale getLocale() {
|
|
||||||
return locale;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAppUrl(String appUrl) {
|
|
||||||
this.appUrl = appUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLocale(Locale locale) {
|
|
||||||
this.locale = locale;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUser(User user) {
|
|
||||||
this.user = user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User getUser() {
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String appUrl;
|
|
||||||
private Locale locale;
|
|
||||||
private User user;
|
|
||||||
|
|
||||||
public Registration() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deliver() {
|
|
||||||
this.eventPublisher.publishEvent(new OnRegistrationComplete(this));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setApplicationEventPublisher(
|
|
||||||
ApplicationEventPublisher applicationEventPublisher) {
|
|
||||||
this.eventPublisher = applicationEventPublisher;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,44 @@
|
|||||||
|
package org.baeldung.event.listener;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.baeldung.event.OnRegistrationCompleteEvent;
|
||||||
|
import org.baeldung.persistence.model.User;
|
||||||
|
import org.baeldung.persistence.service.IUserService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.ApplicationListener;
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.mail.SimpleMailMessage;
|
||||||
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {
|
||||||
|
@Autowired
|
||||||
|
private IUserService service;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MessageSource messages;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JavaMailSender mailSender;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onApplicationEvent(OnRegistrationCompleteEvent event) {
|
||||||
|
this.confirmRegistration(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void confirmRegistration(OnRegistrationCompleteEvent event) {
|
||||||
|
User user = event.getUser();
|
||||||
|
String token = UUID.randomUUID().toString();
|
||||||
|
service.addVerificationToken(user, token);
|
||||||
|
String recipientAddress = user.getEmail();
|
||||||
|
String subject = "Registration Confirmation";
|
||||||
|
String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;
|
||||||
|
String message = messages.getMessage("message.regSucc", null, event.getLocale());
|
||||||
|
SimpleMailMessage email = new SimpleMailMessage();
|
||||||
|
email.setTo(recipientAddress);
|
||||||
|
email.setSubject(subject);
|
||||||
|
email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl);
|
||||||
|
mailSender.send(email);
|
||||||
|
}
|
||||||
|
}
|
@ -1,50 +0,0 @@
|
|||||||
package org.baeldung.event.service;
|
|
||||||
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
import org.baeldung.event.OnRegistrationComplete;
|
|
||||||
import org.baeldung.persistence.model.User;
|
|
||||||
import org.baeldung.persistence.service.IUserService;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.ApplicationListener;
|
|
||||||
import org.springframework.context.MessageSource;
|
|
||||||
import org.springframework.mail.SimpleMailMessage;
|
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class RegistrationService implements
|
|
||||||
ApplicationListener<OnRegistrationComplete> {
|
|
||||||
@Autowired
|
|
||||||
private IUserService service;
|
|
||||||
@Autowired
|
|
||||||
private MessageSource messages;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private JavaMailSender mailSender;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onApplicationEvent(OnRegistrationComplete event) {
|
|
||||||
this.confirmRegistration(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void confirmRegistration(OnRegistrationComplete event) {
|
|
||||||
User user = event.getRegistration().getUser();
|
|
||||||
String token = UUID.randomUUID().toString();
|
|
||||||
service.addVerificationToken(user, token);
|
|
||||||
String recipientAddress = user.getEmail();
|
|
||||||
String subject = "Registration Confirmation";
|
|
||||||
String confirmationUrl = event.getRegistration().getAppUrl()
|
|
||||||
+ "/regitrationConfirm.html?token=" + token;
|
|
||||||
String message = messages.getMessage("message.regSucc", null, event
|
|
||||||
.getRegistration().getLocale());
|
|
||||||
SimpleMailMessage email = new SimpleMailMessage();
|
|
||||||
email.setTo(recipientAddress);
|
|
||||||
email.setSubject(subject);
|
|
||||||
email.setText(message + " \r\n" + "http://localhost:8080"
|
|
||||||
+ confirmationUrl);
|
|
||||||
mailSender.send(email);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -7,4 +7,5 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
|||||||
public User findByEmail(String email);
|
public User findByEmail(String email);
|
||||||
|
|
||||||
public void delete(User user);
|
public void delete(User user);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,12 @@
|
|||||||
package org.baeldung.persistence.dao;
|
package org.baeldung.persistence.dao;
|
||||||
|
|
||||||
|
import org.baeldung.persistence.model.User;
|
||||||
import org.baeldung.persistence.model.VerificationToken;
|
import org.baeldung.persistence.model.VerificationToken;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {
|
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {
|
||||||
|
|
||||||
public VerificationToken findByToken(String token);
|
public VerificationToken findByToken(String token);
|
||||||
|
|
||||||
|
public VerificationToken findByUser(User user);
|
||||||
}
|
}
|
||||||
|
@ -11,8 +11,8 @@ import javax.persistence.JoinColumn;
|
|||||||
import javax.persistence.OneToOne;
|
import javax.persistence.OneToOne;
|
||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
|
|
||||||
@Entity(name = "role")
|
@Entity
|
||||||
@Table(name = "role")
|
@Table
|
||||||
public class Role {
|
public class Role {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@ -28,7 +28,6 @@ public class Role {
|
|||||||
|
|
||||||
public Role() {
|
public Role() {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Role(Integer role) {
|
public Role(Integer role) {
|
||||||
|
@ -17,31 +17,25 @@ public class User {
|
|||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@Column(name = "firstName")
|
@Column(name = "firstName")
|
||||||
private String firstName;
|
private String firstName;
|
||||||
|
|
||||||
@Column(name = "lastName")
|
@Column(name = "lastName")
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
@Column(name = "email")
|
@Column(name = "email")
|
||||||
private String email;
|
private String email;
|
||||||
|
|
||||||
@Column(name = "password")
|
@Column(name = "password")
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
@OneToOne(mappedBy="user",
|
@Column(name = "enabled")
|
||||||
fetch = FetchType.EAGER,
|
private boolean enabled;
|
||||||
cascade= CascadeType.ALL)
|
|
||||||
private VerificationToken verificationToken;
|
|
||||||
|
|
||||||
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||||
private Role role;
|
private Role role;
|
||||||
|
|
||||||
public VerificationToken getVerificationToken() {
|
|
||||||
return verificationToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVerificationToken(VerificationToken verificationToken) {
|
|
||||||
this.verificationToken = verificationToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getId() {
|
public Long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@ -90,6 +84,14 @@ public class User {
|
|||||||
this.role = role;
|
this.role = role;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEnabled(boolean enabled) {
|
||||||
|
this.enabled = enabled;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
@ -111,11 +113,11 @@ public class User {
|
|||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
final StringBuilder builder = new StringBuilder();
|
||||||
builder.append("User [firstName=").append(firstName).append("]").
|
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
|
||||||
append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
|
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -13,8 +13,8 @@ import javax.persistence.JoinColumn;
|
|||||||
import javax.persistence.OneToOne;
|
import javax.persistence.OneToOne;
|
||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
|
|
||||||
@Entity()
|
@Entity
|
||||||
@Table()
|
@Table
|
||||||
public class VerificationToken {
|
public class VerificationToken {
|
||||||
|
|
||||||
private static final int EXPIRATION = 60 * 24;
|
private static final int EXPIRATION = 60 * 24;
|
||||||
@ -26,9 +26,6 @@ public class VerificationToken {
|
|||||||
@Column(name = "token")
|
@Column(name = "token")
|
||||||
private String token;
|
private String token;
|
||||||
|
|
||||||
@Column(name = "verified")
|
|
||||||
private boolean verified;
|
|
||||||
|
|
||||||
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
|
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
|
||||||
@JoinColumn(name = "user_id")
|
@JoinColumn(name = "user_id")
|
||||||
private User user;
|
private User user;
|
||||||
@ -38,7 +35,6 @@ public class VerificationToken {
|
|||||||
|
|
||||||
public VerificationToken() {
|
public VerificationToken() {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public VerificationToken(String token) {
|
public VerificationToken(String token) {
|
||||||
@ -52,7 +48,6 @@ public class VerificationToken {
|
|||||||
this.token = token;
|
this.token = token;
|
||||||
this.user = user;
|
this.user = user;
|
||||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||||
this.verified = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getToken() {
|
public String getToken() {
|
||||||
@ -63,14 +58,6 @@ public class VerificationToken {
|
|||||||
this.token = token;
|
this.token = token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isVerified() {
|
|
||||||
return verified;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVerified(boolean verified) {
|
|
||||||
this.verified = verified;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User getUser() {
|
public User getUser() {
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
@ -112,9 +99,7 @@ public class VerificationToken {
|
|||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
final StringBuilder builder = new StringBuilder();
|
||||||
builder.append("Token [String=").append(token).append("]")
|
builder.append("Token [String=").append(token).append("]").append("[Expires").append(expiryDate).append("]");
|
||||||
.append("[verified=").append(verified).append("]")
|
|
||||||
.append("[Expires").append(expiryDate).append("]");
|
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,17 +1,24 @@
|
|||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
|
import org.baeldung.persistence.model.VerificationToken;
|
||||||
import org.baeldung.validation.service.EmailExistsException;
|
import org.baeldung.validation.service.EmailExistsException;
|
||||||
|
|
||||||
public interface IUserService {
|
public interface IUserService {
|
||||||
|
|
||||||
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
|
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
|
||||||
|
|
||||||
public User getRegisteredUser(String email);
|
/* public User getRegisteredUser(String email);*/
|
||||||
|
|
||||||
public User getUser(String verificationToken);
|
public User getUser(String verificationToken);
|
||||||
|
|
||||||
public void verifyRegisteredUser(User user);
|
public void saveRegisteredUser(User user);
|
||||||
|
|
||||||
public void addVerificationToken(User user, String token);
|
public void addVerificationToken(User user, String token);
|
||||||
|
|
||||||
|
public VerificationToken getVerificationToken(String VerificationToken);
|
||||||
|
|
||||||
|
public void verifyUser(VerificationToken token);
|
||||||
|
|
||||||
|
public void deleteUser(User user);
|
||||||
}
|
}
|
||||||
|
@ -15,18 +15,15 @@ import org.springframework.stereotype.Service;
|
|||||||
public class UserService implements IUserService {
|
public class UserService implements IUserService {
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository repository;
|
private UserRepository repository;
|
||||||
// NOV 6
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private VerificationTokenRepository tokenRepository;
|
private VerificationTokenRepository tokenRepository;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@Override
|
@Override
|
||||||
public User registerNewUserAccount(UserDto accountDto)
|
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
|
||||||
throws EmailExistsException {
|
|
||||||
if (emailExist(accountDto.getEmail())) {
|
if (emailExist(accountDto.getEmail())) {
|
||||||
throw new EmailExistsException(
|
throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail());
|
||||||
"There is an account with that email adress: "
|
|
||||||
+ accountDto.getEmail());
|
|
||||||
}
|
}
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setFirstName(accountDto.getFirstName());
|
user.setFirstName(accountDto.getFirstName());
|
||||||
@ -45,13 +42,13 @@ public class UserService implements IUserService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
/* @Override
|
||||||
public User getRegisteredUser(String email) {
|
public User getRegisteredUser(String email) {
|
||||||
|
|
||||||
User user = repository.findByEmail(email);
|
User user = repository.findByEmail(email);
|
||||||
return user;
|
return user;
|
||||||
|
|
||||||
}
|
}*/
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public User getUser(String verificationToken) {
|
public User getUser(String verificationToken) {
|
||||||
@ -59,17 +56,35 @@ public class UserService implements IUserService {
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public VerificationToken getVerificationToken(String VerificationToken) {
|
||||||
|
return tokenRepository.findByToken(VerificationToken);
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@Override
|
@Override
|
||||||
public void verifyRegisteredUser(User user) {
|
public void saveRegisteredUser(User user) {
|
||||||
repository.save(user);
|
repository.save(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public void verifyUser(VerificationToken token) {
|
||||||
|
tokenRepository.save(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public void deleteUser(User user) {
|
||||||
|
repository.delete(user);
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@Override
|
@Override
|
||||||
public void addVerificationToken(User user, String token) {
|
public void addVerificationToken(User user, String token) {
|
||||||
VerificationToken myToken = new VerificationToken(token, user);
|
VerificationToken myToken = new VerificationToken(token, user);
|
||||||
user.setVerificationToken(myToken);
|
// user.setVerificationToken(myToken);
|
||||||
repository.save(user);
|
tokenRepository.save(myToken);
|
||||||
|
// repository.save(user);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -55,7 +55,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isUser) {
|
if (isUser) {
|
||||||
return "/homepage.html";
|
return "/homepage.html?user="+authentication.getName();
|
||||||
} else if (isAdmin) {
|
} else if (isAdmin) {
|
||||||
return "/console.html";
|
return "/console.html";
|
||||||
} else {
|
} else {
|
||||||
|
@ -1,10 +1,8 @@
|
|||||||
package org.baeldung.security;
|
package org.baeldung.security;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
@ -12,6 +10,7 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.baeldung.persistence.dao.UserRepository;
|
import org.baeldung.persistence.dao.UserRepository;
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
|
import org.baeldung.persistence.service.IUserService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.MessageSource;
|
import org.springframework.context.MessageSource;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
@ -25,10 +24,10 @@ public class MyUserDetailsService implements UserDetailsService {
|
|||||||
|
|
||||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
// OCT 21
|
|
||||||
// @Autowired
|
|
||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
@Autowired
|
@Autowired
|
||||||
|
private IUserService service;
|
||||||
|
@Autowired
|
||||||
private MessageSource messages;
|
private MessageSource messages;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@ -36,8 +35,7 @@ public class MyUserDetailsService implements UserDetailsService {
|
|||||||
this.userRepository = repository;
|
this.userRepository = repository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserDetails loadUserByUsername(String email)
|
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||||
throws UsernameNotFoundException {
|
|
||||||
boolean enabled = true;
|
boolean enabled = true;
|
||||||
boolean accountNonExpired = true;
|
boolean accountNonExpired = true;
|
||||||
boolean credentialsNonExpired = true;
|
boolean credentialsNonExpired = true;
|
||||||
@ -45,32 +43,16 @@ public class MyUserDetailsService implements UserDetailsService {
|
|||||||
try {
|
try {
|
||||||
LOGGER.debug("Loading user by username: {}", email);
|
LOGGER.debug("Loading user by username: {}", email);
|
||||||
User user = userRepository.findByEmail(email);
|
User user = userRepository.findByEmail(email);
|
||||||
// OCT 21
|
|
||||||
Calendar cal = Calendar.getInstance();
|
|
||||||
LOGGER.debug("Found user: {}", user);
|
LOGGER.debug("Found user: {}", user);
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
return new org.springframework.security.core.userdetails.User(
|
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
|
||||||
" ", " ", enabled, true, true, true,
|
|
||||||
getAuthorities(new Integer(1)));
|
|
||||||
}
|
}
|
||||||
// OCT 21
|
if (!user.isEnabled()) {
|
||||||
if (!(user.getVerificationToken().isVerified())) {
|
|
||||||
enabled = false;
|
|
||||||
}
|
|
||||||
// OCT 21
|
|
||||||
if ((user.getVerificationToken().isVerified())
|
|
||||||
&& (user.getVerificationToken().getExpiryDate().getTime() - cal
|
|
||||||
.getTime().getTime()) <= 0) {
|
|
||||||
userRepository.delete(user);
|
|
||||||
// DEBUGGING
|
|
||||||
System.out.println("Deleted");
|
|
||||||
|
|
||||||
accountNonExpired = false;
|
accountNonExpired = false;
|
||||||
|
service.deleteUser(user);
|
||||||
|
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, accountNonExpired, true, true, getAuthorities(new Integer(1)));
|
||||||
}
|
}
|
||||||
return new org.springframework.security.core.userdetails.User(
|
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
|
||||||
user.getEmail(), user.getPassword().toLowerCase(), enabled,
|
|
||||||
accountNonExpired, credentialsNonExpired, accountNonLocked,
|
|
||||||
getAuthorities(user.getRole().getRole()));
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
@ -84,18 +66,15 @@ public class MyUserDetailsService implements UserDetailsService {
|
|||||||
|
|
||||||
public List<String> getRoles(Integer role) {
|
public List<String> getRoles(Integer role) {
|
||||||
List<String> roles = new ArrayList<String>();
|
List<String> roles = new ArrayList<String>();
|
||||||
|
|
||||||
if (role.intValue() == 2) {
|
if (role.intValue() == 2) {
|
||||||
roles.add("ROLE_ADMIN");
|
roles.add("ROLE_ADMIN");
|
||||||
|
|
||||||
} else if (role.intValue() == 1) {
|
} else if (role.intValue() == 1) {
|
||||||
roles.add("ROLE_USER");
|
roles.add("ROLE_USER");
|
||||||
}
|
}
|
||||||
return roles;
|
return roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<GrantedAuthority> getGrantedAuthorities(
|
private static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
||||||
List<String> roles) {
|
|
||||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||||
for (String role : roles) {
|
for (String role : roles) {
|
||||||
authorities.add(new SimpleGrantedAuthority(role));
|
authorities.add(new SimpleGrantedAuthority(role));
|
||||||
|
@ -13,9 +13,7 @@ import org.springframework.core.env.Environment;
|
|||||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan(basePackages = { "org.baeldung.event.service",
|
@ComponentScan(basePackages = { "org.baeldung.event.service", "org.baeldung.event", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||||
"org.baeldung.event", "org.baeldung.persistence.service",
|
|
||||||
"org.baeldung.persistence.dao" })
|
|
||||||
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
||||||
@PropertySource("classpath:application.properties")
|
@PropertySource("classpath:application.properties")
|
||||||
public class AppConfig {
|
public class AppConfig {
|
||||||
|
@ -22,8 +22,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
|||||||
import org.springframework.web.servlet.view.JstlView;
|
import org.springframework.web.servlet.view.JstlView;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service",
|
@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||||
"org.baeldung.persistence.dao" })
|
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
|
@ -1,15 +1,17 @@
|
|||||||
package org.baeldung.web.controller;
|
package org.baeldung.web.controller;
|
||||||
|
|
||||||
|
import java.util.Calendar;
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import org.baeldung.event.Registration;
|
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
import org.baeldung.persistence.model.VerificationToken;
|
import org.baeldung.persistence.model.VerificationToken;
|
||||||
import org.baeldung.persistence.service.UserDto;
|
import org.baeldung.persistence.service.UserDto;
|
||||||
import org.baeldung.persistence.service.IUserService;
|
import org.baeldung.persistence.service.IUserService;
|
||||||
|
import org.baeldung.event.OnRegistrationCompleteEvent;
|
||||||
import org.baeldung.validation.service.EmailExistsException;
|
import org.baeldung.validation.service.EmailExistsException;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.context.MessageSource;
|
import org.springframework.context.MessageSource;
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
@ -28,12 +30,15 @@ public class RegistrationController {
|
|||||||
|
|
||||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||||
private IUserService service;
|
private IUserService service;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MessageSource messages;
|
private MessageSource messages;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private JavaMailSender mailSender;
|
private JavaMailSender mailSender;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Registration registration;
|
private ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public RegistrationController(IUserService service) {
|
public RegistrationController(IUserService service) {
|
||||||
@ -49,58 +54,48 @@ public class RegistrationController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
|
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
|
||||||
public String confirmRegistration(WebRequest request, Model model,
|
public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) {
|
||||||
@RequestParam("token") String token) {
|
VerificationToken verificationToken = service.getVerificationToken(token);
|
||||||
User user = service.getUser(token);
|
if (verificationToken == null) {
|
||||||
if (user == null) {
|
model.addAttribute("message", messages.getMessage("auth.message.invalidToken", null, request.getLocale()));
|
||||||
model.addAttribute("message", messages.getMessage(
|
return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage();
|
||||||
"auth.message.invalidUser", null, request.getLocale()));
|
|
||||||
return "redirect:/badUser.html?lang="
|
|
||||||
+ request.getLocale().getLanguage();
|
|
||||||
}
|
|
||||||
|
|
||||||
VerificationToken verificationToken = user.getVerificationToken();
|
|
||||||
if (!verificationToken.getToken().equals(token)) {
|
|
||||||
model.addAttribute("message", messages.getMessage(
|
|
||||||
"auth.message.invalidToken", null, request.getLocale()));
|
|
||||||
return "redirect:/badUser.html?lang="
|
|
||||||
+ request.getLocale().getLanguage();
|
|
||||||
}
|
}
|
||||||
user.getVerificationToken().setVerified(true);
|
User user = verificationToken.getUser();
|
||||||
service.verifyRegisteredUser(user);
|
Calendar cal = Calendar.getInstance();
|
||||||
|
if (user == null) {
|
||||||
|
model.addAttribute("message", messages.getMessage("auth.message.invalidUser", null, request.getLocale()));
|
||||||
|
return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage();
|
||||||
|
}
|
||||||
|
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
|
||||||
|
user.setEnabled(false);
|
||||||
|
} else {
|
||||||
|
user.setEnabled(true);
|
||||||
|
}
|
||||||
|
service.saveRegisteredUser(user);
|
||||||
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
|
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||||
public ModelAndView registerUserAccount(
|
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) {
|
||||||
@ModelAttribute("user") @Valid UserDto accountDto,
|
LOGGER.debug("Registering user account with information: {}", accountDto);
|
||||||
BindingResult result, WebRequest request, Errors errors) {
|
|
||||||
|
|
||||||
LOGGER.debug("Registering user account with information: {}",
|
|
||||||
accountDto);
|
|
||||||
User registered = new User();
|
User registered = new User();
|
||||||
String appUrl = request.getContextPath();
|
String appUrl = request.getContextPath();
|
||||||
if (!result.hasErrors())
|
if (result.hasErrors()) {
|
||||||
registered = createUserAccount(accountDto, result);
|
return new ModelAndView("registration", "user", accountDto);
|
||||||
|
}
|
||||||
|
registered = createUserAccount(accountDto);
|
||||||
if (registered == null) {
|
if (registered == null) {
|
||||||
result.rejectValue("email", "message.regError");
|
result.rejectValue("email", "message.regError");
|
||||||
}
|
}
|
||||||
if (result.hasErrors()) {
|
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
|
||||||
return new ModelAndView("registration", "user", accountDto);
|
|
||||||
} else {
|
|
||||||
registration.setAppUrl(appUrl);
|
|
||||||
registration.setLocale(request.getLocale());
|
|
||||||
registration.setUser(registered);
|
|
||||||
registration.deliver();
|
|
||||||
return new ModelAndView("successRegister", "user", accountDto);
|
return new ModelAndView("successRegister", "user", accountDto);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private User createUserAccount(UserDto accountDto, BindingResult result) {
|
private User createUserAccount(UserDto accountDto) {
|
||||||
User registered = null;
|
User registered = null;
|
||||||
try {
|
try {
|
||||||
registered = service.registerNewUserAccount(accountDto);
|
registered = service.registerNewUserAccount(accountDto);
|
||||||
|
|
||||||
} catch (EmailExistsException e) {
|
} catch (EmailExistsException e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -12,6 +12,6 @@ hibernate.hbm2ddl.auto=create-drop
|
|||||||
smtp.host=smtp.gmail.com
|
smtp.host=smtp.gmail.com
|
||||||
smtp.port=465
|
smtp.port=465
|
||||||
smtp.protocol=smtps
|
smtp.protocol=smtps
|
||||||
smtp.username=
|
smtp.username=xxx@gmail.com
|
||||||
smtp.password=
|
smtp.password=
|
||||||
support.email=
|
support.email=xxx@gmail.com
|
||||||
|
@ -34,8 +34,8 @@ label.pages.logout=Salir
|
|||||||
label.pages.admin=Administrador
|
label.pages.admin=Administrador
|
||||||
label.pages.home.title=Inicio
|
label.pages.home.title=Inicio
|
||||||
label.pages.home.message=Bienveni@ a Casa
|
label.pages.home.message=Bienveni@ a Casa
|
||||||
label.pages.admin.message=Bienvenido Admin
|
label.pages.admin.message=Bienvenid@ Admin
|
||||||
label.pages.user.message=Bienvenido Usuario
|
label.pages.user.message=Bienvenid@ Usuari@
|
||||||
label.successRegister.title=Registro Exitoso
|
label.successRegister.title=Registro Exitoso
|
||||||
label.badUser.title=Enlace Invalido
|
label.badUser.title=Enlace Invalido
|
||||||
ValidEmail.user.email=Cuenta correo invlida!
|
ValidEmail.user.email=Cuenta correo invlida!
|
||||||
|
@ -13,7 +13,8 @@ code="label.badUser.title"></spring:message></title>
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>
|
<h1>
|
||||||
${message}
|
<div class="alert alert-error">
|
||||||
|
${param.message}
|
||||||
</h1>
|
</h1>
|
||||||
<br>
|
<br>
|
||||||
<a href="<c:url value="/user/registration" />"><spring:message
|
<a href="<c:url value="/user/registration" />"><spring:message
|
||||||
|
@ -8,7 +8,9 @@
|
|||||||
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
|
|
||||||
<div class="span12">
|
<div class="span12">
|
||||||
<sec:authorize access="hasRole('ROLE_USER')">
|
<sec:authorize access="hasRole('ROLE_USER')">
|
||||||
<spring:message code="label.pages.user.message"></spring:message>
|
<spring:message code="label.pages.user.message"></spring:message>
|
||||||
@ -19,6 +21,7 @@
|
|||||||
<spring:message code="label.pages.admin.message"></spring:message>
|
<spring:message code="label.pages.admin.message"></spring:message>
|
||||||
<br />
|
<br />
|
||||||
</sec:authorize>
|
</sec:authorize>
|
||||||
|
${param.user}
|
||||||
<a href="<c:url value="/j_spring_security_logout" />"><spring:message
|
<a href="<c:url value="/j_spring_security_logout" />"><spring:message
|
||||||
code="label.pages.logout"></spring:message></a> <a
|
code="label.pages.logout"></spring:message></a> <a
|
||||||
href="<c:url value="/home.html" />"><spring:message
|
href="<c:url value="/home.html" />"><spring:message
|
||||||
|
Loading…
x
Reference in New Issue
Block a user