Password Encoding

XML Beans eliminated
This commit is contained in:
egmp777 2014-12-15 18:33:30 -05:00
parent 8ff5b3e538
commit 4d875ac538
51 changed files with 7825 additions and 218 deletions

View File

@ -1,6 +1,8 @@
package org.baeldung.persistence.model;
import javax.persistence.CascadeType;
//ERASE
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
@ -36,8 +38,6 @@ public class User {
this.tokenExpired = false;
}
//
public Long getId() {
return id;
}
@ -102,8 +102,6 @@ public class User {
this.tokenExpired = expired;
}
//
@Override
public int hashCode() {
final int prime = 31;

View File

@ -3,6 +3,8 @@ package org.baeldung.persistence.model;
import java.util.Calendar;
import java.sql.Date;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
@ -47,7 +49,6 @@ public class VerificationToken {
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
//
public String getToken() {
return token;

View File

@ -15,7 +15,9 @@ import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
@Component("myAuthenticationSuccessHandler")
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());

View File

@ -17,7 +17,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Service("userDetailsService")
@Transactional
public class MyUserDetailsService implements UserDetailsService {

View File

@ -1,14 +1,38 @@
package org.baeldung.spring;
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.ImportResource;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
@Configuration
@ComponentScan(basePackages = { "org.baeldung.security" })
@ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
@Autowired
UserDetailsService userDetailsService;
public SecSecurityConfig() {
super();
}
}
@Bean
public BCryptPasswordEncoder encoder() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(11);
return encoder;
}
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
}

View File

@ -19,7 +19,7 @@
<intercept-url pattern="/emailError*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
@ -29,18 +29,7 @@
<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" />
<authentication-manager>
<authentication-provider ref="authProvider"/>
</authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" /> <beans:property
name="passwordEncoder" ref="encoder" /> </beans:bean>
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService" />
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
</beans:beans>

View File

@ -0,0 +1,33 @@
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;
}
}

View File

@ -0,0 +1,46 @@
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.createVerificationTokenForUser(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);
}
}

View File

@ -0,0 +1,12 @@
package org.baeldung.hashing;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class HashGenerator {
public String getHashedPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
return hashedPassword;
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
public void delete(User user);
}

View File

@ -0,0 +1,12 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.User;
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);
public VerificationToken findByUser(User user);
}

View File

@ -0,0 +1,94 @@
package org.baeldung.persistence.model;
import javax.persistence.CascadeType;
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
@Table
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
private Integer role;
public Role() {
super();
}
public Role(Integer role) {
super();
this.role = role;
}
public Role(Integer role, User user) {
super();
this.role = role;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Role role = (Role) obj;
if (!role.equals(role.role))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Role [role=").append(role).append("]").append("[id=").append(id).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,140 @@
package org.baeldung.persistence.model;
import javax.persistence.CascadeType;
//ERASE
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.OneToOne;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
private boolean enabled;
// ERASE
@Column(name = "token_expired")
private boolean tokenExpired;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Role role;
public User() {
super();
this.enabled = false;
this.tokenExpired = false;
}
//
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 username) {
this.email = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTokenExpired() {
return tokenExpired;
}
public void setTokenExpired(boolean expired) {
this.tokenExpired = expired;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final User user = (User) obj;
if (!email.equals(user.email))
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("[username").append(email).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,132 @@
package org.baeldung.persistence.model;
import java.util.Calendar;
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;
@Entity
public class VerificationToken {
private static final int EXPIRATION = 60 * 24;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String token;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, 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);
}
//
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((expiryDate == null) ? 0 : expiryDate.hashCode());
result = prime * result + ((token == null) ? 0 : token.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VerificationToken other = (VerificationToken) obj;
if (expiryDate == null) {
if (other.expiryDate != null)
return false;
} else if (!expiryDate.equals(other.expiryDate))
return false;
if (token == null) {
if (other.token != null)
return false;
} else if (!token.equals(other.token))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Token [String=").append(token).append("]").append("[Expires").append(expiryDate).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,21 @@
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 {
User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
User getUser(String verificationToken);
void saveRegisteredUser(User user);
void deleteUser(User user);
void createVerificationTokenForUser(User user, String token);
VerificationToken getVerificationToken(String VerificationToken);
}

View File

@ -0,0 +1,88 @@
package org.baeldung.persistence.service;
import javax.validation.constraints.NotNull;
import org.baeldung.validation.service.PasswordMatches;
import org.baeldung.validation.service.ValidEmail;
import org.hibernate.validator.constraints.NotEmpty;
@PasswordMatches
public class UserDto {
@NotNull
@NotEmpty
private String firstName;
@NotNull
@NotEmpty
private String lastName;
@NotNull
@NotEmpty
private String password;
@NotNull
@NotEmpty
private String matchingPassword;
@ValidEmail
@NotNull
@NotEmpty
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private Integer role;
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
@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("]").append("[password").append(password).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,77 @@
package org.baeldung.persistence.service;
import javax.transaction.Transactional;
import org.baeldung.hashing.HashGenerator;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.dao.VerificationTokenRepository;
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;
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private UserRepository repository;
@Autowired
private VerificationTokenRepository tokenRepository;
@Autowired
private HashGenerator hashGenerator;
@Override
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
if (emailExist(accountDto.getEmail())) {
throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail());
}
User user = new User();
user.setFirstName(accountDto.getFirstName());
user.setLastName(accountDto.getLastName());
String hashedPassword = hashGenerator.getHashedPassword(accountDto.getPassword());
user.setPassword(hashedPassword);
user.setEmail(accountDto.getEmail());
user.setRole(new Role(Integer.valueOf(1), user));
return repository.save(user);
}
@Override
public User getUser(String verificationToken) {
User user = tokenRepository.findByToken(verificationToken).getUser();
return user;
}
@Override
public VerificationToken getVerificationToken(String VerificationToken) {
return tokenRepository.findByToken(VerificationToken);
}
@Override
public void saveRegisteredUser(User user) {
repository.save(user);
}
@Override
public void deleteUser(User user) {
repository.delete(user);
}
@Override
public void createVerificationTokenForUser(User user, String token) {
VerificationToken myToken = new VerificationToken(token, user);
tokenRepository.save(myToken);
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
}

View File

@ -55,7 +55,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
}
}
if (isUser) {
return "/homepage.html";
return "/homepage.html?user=" + authentication.getName();
} else if (isAdmin) {
return "/console.html";
} else {

View File

@ -0,0 +1,74 @@
package org.baeldung.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
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;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
public MyUserDetailsService() {
}
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
try {
User user = userRepository.findByEmail(email);
if (user == null) {
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
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;
}
}

View File

@ -0,0 +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.event.service", "org.baeldung.event", "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();
}
@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;
}
}

View File

@ -2,14 +2,19 @@ package org.baeldung.spring;
import java.util.Locale;
import org.baeldung.hashing.HashGenerator;
import org.baeldung.validation.service.EmailValidator;
import org.baeldung.validation.service.PasswordMatchesValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
@ -18,6 +23,7 @@ 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" })
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
@ -30,15 +36,19 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
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("/emailError.html");
registry.addViewController("/home.html");
registry.addViewController("/invalidSession.html");
registry.addViewController("/console.html");
registry.addViewController("/admin.html");
registry.addViewController("/registration.html");
registry.addViewController("/successRegister.html");
}
@Bean
@ -47,10 +57,14 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
@ -74,5 +88,24 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
messageSource.setCacheSeconds(0);
return messageSource;
}
@Bean
public EmailValidator usernameValidator() {
EmailValidator userNameValidator = new EmailValidator();
return userNameValidator;
}
@Bean
public PasswordMatchesValidator passwordMatchesValidator() {
PasswordMatchesValidator passwordMatchesValidator = new PasswordMatchesValidator();
return passwordMatchesValidator;
}
// DIC 7
@Bean
public HashGenerator hashGenerator() {
HashGenerator hashGenerator = new HashGenerator();
return hashGenerator;
}
}

View File

@ -0,0 +1,73 @@
package org.baeldung.spring;
import java.util.Properties;
import javax.sql.DataSource;
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.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:application.properties" })
@ComponentScan({ "org.baeldung.persistence.model" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig {
@Autowired
private Environment env;
public PersistenceJPAConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
}

View File

@ -10,5 +10,5 @@ public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.validation.service;
@SuppressWarnings("serial")
public class EmailExistsException extends Throwable {
public EmailExistsException(String message) {
super(message);
}
}

View File

@ -0,0 +1,28 @@
package org.baeldung.validation.service;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
@Override
public void initialize(ValidEmail constraintAnnotation) {
}
@Override
public boolean isValid(String username, ConstraintValidatorContext context) {
return (validateEmail(username));
}
private boolean validateEmail(String email) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
}

View File

@ -0,0 +1,24 @@
package org.baeldung.validation.service;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches {
String message() default "Passwords don't match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,19 @@
package org.baeldung.validation.service;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.baeldung.persistence.service.UserDto;
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {
@Override
public void initialize(PasswordMatches constraintAnnotation) {
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
UserDto user = (UserDto) obj;
return user.getPassword().equals(user.getMatchingPassword());
}
}

View File

@ -0,0 +1,23 @@
package org.baeldung.validation.service;
import org.baeldung.persistence.service.UserDto;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return UserDto.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required.");
}
}

View File

@ -0,0 +1,24 @@
package org.baeldung.validation.service;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
@Documented
public @interface ValidEmail {
String message() default "Invalid Email";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,112 @@
package org.baeldung.web.controller;
import java.util.Calendar;
import java.util.Locale;
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.event.OnRegistrationCompleteEvent;
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.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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());
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired
private JavaMailSender mailSender;
@Autowired
private ApplicationEventPublisher eventPublisher;
public RegistrationController() {
}
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
LOGGER.debug("Rendering registration page.");
UserDto accountDto = new UserDto();
model.addAttribute("user", accountDto);
return "registration";
}
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) {
Locale locale = request.getLocale();
VerificationToken verificationToken = service.getVerificationToken(token);
if (verificationToken == null) {
String message = messages.getMessage("auth.message.invalidToken", null, locale);
model.addAttribute("message", message);
return "redirect:/badUser.html?lang=" + locale.getLanguage();
}
User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
return "redirect:/badUser.html?lang=" + locale.getLanguage();
}
user.setEnabled(true);
service.saveRegisteredUser(user);
return "redirect:/login.html?lang=" + locale.getLanguage();
}
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) {
LOGGER.debug("Registering user account with information: {}", accountDto);
if (result.hasErrors()) {
return new ModelAndView("registration", "user", accountDto);
}
User registered = createUserAccount(accountDto);
if (registered == null) {
result.rejectValue("email", "message.regError");
}
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("emailError", "user", accountDto);
}
return new ModelAndView("successRegister", "user", accountDto);
}
private User createUserAccount(UserDto accountDto) {
User registered = null;
try {
registered = service.registerNewUserAccount(accountDto);
} catch (EmailExistsException e) {
return null;
}
return registered;
}
}

View File

@ -0,0 +1,17 @@
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
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=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

View File

@ -5,5 +5,51 @@ message.badCredentials=Invalid Username or Password
message.sessionExpired=Session Timed Out
message.logoutError=Sorry, error logging out
message.logoutSucc=You logged out successfully
message.regSucc=You registrated correctly, please log in
message.regError=There was a registration error please go back to registration
message.regSucc=You registered successfully. We will send you a confirmation message to your email account.
message.regError=An account for that username/email already exists. Please enter a different username.
message.lastName=Last name is required
message.firstName=First name required
message.badEmail=Invalid email address
message.email.config.error=Error in java mail configuration
token.message=Your token is:
auth.message.disabled=Your account is disabled please check your mail and click on the confirmation link
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.
label.user.email=Email:
label.user.firstName=First name:
label.user.lastName=Last name:
label.user.password=Password:
label.user.confirmPass=Confirm password
label.form.submit=Submit
label.form.title=Registration Form
label.form.loginLink=Back to login
label.login=Login here
label.form.loginTitle=Login
label.form.loginEmail=Email
label.form.loginPass=Password
label.form.loginEnglish=English
label.form.loginSpanish=Spanish
label.form.loginSignUp=Sign up
label.pages.logout=Logout
label.pages.admin=Administrator
label.pages.home.title=Home
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
NotEmpty.user.firstName=First name required
NotNull.user.lastName=Last name required
NotEmpty.user.lastName=Last name required
NotNull.user.username=Username(Email) required
NotEmpty.user.username=Username(Email) required
NotNull.user.password=Password required
NotEmpty.user.password=Password required
NotNull.user.matchingPassword=Required
NotEmpty.user.matchingPassword=Required
PasswordMatches.user:Password does not match!
Email.user.email=Invalid Username (Email)

View File

@ -3,7 +3,53 @@ message.password=Por favor ingrese una clave
message.unauth=Acceso denegado !!
message.badCredentials=Usuario o clave invalida
message.sessionExpired=La sesion expiro
message.logoutError=Lo sentimos, hubo problemas en logout
message.logoutSucc=Logout con exito
message.regSucc=Se registro correctamente, por favor ingrese
message.regError=Hubo un error, por favor vuelva a registrarse
message.logoutError=Lo sentimos, hubo problemas al salir
message.logoutSucc=Salida con exito
message.regSucc=Se registro correctamente. Le enviaremos un mensaje de confirmacion a su direccion de email.
message.regError=Ya existe una cuenta con ese nombre de usuario. Ingrese un nombre de usuario diferente.
message.lastName=Por favor ingrese su apellido
message.firstName=Por favor ingrese su nombre
message.badEmail=Direccion de correo no es valida
message.email.config.error=Error en configuracion de java mail
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.
label.user.email=Correo Electronico:
label.user.firstName=Nombre:
label.user.lastName=Apellido:
label.user.password=Contrasenia:
label.user.confirmPass=Confirme la contrasenia
label.form.submit=Enviar
label.form.title=Formulario de Registro
label.login=Autehtifiquese aqui
label.form.loginTitle=Ingreso
label.form.loginLink=Regrese a autentificacion
label.form.loginEmail=Correo Electronico
label.form.loginPass=Contrasenia
label.form.loginEnglish=Ingles
label.form.loginSpanish=Espaniol
label.form.loginSignUp=Registrese
label.pages.logout=Salir
label.pages.admin=Administrador
label.pages.home.title=Inicio
label.pages.home.message=Bienveni@ a Casa
label.pages.admin.message=Bienvenid@ Admin
label.pages.user.message=Bienvenid@ Usuari@
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
NotEmpty.user.firstName=Por favor ingrese su nombre
NotNull.user.lastName=Por favor ingrese su apellido
NotEmpty.user.lastName=Por favor ingrese su apellido
NotNull.user.username=Por favor ingrese su cuenta de email
NotEmpty.user.username=Por favor ingrese su cuenta de email
NotNull.user.password=Por favor ingrese su clave
NotEmpty.user.password=Por favor ingrese su contraseña
NotNull.user.matchingPassword=Campo obligatirio
NotEmpty.user.matchingPassword=Campo obligatrio
PasswordMatches.user:Las claves no coinciden!
Email.user.email=Email no es valido

View File

@ -5,12 +5,18 @@
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http use-expressions="true">
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/logout*" access="permitAll" />
<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="/emailError*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
@ -20,17 +26,21 @@
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=1"
<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" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
<authentication-provider ref="authProvider"/>
</authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" /> <beans:property
name="passwordEncoder" ref="encoder" /> </beans:bean>
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService" />
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
</beans:beans>

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

View File

@ -1,10 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

View File

@ -1,23 +1,29 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<sec:authorize ifAnyGranted="ROLE_USER">
<spring:message code="message.unauth" ></spring:message>
</sec:authorize>
<head></head>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<head></head>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<H1> Hello Admin</H1>
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
<div class="container">
<div class="span12">
<sec:authorize ifAnyGranted="ROLE_USER">
<spring:message code="message.unauth"></spring:message>
</sec:authorize>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<H1>
<spring:message code="label.pages.admin.message"></spring:message>
</H1>
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />"><spring:message
code="label.pages.logout"></spring:message></a> <a
href="<c:url value="/home.html" />"><spring:message
code="label.pages.home.title"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@ 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>
<div class="alert alert-error">
${param.message}
</h1>
<br>
<a href="<c:url value="/user/registration" />"><spring:message
code="label.form.loginSignUp"></spring:message></a>
</body>
</html>

View File

@ -1,23 +1,29 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head></head>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
</head>
<body>
<h1>This is the landing page for the admin</h1>
<security:authorize access="hasRole('ROLE_USER')">
<div class="container">
<div class="span12">
<h1>This is the landing page for the admin</h1>
<sec:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br/>
</security:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
<br />
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />"><spring:message
code="label.pages.logout"></spring:message></a> <a
href="<c:url value="/admin.html" />"><spring:message
code="label.pages.admin"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,19 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<div class="container">
<div class="span12">
<h1 class="alert alert-error">
<spring:message code="message.email.config.error"></spring:message>
</h1>
</div>
</div>
</body>
</html>

View File

@ -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.pages.home.title"></spring:message></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>

View File

@ -1,13 +0,0 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Welcome back home!
</h1>
</body>
</html>

View File

@ -1,28 +0,0 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page session="true" %>
<html>
<head></head>
<body>
<body>
<h1>This is the homepage for the user</h1>
<sec:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br />
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</body>
</html>

View File

@ -1,12 +1,20 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>Home</title>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<h1>
<spring:message code="message.sessionExpired" ></spring:message>
</h1>
<div class="container">
<div class="span12">
<h1 class="alert alert-error">
<spring:message code="message.sessionExpired"></spring:message>
</h1>
<a href="<c:url value="login.html" />"><spring:message
code="label.form.loginLink"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -4,29 +4,36 @@
<%@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="false"%>
<c:if test="${param.error != null}">
<div id="error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
</div>
<a href="registration.html">Register</a>
</c:if>
<%@ 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>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""
@ -40,7 +47,6 @@
document.f.j_username.focus();
return false;
}
if (document.f.j_password.value == "") {
alert("${noPass}");
document.f.j_password.focus();
@ -49,29 +55,40 @@
}
</script>
</head>
<body>
<h1>Login</h1>
<a href="?lang=en">English</a> |
<a href="?lang=es_ES">Spanish</a>
<form name='f' action="j_spring_security_check" method='POST'
onsubmit="return validate();">
<div class="container">
<div class="span12">
<h1>
<spring:message code="label.form.loginTitle"></spring:message>
</h1>
<a href="?lang=en"><spring:message code="label.form.loginEnglish"></spring:message></a>
| <a href="?lang=es_ES"><spring:message
code="label.form.loginSpanish"></spring:message></a>
<form name='f' action="j_spring_security_check" method='POST'
onsubmit="return validate();">
<table>
<tr>
<td><label><spring:message
code="label.form.loginEmail"></spring:message></label></td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td><label><spring:message
code="label.form.loginPass"></spring:message></label></td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit"
value=<spring:message code="label.form.submit"></spring:message> /></td>
</tr>
</table>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
<br> Current Locale : ${pageContext.response.locale}
</form>
<br> Current Locale : ${pageContext.response.locale} <br> <a
href="<c:url value="/user/registration" />"><spring:message
code="label.form.loginSignUp"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -2,23 +2,31 @@
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<div id="error">
<spring:message code="message.logoutError"></spring:message>
</div>
</c:if>
<c:if test="${param.logSucc == 1}">
<div id="success">
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<a href="login.html">Login</a>
<div class="container">
<div class="span12">
<c:if test="${param.logSucc == true}">
<div id="success">
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<a href="<c:url value="login.html" />"><spring:message
code="label.form.loginLink"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -1,12 +1,64 @@
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@ page session="false"%>
<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</title>
<title><spring:message code="label.form.title"></spring:message></title>
</head>
<body>
<H1> This is the registration page</H1>
<div class="container">
<div class="span12">
<H1>
<spring:message code="label.form.title"></spring:message>
</H1>
<form:form modelAttribute="user" method="POST" enctype="utf8">
<br>
<tr>
<td><label><spring:message code="label.user.firstName"></spring:message></label></td>
<td><form:input path="firstName" value="" /></td>
<form:errors path="firstName" cssClass="alert alert-error"
element="div" />
</tr>
<tr>
<td><label><spring:message code="label.user.lastName"></spring:message></label></td>
<td><form:input path="lastName" value="" /></td>
<form:errors path="lastName" cssClass="alert alert-error"
element="div" />
</tr>
<tr>
<td><label><spring:message code="label.user.email"></spring:message></label></td>
<td><form:input path="email" value="" /></td>
<form:errors path="email" cssClass="alert alert-error"
element="div" />
</tr>
<tr>
<td><label><spring:message code="label.user.password"></spring:message></label></td>
<td><form:input path="password" value="" type="password" /></td>
<form:errors path="password" cssClass="alert alert-error"
element="div" />
</tr>
<tr>
<td><label><spring:message
code="label.user.confirmPass"></spring:message></label></td>
<td><form:input path="matchingPassword" value=""
type="password" /></td>
<form:errors cssClass="alert alert-error" element="div" />
</tr>
<button type="submit">
<spring:message code="label.form.submit"></spring:message>
</button>
</form:form>
<br> <a href="<c:url value="login.html" />"><spring:message
code="label.form.loginLink"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -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><spring:message code="label.pages.home.title"></spring:message></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>

View File

@ -0,0 +1,27 @@
<%@ 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"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<div class="container">
<div class="span12">
<div id="success">
<spring:message code="message.regSucc"></spring:message>
</div>
<a href="<c:url value="login.html" />"><spring:message
code="label.login"></spring:message></a>
</div>
</div>
</body>
</html>

View File

@ -1,41 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextClass</param-name>
<param-value>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

6167
src/main/webapp/resources/bootstrap.css vendored Normal file

File diff suppressed because it is too large Load Diff