Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
6988a5be69
|
@ -2,7 +2,12 @@ package org.baeldung.persistence.dao;
|
|||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
public User findByEmail(String email);
|
||||
//NOV 5th
|
||||
// public User findByVerificationToken(VerificationToken token);
|
||||
//OCT 21
|
||||
public void delete(User user);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {
|
||||
|
||||
public VerificationToken findByToken(String token);
|
||||
}
|
|
@ -10,25 +10,39 @@ import javax.persistence.Id;
|
|||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity(name = "user")
|
||||
@Table(name = "user")
|
||||
@Entity
|
||||
@Table
|
||||
public class User {
|
||||
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column(name = "firstName")
|
||||
@Column(name="firstName")
|
||||
private String firstName;
|
||||
@Column(name = "lastName")
|
||||
@Column(name="lastName")
|
||||
private String lastName;
|
||||
@Column(name = "email")
|
||||
@Column(name="email")
|
||||
private String email;
|
||||
@Column(name = "password")
|
||||
@Column(name="password")
|
||||
private String password;
|
||||
|
||||
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||
|
||||
//EMAIL CONF ARTICLE
|
||||
@OneToOne(mappedBy="user",
|
||||
fetch = FetchType.EAGER,
|
||||
cascade= CascadeType.ALL)
|
||||
private VerificationToken verificationToken;
|
||||
|
||||
@OneToOne(mappedBy = "user",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||
private Role role;
|
||||
|
||||
public VerificationToken getVerificationToken() {
|
||||
return verificationToken;
|
||||
}
|
||||
|
||||
public void setVerificationToken(VerificationToken verificationToken) {
|
||||
this.verificationToken = verificationToken;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
@ -57,8 +71,8 @@ public class User {
|
|||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
public void setEmail(String username) {
|
||||
this.email = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
|
@ -98,11 +112,11 @@ public class User {
|
|||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]");
|
||||
builder.append("User [firstName=").append(firstName).append("]").
|
||||
append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,124 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
import java.sql.Timestamp;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity(/*name = "verrification_token"*/)
|
||||
@Table(/*name = "verrification_token"*/)
|
||||
public class VerificationToken /*implements Serializable*/ {
|
||||
|
||||
//private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final int EXPIRATION = 60 * 24/* 1 */;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "token")
|
||||
private String token;
|
||||
|
||||
@Column(name = "verified")
|
||||
private boolean verified;
|
||||
|
||||
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "user_id")
|
||||
private User user;
|
||||
|
||||
@Column(name = "expiry_date")
|
||||
private Date expiryDate;
|
||||
|
||||
public VerificationToken() {
|
||||
super();
|
||||
|
||||
}
|
||||
|
||||
public VerificationToken(String token) {
|
||||
super();
|
||||
this.token = token;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
public VerificationToken(String token, User user) {
|
||||
super();
|
||||
this.token = token;
|
||||
this.user = user;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
this.verified = false;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public boolean isVerified() {
|
||||
return verified;
|
||||
}
|
||||
|
||||
public void setVerified(boolean verified) {
|
||||
this.verified = verified;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getExpiryDate() {
|
||||
return expiryDate;
|
||||
}
|
||||
|
||||
public void setExpiryDate(Date expiryDate) {
|
||||
this.expiryDate = expiryDate;
|
||||
}
|
||||
|
||||
private Date calculateExpiryDate(int expiryTimeInMinutes) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(new Timestamp(cal.getTime().getTime()));
|
||||
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
|
||||
return new Date(cal.getTime().getTime());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final VerificationToken verificationToken = (VerificationToken) obj;
|
||||
if (!token.equals(verificationToken.getToken()))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Token [String=").append(token).append("]")
|
||||
.append("[verified=").append(verified).append("]")
|
||||
.append("[Expires").append(expiryDate).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,15 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.service.EmailExistsException;
|
||||
|
||||
public interface IUserService {
|
||||
|
||||
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
|
||||
|
||||
//OCT 21 EMAIL VERIFICATION
|
||||
public User getRegisteredUser(String email);
|
||||
|
||||
public void verifyRegisteredUser(User user);
|
||||
}
|
||||
|
|
|
@ -24,8 +24,17 @@ public class UserDto {
|
|||
@NotNull
|
||||
@NotEmpty
|
||||
private String email;
|
||||
private String token;
|
||||
|
||||
public String getEmail() {
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
|
|
|
@ -5,6 +5,7 @@ import javax.transaction.Transactional;
|
|||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.service.EmailExistsException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
@ -27,6 +28,10 @@ public class UserService implements IUserService {
|
|||
user.setEmail(accountDto.getEmail());
|
||||
// ROLE WILL ALWAYS BE USER. HARDCODING IT
|
||||
user.setRole(new Role(Integer.valueOf(1), user));
|
||||
//OCT 21 EMAIL VERIFICATION VERSION
|
||||
//MIGHT CHANGE HERE
|
||||
VerificationToken myToken = new VerificationToken(accountDto.getToken(),user);
|
||||
user.setVerificationToken(myToken);
|
||||
return repository.save(user);
|
||||
}
|
||||
|
||||
|
@ -37,4 +42,19 @@ public class UserService implements IUserService {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//OCT 21 EMAIL VERIFICATION
|
||||
@Override
|
||||
public User getRegisteredUser(String email){
|
||||
|
||||
User user = repository.findByEmail(email);
|
||||
return user;
|
||||
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Override
|
||||
public void verifyRegisteredUser(User user){
|
||||
repository.save(user);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -12,6 +13,7 @@ import org.slf4j.LoggerFactory;
|
|||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
@ -21,54 +23,83 @@ import org.springframework.transaction.annotation.Transactional;
|
|||
@Transactional
|
||||
public class MyUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
// OCT 21
|
||||
// @Autowired
|
||||
private UserRepository userRepository;
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||
try {
|
||||
LOGGER.debug("Loading user by username: {}", email);
|
||||
User user = userRepository.findByEmail(email);
|
||||
LOGGER.debug("Found user: {}", user);
|
||||
if (user == null) {
|
||||
boolean enabled = false;
|
||||
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
|
||||
}
|
||||
boolean enabled = true;
|
||||
boolean accountNonExpired = true;
|
||||
boolean credentialsNonExpired = true;
|
||||
boolean accountNonLocked = true;
|
||||
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
|
||||
@Autowired
|
||||
public MyUserDetailsService(UserRepository repository) {
|
||||
this.userRepository = repository;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
public UserDetails loadUserByUsername(String email)
|
||||
throws UsernameNotFoundException {
|
||||
boolean enabled = true;
|
||||
boolean accountNonExpired = true;
|
||||
boolean credentialsNonExpired = true;
|
||||
boolean accountNonLocked = true;
|
||||
try {
|
||||
LOGGER.debug("Loading user by username: {}", email);
|
||||
User user = userRepository.findByEmail(email);
|
||||
// OCT 21
|
||||
Calendar cal = Calendar.getInstance();
|
||||
LOGGER.debug("Found user: {}", user);
|
||||
if (user == null) {
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
" ", " ", enabled, true, true, true,
|
||||
getAuthorities(new Integer(1)));
|
||||
}
|
||||
// OCT 21
|
||||
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");
|
||||
|
||||
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
||||
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
|
||||
return authList;
|
||||
}
|
||||
accountNonExpired = false;
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
user.getEmail(), user.getPassword().toLowerCase(), enabled,
|
||||
accountNonExpired, credentialsNonExpired, accountNonLocked,
|
||||
getAuthorities(user.getRole().getRole()));
|
||||
|
||||
public List<String> getRoles(Integer role) {
|
||||
List<String> roles = new ArrayList<String>();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (role.intValue() == 2) {
|
||||
roles.add("ROLE_ADMIN");
|
||||
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
||||
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
|
||||
return authList;
|
||||
}
|
||||
|
||||
} else if (role.intValue() == 1) {
|
||||
roles.add("ROLE_USER");
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
public List<String> getRoles(Integer role) {
|
||||
List<String> roles = new ArrayList<String>();
|
||||
|
||||
private static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
if (role.intValue() == 2) {
|
||||
roles.add("ROLE_ADMIN");
|
||||
|
||||
} else if (role.intValue() == 1) {
|
||||
roles.add("ROLE_USER");
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
private static List<GrantedAuthority> getGrantedAuthorities(
|
||||
List<String> roles) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +1,43 @@
|
|||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
||||
@PropertySource("classpath:application.properties")
|
||||
public class AppConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
}
|
||||
}
|
||||
|
||||
//OCT 21
|
||||
@Bean
|
||||
public JavaMailSenderImpl javaMailSenderImpl() {
|
||||
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
|
||||
mailSenderImpl.setHost(env.getProperty("smtp.host"));
|
||||
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
|
||||
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
|
||||
mailSenderImpl.setUsername(env.getProperty("smtp.username"));
|
||||
mailSenderImpl.setPassword(env.getProperty("smtp.password"));
|
||||
Properties javaMailProps = new Properties();
|
||||
javaMailProps.put("mail.smtp.auth", true);
|
||||
javaMailProps.put("mail.smtp.starttls.enable", true);
|
||||
mailSenderImpl.setJavaMailProperties(javaMailProps);
|
||||
return mailSenderImpl;
|
||||
}
|
||||
}
|
|
@ -22,7 +22,8 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
|||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||
@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service",
|
||||
"org.baeldung.persistence.dao" })
|
||||
@EnableWebMvc
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
|
@ -38,6 +39,9 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
|||
registry.addViewController("/login.html");
|
||||
registry.addViewController("/logout.html");
|
||||
registry.addViewController("/homepage.html");
|
||||
registry.addViewController("/expiredAccount.html");
|
||||
registry.addViewController("/regitrationConfirm.html");
|
||||
registry.addViewController("/badUser.html");
|
||||
registry.addViewController("/home.html");
|
||||
registry.addViewController("/invalidSession.html");
|
||||
registry.addViewController("/console.html");
|
||||
|
|
|
@ -1,14 +1,21 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.persistence.service.UserDto;
|
||||
import org.baeldung.persistence.service.IUserService;
|
||||
import org.baeldung.validation.service.EmailExistsException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
|
@ -16,54 +23,116 @@ import org.springframework.validation.Errors;
|
|||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
public class RegistrationController {
|
||||
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
private IUserService service;
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
private IUserService service;
|
||||
@Autowired
|
||||
// OCT 21
|
||||
private MessageSource messages;
|
||||
// OCT 21
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Autowired
|
||||
public RegistrationController(IUserService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
|
||||
public String showRegistrationForm(WebRequest request, Model model) {
|
||||
LOGGER.debug("Rendering registration page.");
|
||||
UserDto userDto = new UserDto();
|
||||
model.addAttribute("user", userDto);
|
||||
return "registration";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) {
|
||||
|
||||
User registered = new User();
|
||||
if (!result.hasErrors())
|
||||
registered = createUserAccount(accountDto, result);
|
||||
if (registered == null) {
|
||||
result.rejectValue("email", "message.regError");
|
||||
}
|
||||
if (result.hasErrors()) {
|
||||
return new ModelAndView("registration", "user", accountDto);
|
||||
} else {
|
||||
|
||||
return new ModelAndView("successRegister", "user", accountDto);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private User createUserAccount(UserDto accountDto, BindingResult result) {
|
||||
User registered = null;
|
||||
try {
|
||||
registered = service.registerNewUserAccount(accountDto);
|
||||
} catch (EmailExistsException e) {
|
||||
return null;
|
||||
}
|
||||
return registered;
|
||||
@Autowired
|
||||
public RegistrationController(IUserService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
|
||||
public String showRegistrationForm(WebRequest request, Model model) {
|
||||
LOGGER.debug("Rendering registration page.");
|
||||
//Changed name to accountDto
|
||||
UserDto accountDto = new UserDto();
|
||||
model.addAttribute("user", accountDto);
|
||||
return "registration";
|
||||
}
|
||||
|
||||
// OCT 21
|
||||
// FOR EMAIL ARTICLE
|
||||
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
|
||||
public String confirmRegistration(WebRequest request, Model model,
|
||||
@RequestParam("token") String token,
|
||||
@RequestParam("email") String email) {
|
||||
System.out.println(token);
|
||||
System.out.println(email);
|
||||
//NOV 5 get user by token
|
||||
User user = service.getRegisteredUser(email);
|
||||
|
||||
if(user==null) {
|
||||
model.addAttribute("message",messages.getMessage("auth.message.invalidUser", null, request.getLocale()));
|
||||
//return "badUser";
|
||||
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 "badUser";
|
||||
return "redirect:/badUser.html?lang="+request.getLocale().getLanguage();
|
||||
}
|
||||
user.getVerificationToken().setVerified(true);
|
||||
service.verifyRegisteredUser(user);
|
||||
//return "login";
|
||||
return "redirect:/login.html?lang="+request.getLocale().getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||
public ModelAndView registerUserAccount(
|
||||
@ModelAttribute("user") @Valid UserDto accountDto,
|
||||
BindingResult result, WebRequest request, Errors errors) {
|
||||
//OCT 21
|
||||
LOGGER.debug("Registering user account with information: {}", accountDto);
|
||||
User registered = new User();
|
||||
//OCT 21
|
||||
String token = UUID.randomUUID().toString();
|
||||
accountDto.setToken(token);
|
||||
String appUrl = request.getContextPath();
|
||||
if (!result.hasErrors())
|
||||
registered = createUserAccount(accountDto, result);
|
||||
if (registered == null) {
|
||||
result.rejectValue("email", "message.regError");
|
||||
}
|
||||
if (result.hasErrors()) {
|
||||
return new ModelAndView("registration", "user", accountDto);
|
||||
} else {
|
||||
//OCT 21
|
||||
//FOR ARTICLE 2
|
||||
//System.out.println("Will be Sending mail");
|
||||
sendConfirmMail(accountDto.getEmail(), request.getLocale(), accountDto.getToken(), appUrl);
|
||||
return new ModelAndView("successRegister", "user", accountDto);
|
||||
}
|
||||
}
|
||||
|
||||
private User createUserAccount(UserDto accountDto, BindingResult result) {
|
||||
User registered = null;
|
||||
try {
|
||||
registered = service.registerNewUserAccount(accountDto);
|
||||
|
||||
} catch (EmailExistsException e) {
|
||||
return null;
|
||||
}
|
||||
return registered;
|
||||
}
|
||||
|
||||
//OCT 21
|
||||
//FOR ARTICLE 2
|
||||
private void sendConfirmMail(String address, Locale locale, String token, String appUrl){
|
||||
String recipientAddress = address;
|
||||
String subject = "Registration Confirmation";
|
||||
String confirmationUrl = appUrl + "/regitrationConfirm.html?token="+token+"&email="+address;
|
||||
String message = messages.getMessage("message.regSucc", null, locale);
|
||||
SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setTo(recipientAddress);
|
||||
email.setSubject(subject);
|
||||
email.setText(message +" \r\n"+ "http://localhost:8080"+confirmationUrl);
|
||||
mailSender.send(email);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,10 +1,17 @@
|
|||
################### DataSource Configuration ##########################
|
||||
jdbc.driverClassName=com.mysql.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/authdata?createDatabaseIfNotExist=true
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
jdbc.url=jdbc:mysql://localhost:3306/AUTHDATA
|
||||
jdbc.user=root
|
||||
###jdbc.pass=admin###
|
||||
init-db=false
|
||||
################### Hibernate Configuration ##########################
|
||||
hibernate.dialect=org.hibernate.dialect.MySQLDialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.hbm2ddl.auto=validate
|
||||
################### JavaMail Configuration ##########################
|
||||
smtp.host=smtp.gmail.com
|
||||
smtp.port=465
|
||||
smtp.protocol=smtps
|
||||
smtp.username=egmp777@gmail.com
|
||||
smtp.password=biiikupozvjvistz
|
||||
support.email=egmp777@gmail.com
|
||||
|
|
|
@ -10,6 +10,11 @@ message.regError=An account for that username/email already exists. Please enter
|
|||
message.lastName=Last name is required
|
||||
message.firstName=First name required
|
||||
message.badEmail=Invalid email address
|
||||
token.message=Your token is:
|
||||
auth.message.disabled=Your account is disabled please check your mail an click on the link to login.
|
||||
auth.message.expired=Your registration token has expired. Please register again.
|
||||
auth.message.invalidUser=This username is invalid, or does not exist.
|
||||
auth.message.invalidToken=Invalid account confirmation token. The confirmation link is not valid.
|
||||
label.user.email=Email:
|
||||
label.user.firstName=First name:
|
||||
label.user.lastName=Last name:
|
||||
|
@ -32,6 +37,7 @@ label.pages.home.message=Welcome Home
|
|||
label.pages.admin.message=Welcome Admin
|
||||
label.pages.user.message=Welcome User
|
||||
label.successRegister.title=Registration Success
|
||||
label.badUser.title=Invalid Link
|
||||
ValidEmail.user.email=Invalid email address!
|
||||
UniqueUsername.user.username=An account with that username/email already exists
|
||||
NotNull.user.firstName=First name required
|
||||
|
|
|
@ -10,6 +10,11 @@ message.regError=Ya existe una cuenta con ese nombre de usuario. Ingrese un nomb
|
|||
message.lastName=Por favor ingrese su apellido
|
||||
message.firstName=Por favor ingrese su nombre
|
||||
message.badEmail=Direccion de correo no es valida
|
||||
token.message=Su token es:
|
||||
auth.message.disabled=Su cuenta no esta habilitada. Hemos enviado a su correo un link para habilitar su cuenta.
|
||||
auth.message.expired=Su ficha de registro ha caducado, por favor registrese de nuevo.
|
||||
auth.message.invalidUser=Este nombre de usuario es invalido o no existe.
|
||||
auth.message.invalidToken=Codigo de confirmacion incorrecto.El enlace de confirmacion no es valido.
|
||||
label.user.email=Correo Electronico:
|
||||
label.user.firstName=Nombre:
|
||||
label.user.lastName=Apellido:
|
||||
|
@ -32,6 +37,7 @@ label.pages.home.message=Bienveni@ a Casa
|
|||
label.pages.admin.message=Bienvenido Admin
|
||||
label.pages.user.message=Bienvenido Usuario
|
||||
label.successRegister.title=Registro Exitoso
|
||||
label.badUser.title=Enlace Invalido
|
||||
ValidEmail.user.email=Cuenta correo invlida!
|
||||
UniqueUsername.user.username=Ya existe una cuenta con ese nombre de usuario
|
||||
NotNull.user.firstName=Por favor ingrese su nombre
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
|
||||
|
@ -10,17 +11,25 @@
|
|||
<intercept-url pattern="/signin/**" access="permitAll" />
|
||||
<intercept-url pattern="/signup/**" access="permitAll" />
|
||||
<intercept-url pattern="/user/registration*" access="permitAll" />
|
||||
<intercept-url pattern="/regitrationConfirm*" access="permitAll" />
|
||||
<intercept-url pattern="/expiredAccount*" access="permitAll" />
|
||||
<intercept-url pattern="/registration*" access="permitAll" />
|
||||
<intercept-url pattern="/badUser*" access="permitAll" />
|
||||
<intercept-url pattern="/resources/**" access="permitAll" />
|
||||
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
|
||||
<intercept-url pattern="/**" access="isAuthenticated()" />
|
||||
<form-login login-page='/login.html' authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
<form-login login-page='/login.html'
|
||||
authentication-failure-url="/login.html?error=true"
|
||||
authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
default-target-url="/homepage.html" />
|
||||
<session-management invalid-session-url="/invalidSession.html" session-fixation-protection="none" />
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID" />
|
||||
<session-management invalid-session-url="/invalidSession.html"
|
||||
session-fixation-protection="none" />
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true"
|
||||
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID" />
|
||||
</http>
|
||||
|
||||
<beans:bean id="myAuthenticationSuccessHandler" class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
|
||||
<beans:bean id="myAuthenticationSuccessHandler"
|
||||
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider user-service-ref="userDetailsService" />
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ taglib prefix="sec"
|
||||
uri="http://www.springframework.org/security/tags"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
||||
<fmt:setBundle basename="messages" />
|
||||
<%@ page session="true"%>
|
||||
<html>
|
||||
<head>
|
||||
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||
<title><spring:message
|
||||
code="label.badUser.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>
|
||||
${message}
|
||||
</h1>
|
||||
<br>
|
||||
<a href="<c:url value="/user/registration" />"><spring:message
|
||||
code="label.form.loginSignUp"></spring:message></a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,23 @@
|
|||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ taglib prefix="sec"
|
||||
uri="http://www.springframework.org/security/tags"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
||||
<fmt:setBundle basename="messages" />
|
||||
<%@ page session="true"%>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||
<title>Expired</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>
|
||||
<spring:message code="auth.message.expired"></spring:message>
|
||||
</h1>
|
||||
<br>
|
||||
<a href="<c:url value="/user/registration" />"><spring:message
|
||||
code="label.form.loginSignUp"></spring:message></a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -7,11 +7,33 @@
|
|||
<%@ page session="true"%>
|
||||
<fmt:message key="message.password" var="noPass" />
|
||||
<fmt:message key="message.username" var="noUser" />
|
||||
<c:if test="${param.error != null}">
|
||||
<c:choose>
|
||||
<c:when
|
||||
test="${SPRING_SECURITY_LAST_EXCEPTION.message == 'User is disabled'}">
|
||||
<div class="alert alert-error">
|
||||
<spring:message code="auth.message.disabled"></spring:message>
|
||||
</div>
|
||||
</c:when>
|
||||
<c:when
|
||||
test="${SPRING_SECURITY_LAST_EXCEPTION.message == 'User account has expired'}">
|
||||
<div class="alert alert-error">
|
||||
<spring:message code="auth.message.expired"></spring:message>
|
||||
</div>
|
||||
</c:when>
|
||||
<c:otherwise>
|
||||
<div class="alert alert-error">
|
||||
<!-- <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/> -->
|
||||
<spring:message code="message.badCredentials"></spring:message>
|
||||
</div>
|
||||
</c:otherwise>
|
||||
</c:choose>
|
||||
</c:if>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||
<c:if test="${param.error != null}">
|
||||
<!-- <c:if test="${param.error != null}">
|
||||
<div class="container">
|
||||
<div class="span12">
|
||||
<div class="alert alert-error">
|
||||
|
@ -19,7 +41,7 @@
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</c:if>
|
||||
</c:if> -->
|
||||
<script type="text/javascript">
|
||||
function validate() {
|
||||
if (document.f.j_username.value == ""
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<%@ taglib prefix="sec"
|
||||
uri="http://www.springframework.org/security/tags"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
||||
<fmt:setBundle basename="messages" />
|
||||
<%@ page session="true"%>
|
||||
<c:if test="${param.token != null}">
|
||||
<spring:message code="token.message"><c:out value="${param.token}"></c:out></spring:message>
|
||||
</c:if>
|
||||
<html>
|
||||
<head>
|
||||
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title>Registration Success</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<spring:message code="message.regSucc"></spring:message>
|
||||
<a href="<c:url value="login.html" />"><spring:message code="label.login"></spring:message></a>
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in New Issue