moving registration code
This commit is contained in:
parent
3a901e0d56
commit
c8a84157fb
|
@ -1,32 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
|
@ -1,55 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>spring-security-login-and-registration</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
|
||||
<triggers>full,incremental,</triggers>
|
||||
<arguments>
|
||||
<dictionary>
|
||||
<key>LaunchConfigHandle</key>
|
||||
<value><project>/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch</value>
|
||||
</dictionary>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.common.project.facet.core.builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.validation.validationbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
||||
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
|
||||
<nature>org.springframework.ide.eclipse.core.springnature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
||||
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
||||
<nature>org.hibernate.eclipse.console.hibernateNature</nature>
|
||||
<nature>org.jboss.tools.jst.web.kb.kbnature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
|
@ -1,15 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.5.1.201404300732-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[true]]></enableImports>
|
||||
<configs>
|
||||
</configs>
|
||||
<autoconfigs>
|
||||
</autoconfigs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
|
@ -1,37 +0,0 @@
|
|||
=========
|
||||
|
||||
## Login and Registration Example Project with Spring Security
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Registration Tutorial](http://www.baeldung.com/spring-security-registration)
|
||||
- [The Registration Process With Spring Security](http://www.baeldung.com/registration-with-spring-mvc-and-spring-security)
|
||||
- [Registration – Activate a New Account by Email](http://www.baeldung.com/registration-verify-user-by-email)
|
||||
- [Registration with Spring Security – Password Encoding](http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt)
|
||||
- [Spring Security – Roles and Privileges](http://www.baeldung.com/role-and-privilege-for-spring-security-registration)
|
||||
- [Prevent Brute Force Authentication Attempts with Spring Security](http://www.baeldung.com/spring-security-block-brute-force-authentication-attempts)
|
||||
- [Spring Security – Reset Your Password](http://www.baeldung.com/spring-security-registration-i-forgot-my-password)
|
||||
- [Spring Security Registration – Resend Verification Email](http://www.baeldung.com/spring-security-registration-verification-email)
|
||||
- [The Registration API becomes RESTful](http://www.baeldung.com/registration-restful-api)
|
||||
- [Registration – Password Strength and Rules](http://www.baeldung.com/registration-password-strength-and-rules)
|
||||
- [Updating your Password](http://www.baeldung.com/updating-your-password/)
|
||||
|
||||
### Build the Project
|
||||
```
|
||||
mvn clean install
|
||||
```
|
||||
|
||||
|
||||
### Set up MySQL
|
||||
```
|
||||
mysql -u root -p
|
||||
> CREATE USER 'tutorialuser'@'localhost' IDENTIFIED BY 'tutorialmy5ql';
|
||||
> GRANT ALL PRIVILEGES ON *.* TO 'tutorialuser'@'localhost';
|
||||
> FLUSH PRIVILEGES;
|
||||
```
|
||||
|
||||
|
||||
### Set up Email
|
||||
|
||||
You need to configure the email by renaming file "email.properties.sample" to "email.properties" and provide your own username and password.
|
||||
You also need to use your own host, you can use Amazon or Google for example.
|
|
@ -1,354 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>spring-security-login-and-registration</artifactId>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>spring-security-login-and-registration</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Spring Security -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Servlet -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Password Validation -->
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>${passay.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Data JPA dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data-jpa.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<!-- <dependency> -->
|
||||
<!-- <groupId>xml-apis</groupId> -->
|
||||
<!-- <artifactId>xml-apis</artifactId> -->
|
||||
<!-- <version>1.4.01</version> -->
|
||||
<!-- </dependency> -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- DB dependencies -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql-connector-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-dbcp</groupId>
|
||||
<artifactId>commons-dbcp</artifactId>
|
||||
<version>${commons-dbcp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>el-api</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-security-login-and-registration</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<wait>true</wait>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java-version>1.8</java-version>
|
||||
|
||||
<!-- spring -->
|
||||
<org.springframework.version>4.2.4.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.3.RELEASE</org.springframework.security.version>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<mysql-connector-java.version>5.1.37</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
|
||||
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- javax jsp -->
|
||||
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
|
||||
<javax.servlet.version>3.0.1</javax.servlet.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
|
||||
<!-- Inject -->
|
||||
<javax.inject.version>1</javax.inject.version>
|
||||
|
||||
<!-- Spring Data Jpa -->
|
||||
<spring-data-jpa.version>1.8.2.RELEASE</spring-data-jpa.version>
|
||||
|
||||
<!-- guava -->
|
||||
<guava.version>19.0</guava.version>
|
||||
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<passay.version>1.0</passay.version>
|
||||
<rest-assured.version>2.4.0</rest-assured.version>
|
||||
<javax.mail.version>1.4.7</javax.mail.version>
|
||||
<jackson.version>2.6.4</jackson.version>
|
||||
<commons-dbcp.version>1.4</commons-dbcp.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.4.17</cargo-maven2-plugin.version>
|
||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,13 +0,0 @@
|
|||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.PasswordResetToken;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
|
||||
|
||||
PasswordResetToken findByToken(String token);
|
||||
|
||||
PasswordResetToken findByUser(User user);
|
||||
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.Privilege;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {
|
||||
|
||||
Privilege findByName(String name);
|
||||
|
||||
@Override
|
||||
void delete(Privilege privilege);
|
||||
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface RoleRepository extends JpaRepository<Role, Long> {
|
||||
|
||||
Role findByName(String name);
|
||||
|
||||
@Override
|
||||
void delete(Role role);
|
||||
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
package org.baeldung.persistence.dao;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
User findByEmail(String email);
|
||||
|
||||
@Override
|
||||
void delete(User user);
|
||||
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
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> {
|
||||
|
||||
VerificationToken findByToken(String token);
|
||||
|
||||
VerificationToken findByUser(User user);
|
||||
|
||||
}
|
|
@ -1,143 +0,0 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
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 PasswordResetToken {
|
||||
|
||||
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;
|
||||
|
||||
private Date expiryDate;
|
||||
|
||||
public PasswordResetToken() {
|
||||
super();
|
||||
}
|
||||
|
||||
public PasswordResetToken(final String token) {
|
||||
super();
|
||||
|
||||
this.token = token;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
public PasswordResetToken(final String token, final User user) {
|
||||
super();
|
||||
|
||||
this.token = token;
|
||||
this.user = user;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(final String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(final User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getExpiryDate() {
|
||||
return expiryDate;
|
||||
}
|
||||
|
||||
public void setExpiryDate(final Date expiryDate) {
|
||||
this.expiryDate = expiryDate;
|
||||
}
|
||||
|
||||
private Date calculateExpiryDate(final int expiryTimeInMinutes) {
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
cal.setTimeInMillis(new Date().getTime());
|
||||
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
|
||||
return new Date(cal.getTime().getTime());
|
||||
}
|
||||
|
||||
public void updateToken(final String token) {
|
||||
this.token = token;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@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(final Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final PasswordResetToken other = (PasswordResetToken) 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,90 +0,0 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToMany;
|
||||
|
||||
@Entity
|
||||
public class Privilege {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "privileges")
|
||||
private Collection<Role> roles;
|
||||
|
||||
public Privilege() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Privilege(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Collection<Role> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(final Collection<Role> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.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 Privilege privilege = (Privilege) obj;
|
||||
if (!privilege.equals(privilege.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
|
@ -1,104 +0,0 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinTable;
|
||||
import javax.persistence.ManyToMany;
|
||||
|
||||
@Entity
|
||||
public class Role {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToMany(mappedBy = "roles")
|
||||
private Collection<User> users;
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id") )
|
||||
private Collection<Privilege> privileges;
|
||||
|
||||
private String name;
|
||||
|
||||
public Role() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Role(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Collection<User> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public void setUsers(final Collection<User> users) {
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
public Collection<Privilege> getPrivileges() {
|
||||
return privileges;
|
||||
}
|
||||
|
||||
public void setPrivileges(final Collection<Privilege> privileges) {
|
||||
this.privileges = privileges;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.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.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
|
@ -1,143 +0,0 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinTable;
|
||||
import javax.persistence.ManyToMany;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String email;
|
||||
|
||||
@Column(length = 60)
|
||||
private String password;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private boolean tokenExpired;
|
||||
|
||||
//
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") )
|
||||
private Collection<Role> roles;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
this.enabled = false;
|
||||
this.tokenExpired = false;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(final String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(final String username) {
|
||||
this.email = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(final String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Collection<Role> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(final Collection<Role> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(final boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean isTokenExpired() {
|
||||
return tokenExpired;
|
||||
}
|
||||
|
||||
public void setTokenExpired(final 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,141 +0,0 @@
|
|||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
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;
|
||||
|
||||
private Date expiryDate;
|
||||
|
||||
public VerificationToken() {
|
||||
super();
|
||||
}
|
||||
|
||||
public VerificationToken(final String token) {
|
||||
super();
|
||||
|
||||
this.token = token;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
public VerificationToken(final String token, final User user) {
|
||||
super();
|
||||
|
||||
this.token = token;
|
||||
this.user = user;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(final String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(final User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getExpiryDate() {
|
||||
return expiryDate;
|
||||
}
|
||||
|
||||
public void setExpiryDate(final Date expiryDate) {
|
||||
this.expiryDate = expiryDate;
|
||||
}
|
||||
|
||||
private Date calculateExpiryDate(final int expiryTimeInMinutes) {
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
cal.setTimeInMillis(new Date().getTime());
|
||||
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
|
||||
return new Date(cal.getTime().getTime());
|
||||
}
|
||||
|
||||
public void updateToken(final String token) {
|
||||
this.token = token;
|
||||
this.expiryDate = calculateExpiryDate(EXPIRATION);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@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(final Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import org.baeldung.persistence.model.PasswordResetToken;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.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);
|
||||
|
||||
VerificationToken generateNewVerificationToken(String token);
|
||||
|
||||
void createPasswordResetTokenForUser(User user, String token);
|
||||
|
||||
User findUserByEmail(String email);
|
||||
|
||||
PasswordResetToken getPasswordResetToken(String token);
|
||||
|
||||
User getUserByPasswordResetToken(String token);
|
||||
|
||||
User getUserByID(long id);
|
||||
|
||||
void changeUserPassword(User user, String password);
|
||||
|
||||
boolean checkIfValidOldPassword(User user, String password);
|
||||
|
||||
}
|
|
@ -1,88 +0,0 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import org.baeldung.validation.PasswordMatches;
|
||||
import org.baeldung.validation.ValidEmail;
|
||||
import org.baeldung.validation.ValidPassword;
|
||||
|
||||
@PasswordMatches
|
||||
public class UserDto {
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
private String firstName;
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
private String lastName;
|
||||
|
||||
@ValidPassword
|
||||
private String password;
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
private String matchingPassword;
|
||||
|
||||
@ValidEmail
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
private String email;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(final String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
private Integer role;
|
||||
|
||||
public Integer getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(final Integer role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(final String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(final String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getMatchingPassword() {
|
||||
return matchingPassword;
|
||||
}
|
||||
|
||||
public void setMatchingPassword(final 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();
|
||||
}
|
||||
}
|
|
@ -1,136 +0,0 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.baeldung.persistence.dao.PasswordResetTokenRepository;
|
||||
import org.baeldung.persistence.dao.RoleRepository;
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.dao.VerificationTokenRepository;
|
||||
import org.baeldung.persistence.model.PasswordResetToken;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.validation.EmailExistsException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService implements IUserService {
|
||||
@Autowired
|
||||
private UserRepository repository;
|
||||
|
||||
@Autowired
|
||||
private VerificationTokenRepository tokenRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordResetTokenRepository passwordTokenRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public User registerNewUserAccount(final UserDto accountDto) throws EmailExistsException {
|
||||
if (emailExist(accountDto.getEmail())) {
|
||||
throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail());
|
||||
}
|
||||
final User user = new User();
|
||||
|
||||
user.setFirstName(accountDto.getFirstName());
|
||||
user.setLastName(accountDto.getLastName());
|
||||
user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
|
||||
user.setEmail(accountDto.getEmail());
|
||||
|
||||
user.setRoles(Arrays.asList(roleRepository.findByName("ROLE_USER")));
|
||||
return repository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUser(final String verificationToken) {
|
||||
final User user = tokenRepository.findByToken(verificationToken).getUser();
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VerificationToken getVerificationToken(final String VerificationToken) {
|
||||
return tokenRepository.findByToken(VerificationToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveRegisteredUser(final User user) {
|
||||
repository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteUser(final User user) {
|
||||
repository.delete(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createVerificationTokenForUser(final User user, final String token) {
|
||||
final VerificationToken myToken = new VerificationToken(token, user);
|
||||
tokenRepository.save(myToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VerificationToken generateNewVerificationToken(final String existingVerificationToken) {
|
||||
VerificationToken vToken = tokenRepository.findByToken(existingVerificationToken);
|
||||
vToken.updateToken(UUID.randomUUID().toString());
|
||||
vToken = tokenRepository.save(vToken);
|
||||
return vToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createPasswordResetTokenForUser(final User user, final String token) {
|
||||
final PasswordResetToken myToken = new PasswordResetToken(token, user);
|
||||
passwordTokenRepository.save(myToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User findUserByEmail(final String email) {
|
||||
return repository.findByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PasswordResetToken getPasswordResetToken(final String token) {
|
||||
return passwordTokenRepository.findByToken(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUserByPasswordResetToken(final String token) {
|
||||
return passwordTokenRepository.findByToken(token).getUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUserByID(final long id) {
|
||||
return repository.findOne(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void changeUserPassword(final User user, final String password) {
|
||||
user.setPassword(passwordEncoder.encode(password));
|
||||
repository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkIfValidOldPassword(final User user, final String oldPassword) {
|
||||
return passwordEncoder.matches(oldPassword, user.getPassword());
|
||||
}
|
||||
|
||||
private boolean emailExist(final String email) {
|
||||
final User user = repository.findByEmail(email);
|
||||
if (user != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
package org.baeldung.registration;
|
||||
|
||||
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(final User user, final Locale locale, final String appUrl) {
|
||||
super(user);
|
||||
this.user = user;
|
||||
this.locale = locale;
|
||||
this.appUrl = appUrl;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public String getAppUrl() {
|
||||
return appUrl;
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return locale;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,61 +0,0 @@
|
|||
package org.baeldung.registration.listener;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.service.IUserService;
|
||||
import org.baeldung.registration.OnRegistrationCompleteEvent;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.core.env.Environment;
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(final OnRegistrationCompleteEvent event) {
|
||||
this.confirmRegistration(event);
|
||||
}
|
||||
|
||||
private void confirmRegistration(final OnRegistrationCompleteEvent event) {
|
||||
final User user = event.getUser();
|
||||
final String token = UUID.randomUUID().toString();
|
||||
service.createVerificationTokenForUser(user, token);
|
||||
|
||||
final SimpleMailMessage email = constructEmailMessage(event, user, token);
|
||||
mailSender.send(email);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private final SimpleMailMessage constructEmailMessage(final OnRegistrationCompleteEvent event, final User user, final String token) {
|
||||
final String recipientAddress = user.getEmail();
|
||||
final String subject = "Registration Confirmation";
|
||||
final String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;
|
||||
final String message = messages.getMessage("message.regSucc", null, event.getLocale());
|
||||
final SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setTo(recipientAddress);
|
||||
email.setSubject(subject);
|
||||
email.setText(message + " \r\n" + confirmationUrl);
|
||||
email.setFrom(env.getProperty("support.email"));
|
||||
return email;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
|
||||
|
||||
@Autowired
|
||||
private LoginAttemptService loginAttemptService;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent e) {
|
||||
final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
|
||||
if (auth != null) {
|
||||
loginAttemptService.loginFailed(auth.getRemoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
|
||||
|
||||
@Autowired
|
||||
private LoginAttemptService loginAttemptService;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(final AuthenticationSuccessEvent e) {
|
||||
final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
|
||||
if (auth != null) {
|
||||
loginAttemptService.loginSucceeded(auth.getRemoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
@Component("authenticationFailureHandler")
|
||||
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
|
||||
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
@Autowired
|
||||
private LocaleResolver localeResolver;
|
||||
|
||||
@Override
|
||||
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException {
|
||||
setDefaultFailureUrl("/login.html?error=true");
|
||||
|
||||
super.onAuthenticationFailure(request, response, exception);
|
||||
|
||||
final Locale locale = localeResolver.resolveLocale(request);
|
||||
|
||||
String errorMessage = messages.getMessage("message.badCredentials", null, locale);
|
||||
|
||||
if (exception.getMessage().equalsIgnoreCase("User is disabled")) {
|
||||
errorMessage = messages.getMessage("auth.message.disabled", null, locale);
|
||||
} else if (exception.getMessage().equalsIgnoreCase("User account has expired")) {
|
||||
errorMessage = messages.getMessage("auth.message.expired", null, locale);
|
||||
} else if (exception.getMessage().equalsIgnoreCase("blocked")) {
|
||||
errorMessage = messages.getMessage("auth.message.blocked", null, locale);
|
||||
}
|
||||
|
||||
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
|
||||
}
|
||||
}
|
|
@ -1,52 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
@Service
|
||||
public class LoginAttemptService {
|
||||
|
||||
private final int MAX_ATTEMPT = 10;
|
||||
private LoadingCache<String, Integer> attemptsCache;
|
||||
|
||||
public LoginAttemptService() {
|
||||
super();
|
||||
attemptsCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() {
|
||||
@Override
|
||||
public Integer load(final String key) {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public void loginSucceeded(final String key) {
|
||||
attemptsCache.invalidate(key);
|
||||
}
|
||||
|
||||
public void loginFailed(final String key) {
|
||||
int attempts = 0;
|
||||
try {
|
||||
attempts = attemptsCache.get(key);
|
||||
} catch (final ExecutionException e) {
|
||||
attempts = 0;
|
||||
}
|
||||
attempts++;
|
||||
attemptsCache.put(key, attempts);
|
||||
}
|
||||
|
||||
public boolean isBlocked(final String key) {
|
||||
try {
|
||||
return attemptsCache.get(key) >= MAX_ATTEMPT;
|
||||
} catch (final ExecutionException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
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());
|
||||
|
||||
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
|
||||
handle(request, response, authentication);
|
||||
final HttpSession session = request.getSession(false);
|
||||
if (session != null) {
|
||||
session.setMaxInactiveInterval(30 * 60);
|
||||
}
|
||||
clearAuthenticationAttributes(request);
|
||||
}
|
||||
|
||||
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
|
||||
final String targetUrl = determineTargetUrl(authentication);
|
||||
|
||||
if (response.isCommitted()) {
|
||||
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
redirectStrategy.sendRedirect(request, response, targetUrl);
|
||||
}
|
||||
|
||||
protected String determineTargetUrl(final Authentication authentication) {
|
||||
boolean isUser = false;
|
||||
boolean isAdmin = false;
|
||||
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
|
||||
for (final GrantedAuthority grantedAuthority : authorities) {
|
||||
if (grantedAuthority.getAuthority().equals("READ_PRIVILEGE")) {
|
||||
isUser = true;
|
||||
} else if (grantedAuthority.getAuthority().equals("WRITE_PRIVILEGE")) {
|
||||
isAdmin = true;
|
||||
isUser = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isUser) {
|
||||
return "/homepage.html?user=" + authentication.getName();
|
||||
} else if (isAdmin) {
|
||||
return "/console.html";
|
||||
} else {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
protected void clearAuthenticationAttributes(final HttpServletRequest request) {
|
||||
final HttpSession session = request.getSession(false);
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
|
||||
}
|
||||
|
||||
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
|
||||
this.redirectStrategy = redirectStrategy;
|
||||
}
|
||||
|
||||
protected RedirectStrategy getRedirectStrategy() {
|
||||
return redirectStrategy;
|
||||
}
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
package org.baeldung.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.Privilege;
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service("userDetailsService")
|
||||
@Transactional
|
||||
public class MyUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private LoginAttemptService loginAttemptService;
|
||||
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
public MyUserDetailsService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
|
||||
final String ip = getClientIP();
|
||||
if (loginAttemptService.isBlocked(ip)) {
|
||||
throw new RuntimeException("blocked");
|
||||
}
|
||||
|
||||
try {
|
||||
final User user = userRepository.findByEmail(email);
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException("No user found with username: " + email);
|
||||
}
|
||||
|
||||
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles()));
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
public final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Role> roles) {
|
||||
return getGrantedAuthorities(getPrivileges(roles));
|
||||
}
|
||||
|
||||
private final List<String> getPrivileges(final Collection<Role> roles) {
|
||||
final List<String> privileges = new ArrayList<String>();
|
||||
final List<Privilege> collection = new ArrayList<Privilege>();
|
||||
for (final Role role : roles) {
|
||||
collection.addAll(role.getPrivileges());
|
||||
}
|
||||
for (final Privilege item : collection) {
|
||||
privileges.add(item.getName());
|
||||
}
|
||||
return privileges;
|
||||
}
|
||||
|
||||
private final List<GrantedAuthority> getGrantedAuthorities(final List<String> privileges) {
|
||||
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (final String privilege : privileges) {
|
||||
authorities.add(new SimpleGrantedAuthority(privilege));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
|
||||
private String getClientIP() {
|
||||
final String xfHeader = request.getHeader("X-Forwarded-For");
|
||||
if (xfHeader == null) {
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
return xfHeader.split(",")[0];
|
||||
}
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
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.PropertySource;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.registration" })
|
||||
@PropertySource("classpath:email.properties")
|
||||
public class AppConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JavaMailSenderImpl javaMailSenderImpl() {
|
||||
final 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"));
|
||||
final Properties javaMailProps = new Properties();
|
||||
javaMailProps.put("mail.smtp.auth", true);
|
||||
javaMailProps.put("mail.smtp.starttls.enable", true);
|
||||
mailSenderImpl.setJavaMailProperties(javaMailProps);
|
||||
return mailSenderImpl;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,105 +0,0 @@
|
|||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.baeldung.validation.EmailValidator;
|
||||
import org.baeldung.validation.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;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.web" })
|
||||
@EnableWebMvc
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public MvcConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/login");
|
||||
registry.addViewController("/registration.html");
|
||||
registry.addViewController("/logout.html");
|
||||
registry.addViewController("/homepage.html");
|
||||
registry.addViewController("/expiredAccount.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("/successRegister.html");
|
||||
registry.addViewController("/forgetPassword.html");
|
||||
registry.addViewController("/updatePassword.html");
|
||||
registry.addViewController("/changePassword.html");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(final InterceptorRegistry registry) {
|
||||
final LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||
localeChangeInterceptor.setParamName("lang");
|
||||
registry.addInterceptor(localeChangeInterceptor);
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setViewClass(JstlView.class);
|
||||
bean.setPrefix("/WEB-INF/view/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
|
||||
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
|
||||
return cookieLocaleResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
|
||||
messageSource.setBasename("classpath:messages");
|
||||
messageSource.setUseCodeAsDefaultMessage(true);
|
||||
messageSource.setDefaultEncoding("UTF-8");
|
||||
messageSource.setCacheSeconds(0);
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EmailValidator usernameValidator() {
|
||||
return new EmailValidator();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordMatchesValidator passwordMatchesValidator() {
|
||||
return new PasswordMatchesValidator();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
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:persistence.properties" })
|
||||
@ComponentScan({ "org.baeldung.persistence" })
|
||||
@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() {
|
||||
final 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,96 +0,0 @@
|
|||
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.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "org.baeldung.security" })
|
||||
// @ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
@EnableWebSecurity
|
||||
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationSuccessHandler myAuthenticationSuccessHandler;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationFailureHandler authenticationFailureHandler;
|
||||
|
||||
public SecSecurityConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.authenticationProvider(authProvider());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final WebSecurity web) throws Exception {
|
||||
web.ignoring().antMatchers("/resources/**");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(final HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/login*","/login*", "/logout*", "/signin/**", "/signup/**",
|
||||
"/user/registration*", "/regitrationConfirm*", "/expiredAccount*", "/registration*",
|
||||
"/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*",
|
||||
"/user/changePassword*", "/emailError*", "/resources/**","/old/user/registration*","/successRegister*").permitAll()
|
||||
.antMatchers("/invalidSession*").anonymous()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/login")
|
||||
.defaultSuccessUrl("/homepage.html")
|
||||
.failureUrl("/login?error=true")
|
||||
.successHandler(myAuthenticationSuccessHandler)
|
||||
.failureHandler(authenticationFailureHandler)
|
||||
.permitAll()
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.invalidSessionUrl("/invalidSession.html")
|
||||
.sessionFixation().none()
|
||||
.and()
|
||||
.logout()
|
||||
.invalidateHttpSession(false)
|
||||
.logoutSuccessUrl("/logout.html?logSucc=true")
|
||||
.deleteCookies("JSESSIONID")
|
||||
.permitAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public DaoAuthenticationProvider authProvider() {
|
||||
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(encoder());
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder encoder() {
|
||||
return new BCryptPasswordEncoder(11);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,89 +0,0 @@
|
|||
package org.baeldung.spring;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.persistence.dao.PrivilegeRepository;
|
||||
import org.baeldung.persistence.dao.RoleRepository;
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.Privilege;
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Component
|
||||
public class SetupDataLoader implements ApplicationListener<ContextRefreshedEvent> {
|
||||
|
||||
private boolean alreadySetup = false;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
@Autowired
|
||||
private PrivilegeRepository privilegeRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void onApplicationEvent(final ContextRefreshedEvent event) {
|
||||
if (alreadySetup) {
|
||||
return;
|
||||
}
|
||||
|
||||
// == create initial privileges
|
||||
final Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE");
|
||||
final Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE");
|
||||
|
||||
// == create initial roles
|
||||
final List<Privilege> adminPrivileges = Arrays.asList(readPrivilege, writePrivilege);
|
||||
createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
|
||||
createRoleIfNotFound("ROLE_USER", Arrays.asList(readPrivilege));
|
||||
|
||||
final Role adminRole = roleRepository.findByName("ROLE_ADMIN");
|
||||
final User user = new User();
|
||||
user.setFirstName("Test");
|
||||
user.setLastName("Test");
|
||||
user.setPassword(passwordEncoder.encode("test"));
|
||||
user.setEmail("test@test.com");
|
||||
user.setRoles(Arrays.asList(adminRole));
|
||||
user.setEnabled(true);
|
||||
userRepository.save(user);
|
||||
|
||||
alreadySetup = true;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
private final Privilege createPrivilegeIfNotFound(final String name) {
|
||||
Privilege privilege = privilegeRepository.findByName(name);
|
||||
if (privilege == null) {
|
||||
privilege = new Privilege(name);
|
||||
privilegeRepository.save(privilege);
|
||||
}
|
||||
return privilege;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
private final Role createRoleIfNotFound(final String name, final Collection<Privilege> privileges) {
|
||||
Role role = roleRepository.findByName(name);
|
||||
if (role == null) {
|
||||
role = new Role(name);
|
||||
role.setPrivileges(privileges);
|
||||
roleRepository.save(role);
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
package org.baeldung.test;
|
||||
|
||||
import org.baeldung.spring.PersistenceJPAConfig;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@ComponentScan({ "org.baeldung.persistence.dao" })
|
||||
public class TestConfig extends PersistenceJPAConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder encoder() {
|
||||
return new BCryptPasswordEncoder(11);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class EmailExistsException extends Throwable {
|
||||
|
||||
public EmailExistsException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,28 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
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(final ValidEmail constraintAnnotation) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(final String username, final ConstraintValidatorContext context) {
|
||||
return (validateEmail(username));
|
||||
}
|
||||
|
||||
private boolean validateEmail(final String email) {
|
||||
pattern = Pattern.compile(EMAIL_PATTERN);
|
||||
matcher = pattern.matcher(email);
|
||||
return matcher.matches();
|
||||
}
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
import org.passay.DigitCharacterRule;
|
||||
import org.passay.LengthRule;
|
||||
import org.passay.PasswordData;
|
||||
import org.passay.PasswordValidator;
|
||||
import org.passay.RuleResult;
|
||||
import org.passay.SpecialCharacterRule;
|
||||
import org.passay.UppercaseCharacterRule;
|
||||
import org.passay.WhitespaceRule;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
|
||||
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {
|
||||
|
||||
@Override
|
||||
public void initialize(final ValidPassword arg0) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(final String password, final ConstraintValidatorContext context) {
|
||||
final PasswordValidator validator = new PasswordValidator(Arrays.asList(new LengthRule(8, 30), new UppercaseCharacterRule(1), new DigitCharacterRule(1), new SpecialCharacterRule(1), new WhitespaceRule()));
|
||||
final RuleResult result = validator.validate(new PasswordData(password));
|
||||
if (result.isValid()) {
|
||||
return true;
|
||||
}
|
||||
context.disableDefaultConstraintViolation();
|
||||
context.buildConstraintViolationWithTemplate(Joiner.on("\n").join(validator.getMessages(result))).addConstraintViolation();
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@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 {};
|
||||
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
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(final PasswordMatches constraintAnnotation) {
|
||||
//
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
|
||||
final UserDto user = (UserDto) obj;
|
||||
return user.getPassword().equals(user.getMatchingPassword());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
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(final Class<?> clazz) {
|
||||
return UserDto.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(final Object obj, final 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.");
|
||||
}
|
||||
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@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 {};
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
package org.baeldung.validation;
|
||||
|
||||
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@Documented
|
||||
@Constraint(validatedBy = PasswordConstraintValidator.class)
|
||||
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
|
||||
@Retention(RUNTIME)
|
||||
public @interface ValidPassword {
|
||||
|
||||
String message() default "Invalid Password";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
}
|
|
@ -1,237 +0,0 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.baeldung.persistence.model.PasswordResetToken;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.persistence.service.IUserService;
|
||||
import org.baeldung.persistence.service.UserDto;
|
||||
import org.baeldung.registration.OnRegistrationCompleteEvent;
|
||||
import org.baeldung.validation.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.core.env.Environment;
|
||||
import org.springframework.mail.MailAuthenticationException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
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.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/old")
|
||||
public class OldRegistrationController {
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@Autowired
|
||||
private IUserService userService;
|
||||
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public OldRegistrationController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
|
||||
public String showRegistrationForm(final HttpServletRequest request, final Model model) {
|
||||
LOGGER.debug("Rendering registration page.");
|
||||
final UserDto accountDto = new UserDto();
|
||||
model.addAttribute("user", accountDto);
|
||||
return "registration";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
|
||||
public String confirmRegistration(final HttpServletRequest request, final Model model, @RequestParam("token") final String token) {
|
||||
final Locale locale = request.getLocale();
|
||||
|
||||
final VerificationToken verificationToken = userService.getVerificationToken(token);
|
||||
if (verificationToken == null) {
|
||||
final String message = messages.getMessage("auth.message.invalidToken", null, locale);
|
||||
model.addAttribute("message", message);
|
||||
return "redirect:/badUser.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final User user = verificationToken.getUser();
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
|
||||
model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
|
||||
model.addAttribute("expired", true);
|
||||
model.addAttribute("token", token);
|
||||
return "redirect:/badUser.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
user.setEnabled(true);
|
||||
userService.saveRegisteredUser(user);
|
||||
model.addAttribute("message", messages.getMessage("message.accountVerified", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid final UserDto userDto, final HttpServletRequest request, final Errors errors) {
|
||||
LOGGER.debug("Registering user account with information: {}", userDto);
|
||||
|
||||
final User registered = createUserAccount(userDto);
|
||||
if (registered == null) {
|
||||
// result.rejectValue("email", "message.regError");
|
||||
return new ModelAndView("registration", "user", userDto);
|
||||
}
|
||||
try {
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
|
||||
} catch (final Exception ex) {
|
||||
LOGGER.warn("Unable to register user", ex);
|
||||
return new ModelAndView("emailError", "user", userDto);
|
||||
}
|
||||
return new ModelAndView("successRegister", "user", userDto);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET)
|
||||
public String resendRegistrationToken(final HttpServletRequest request, final Model model, @RequestParam("token") final String existingToken) {
|
||||
final Locale locale = request.getLocale();
|
||||
final VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
|
||||
final User user = userService.getUser(newToken.getToken());
|
||||
try {
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
final SimpleMailMessage email = constructResetVerificationTokenEmail(appUrl, request.getLocale(), newToken, user);
|
||||
mailSender.send(email);
|
||||
} catch (final MailAuthenticationException e) {
|
||||
LOGGER.debug("MailAuthenticationException", e);
|
||||
return "redirect:/emailError.html?lang=" + locale.getLanguage();
|
||||
} catch (final Exception e) {
|
||||
LOGGER.debug(e.getLocalizedMessage(), e);
|
||||
model.addAttribute("message", e.getLocalizedMessage());
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
model.addAttribute("message", messages.getMessage("message.resendToken", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
|
||||
public String resetPassword(final HttpServletRequest request, final Model model, @RequestParam("email") final String userEmail) {
|
||||
final User user = userService.findUserByEmail(userEmail);
|
||||
if (user == null) {
|
||||
model.addAttribute("message", messages.getMessage("message.userNotFound", null, request.getLocale()));
|
||||
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
|
||||
}
|
||||
|
||||
final String token = UUID.randomUUID().toString();
|
||||
userService.createPasswordResetTokenForUser(user, token);
|
||||
try {
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user);
|
||||
mailSender.send(email);
|
||||
} catch (final MailAuthenticationException e) {
|
||||
LOGGER.debug("MailAuthenticationException", e);
|
||||
return "redirect:/emailError.html?lang=" + request.getLocale().getLanguage();
|
||||
} catch (final Exception e) {
|
||||
LOGGER.debug(e.getLocalizedMessage(), e);
|
||||
model.addAttribute("message", e.getLocalizedMessage());
|
||||
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
|
||||
}
|
||||
model.addAttribute("message", messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
|
||||
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/changePassword", method = RequestMethod.GET)
|
||||
public String changePassword(final HttpServletRequest request, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) {
|
||||
final Locale locale = request.getLocale();
|
||||
|
||||
final PasswordResetToken passToken = userService.getPasswordResetToken(token);
|
||||
final User user = passToken.getUser();
|
||||
if (passToken == null || user.getId() != id) {
|
||||
final String message = messages.getMessage("auth.message.invalidToken", null, locale);
|
||||
model.addAttribute("message", message);
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
if ((passToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
|
||||
model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final Authentication auth = new UsernamePasswordAuthenticationToken(user, null, userDetailsService.loadUserByUsername(user.getEmail()).getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
return "redirect:/updatePassword.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
|
||||
@PreAuthorize("hasRole('READ_PRIVILEGE')")
|
||||
public String savePassword(final HttpServletRequest request, final Model model, @RequestParam("password") final String password) {
|
||||
final Locale locale = request.getLocale();
|
||||
|
||||
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
userService.changeUserPassword(user, password);
|
||||
model.addAttribute("message", messages.getMessage("message.resetPasswordSuc", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale;
|
||||
}
|
||||
|
||||
// NON-API
|
||||
|
||||
private final SimpleMailMessage constructResetVerificationTokenEmail(final String contextPath, final Locale locale, final VerificationToken newToken, final User user) {
|
||||
final String confirmationUrl = contextPath + "/old/regitrationConfirm.html?token=" + newToken.getToken();
|
||||
final String message = messages.getMessage("message.resendToken", null, locale);
|
||||
final SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setSubject("Resend Registration Token");
|
||||
email.setText(message + " \r\n" + confirmationUrl);
|
||||
email.setTo(user.getEmail());
|
||||
email.setFrom(env.getProperty("support.email"));
|
||||
return email;
|
||||
}
|
||||
|
||||
private final SimpleMailMessage constructResetTokenEmail(final String contextPath, final Locale locale, final String token, final User user) {
|
||||
final String url = contextPath + "/old/user/changePassword?id=" + user.getId() + "&token=" + token;
|
||||
final String message = messages.getMessage("message.resetPassword", null, locale);
|
||||
final SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setTo(user.getEmail());
|
||||
email.setSubject("Reset Password");
|
||||
email.setText(message + " \r\n" + url);
|
||||
email.setFrom(env.getProperty("support.email"));
|
||||
return email;
|
||||
}
|
||||
|
||||
private User createUserAccount(final UserDto accountDto) {
|
||||
User registered = null;
|
||||
try {
|
||||
registered = userService.registerNewUserAccount(accountDto);
|
||||
} catch (final EmailExistsException e) {
|
||||
return null;
|
||||
}
|
||||
return registered;
|
||||
}
|
||||
}
|
|
@ -1,218 +0,0 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.baeldung.persistence.model.PasswordResetToken;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.persistence.model.VerificationToken;
|
||||
import org.baeldung.persistence.service.IUserService;
|
||||
import org.baeldung.persistence.service.UserDto;
|
||||
import org.baeldung.registration.OnRegistrationCompleteEvent;
|
||||
import org.baeldung.validation.EmailExistsException;
|
||||
import org.baeldung.web.error.InvalidOldPasswordException;
|
||||
import org.baeldung.web.error.UserAlreadyExistException;
|
||||
import org.baeldung.web.error.UserNotFoundException;
|
||||
import org.baeldung.web.util.GenericResponse;
|
||||
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.core.env.Environment;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
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.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class RegistrationController {
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@Autowired
|
||||
private IUserService userService;
|
||||
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public RegistrationController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// Registration
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||
@ResponseBody
|
||||
public GenericResponse registerUserAccount(@Valid final UserDto accountDto, final HttpServletRequest request) {
|
||||
LOGGER.debug("Registering user account with information: {}", accountDto);
|
||||
|
||||
final User registered = createUserAccount(accountDto);
|
||||
if (registered == null) {
|
||||
throw new UserAlreadyExistException();
|
||||
}
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
|
||||
|
||||
return new GenericResponse("success");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
|
||||
public String confirmRegistration(final Locale locale, final Model model, @RequestParam("token") final String token) {
|
||||
final VerificationToken verificationToken = userService.getVerificationToken(token);
|
||||
if (verificationToken == null) {
|
||||
final String message = messages.getMessage("auth.message.invalidToken", null, locale);
|
||||
model.addAttribute("message", message);
|
||||
return "redirect:/badUser.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final User user = verificationToken.getUser();
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
|
||||
model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
|
||||
model.addAttribute("expired", true);
|
||||
model.addAttribute("token", token);
|
||||
return "redirect:/badUser.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
user.setEnabled(true);
|
||||
userService.saveRegisteredUser(user);
|
||||
model.addAttribute("message", messages.getMessage("message.accountVerified", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
// user activation - verification
|
||||
|
||||
@RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public GenericResponse resendRegistrationToken(final HttpServletRequest request, @RequestParam("token") final String existingToken) {
|
||||
final VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
|
||||
final User user = userService.getUser(newToken.getToken());
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
final SimpleMailMessage email = constructResendVerificationTokenEmail(appUrl, request.getLocale(), newToken, user);
|
||||
mailSender.send(email);
|
||||
|
||||
return new GenericResponse(messages.getMessage("message.resendToken", null, request.getLocale()));
|
||||
}
|
||||
|
||||
// Reset password
|
||||
|
||||
@RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
|
||||
@ResponseBody
|
||||
public GenericResponse resetPassword(final HttpServletRequest request, @RequestParam("email") final String userEmail) {
|
||||
final User user = userService.findUserByEmail(userEmail);
|
||||
if (user == null) {
|
||||
throw new UserNotFoundException();
|
||||
}
|
||||
|
||||
final String token = UUID.randomUUID().toString();
|
||||
userService.createPasswordResetTokenForUser(user, token);
|
||||
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user);
|
||||
mailSender.send(email);
|
||||
return new GenericResponse(messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/changePassword", method = RequestMethod.GET)
|
||||
public String showChangePasswordPage(final Locale locale, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) {
|
||||
final PasswordResetToken passToken = userService.getPasswordResetToken(token);
|
||||
final User user = passToken.getUser();
|
||||
if (passToken == null || user.getId() != id) {
|
||||
final String message = messages.getMessage("auth.message.invalidToken", null, locale);
|
||||
model.addAttribute("message", message);
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
if ((passToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
|
||||
model.addAttribute("message", messages.getMessage("auth.message.expired", null, locale));
|
||||
return "redirect:/login.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
final Authentication auth = new UsernamePasswordAuthenticationToken(user, null, userDetailsService.loadUserByUsername(user.getEmail()).getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
return "redirect:/updatePassword.html?lang=" + locale.getLanguage();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
|
||||
@PreAuthorize("hasRole('READ_PRIVILEGE')")
|
||||
@ResponseBody
|
||||
public GenericResponse savePassword(final Locale locale, @RequestParam("password") final String password) {
|
||||
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
userService.changeUserPassword(user, password);
|
||||
return new GenericResponse(messages.getMessage("message.resetPasswordSuc", null, locale));
|
||||
}
|
||||
|
||||
// change user password
|
||||
|
||||
@RequestMapping(value = "/user/updatePassword", method = RequestMethod.POST)
|
||||
@PreAuthorize("hasRole('READ_PRIVILEGE')")
|
||||
@ResponseBody
|
||||
public GenericResponse changeUserPassword(final Locale locale, @RequestParam("password") final String password, @RequestParam("oldpassword") final String oldPassword) {
|
||||
final User user = userService.findUserByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
|
||||
if (!userService.checkIfValidOldPassword(user, oldPassword)) {
|
||||
throw new InvalidOldPasswordException();
|
||||
}
|
||||
userService.changeUserPassword(user, password);
|
||||
return new GenericResponse(messages.getMessage("message.updatePasswordSuc", null, locale));
|
||||
}
|
||||
|
||||
// NON-API
|
||||
|
||||
private final SimpleMailMessage constructResendVerificationTokenEmail(final String contextPath, final Locale locale, final VerificationToken newToken, final User user) {
|
||||
final String confirmationUrl = contextPath + "/regitrationConfirm.html?token=" + newToken.getToken();
|
||||
final String message = messages.getMessage("message.resendToken", null, locale);
|
||||
final SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setSubject("Resend Registration Token");
|
||||
email.setText(message + " \r\n" + confirmationUrl);
|
||||
email.setTo(user.getEmail());
|
||||
email.setFrom(env.getProperty("support.email"));
|
||||
return email;
|
||||
}
|
||||
|
||||
private final SimpleMailMessage constructResetTokenEmail(final String contextPath, final Locale locale, final String token, final User user) {
|
||||
final String url = contextPath + "/user/changePassword?id=" + user.getId() + "&token=" + token;
|
||||
final String message = messages.getMessage("message.resetPassword", null, locale);
|
||||
final SimpleMailMessage email = new SimpleMailMessage();
|
||||
email.setTo(user.getEmail());
|
||||
email.setSubject("Reset Password");
|
||||
email.setText(message + " \r\n" + url);
|
||||
email.setFrom(env.getProperty("support.email"));
|
||||
return email;
|
||||
}
|
||||
|
||||
private User createUserAccount(final UserDto accountDto) {
|
||||
User registered = null;
|
||||
try {
|
||||
registered = userService.registerNewUserAccount(accountDto);
|
||||
} catch (final EmailExistsException e) {
|
||||
return null;
|
||||
}
|
||||
return registered;
|
||||
}
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.web.error;
|
||||
|
||||
public final class InvalidOldPasswordException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 5861310537366287163L;
|
||||
|
||||
public InvalidOldPasswordException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public InvalidOldPasswordException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public InvalidOldPasswordException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public InvalidOldPasswordException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,85 +0,0 @@
|
|||
package org.baeldung.web.error;
|
||||
|
||||
import org.baeldung.web.util.GenericResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mail.MailAuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
@ControllerAdvice
|
||||
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
@Autowired
|
||||
private MessageSource messages;
|
||||
|
||||
public RestResponseEntityExceptionHandler() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// 400
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleBindException(final BindException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
|
||||
logger.error("400 Status Code", ex);
|
||||
final BindingResult result = ex.getBindingResult();
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(result.getFieldErrors(), result.getGlobalErrors());
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
|
||||
logger.error("400 Status Code", ex);
|
||||
final BindingResult result = ex.getBindingResult();
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(result.getFieldErrors(), result.getGlobalErrors());
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler({ InvalidOldPasswordException.class })
|
||||
public ResponseEntity<Object> handleInvalidOldPassword(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("400 Status Code", ex);
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.invalidOldPassword", null, request.getLocale()), "InvalidOldEmail");
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
// 404
|
||||
@ExceptionHandler({ UserNotFoundException.class })
|
||||
public ResponseEntity<Object> handleUserNotFound(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("404 Status Code", ex);
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.userNotFound", null, request.getLocale()), "UserNotFound");
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
|
||||
}
|
||||
|
||||
// 409
|
||||
@ExceptionHandler({ UserAlreadyExistException.class })
|
||||
public ResponseEntity<Object> handleUserAlreadyExist(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("409 Status Code", ex);
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.regError", null, request.getLocale()), "UserAlreadyExist");
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
|
||||
}
|
||||
|
||||
// 500
|
||||
@ExceptionHandler({ MailAuthenticationException.class })
|
||||
public ResponseEntity<Object> handleMail(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("500 Status Code", ex);
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.email.config.error", null, request.getLocale()), "MailError");
|
||||
return new ResponseEntity<Object>(bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
@ExceptionHandler({ Exception.class })
|
||||
public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("500 Status Code", ex);
|
||||
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.error", null, request.getLocale()), "InternalError");
|
||||
return new ResponseEntity<Object>(bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.web.error;
|
||||
|
||||
public final class UserAlreadyExistException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 5861310537366287163L;
|
||||
|
||||
public UserAlreadyExistException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserAlreadyExistException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public UserAlreadyExistException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public UserAlreadyExistException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.web.error;
|
||||
|
||||
public final class UserNotFoundException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 5861310537366287163L;
|
||||
|
||||
public UserNotFoundException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserNotFoundException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public UserNotFoundException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public UserNotFoundException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,54 +0,0 @@
|
|||
package org.baeldung.web.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.validation.ObjectError;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class GenericResponse {
|
||||
private String message;
|
||||
private String error;
|
||||
|
||||
public GenericResponse(final String message) {
|
||||
super();
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public GenericResponse(final String message, final String error) {
|
||||
super();
|
||||
this.message = message;
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public GenericResponse(final List<FieldError> fieldErrors, final List<ObjectError> globalErrors) {
|
||||
super();
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
this.message = mapper.writeValueAsString(fieldErrors);
|
||||
this.error = mapper.writeValueAsString(globalErrors);
|
||||
} catch (final JsonProcessingException e) {
|
||||
this.message = "";
|
||||
this.error = "";
|
||||
}
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(final String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public void setError(final String error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
email.properties
|
|
@ -1,7 +0,0 @@
|
|||
################### JavaMail Configuration ##########################
|
||||
smtp.host=email-smtp.us-east-1.amazonaws.com
|
||||
smtp.port=465
|
||||
smtp.protocol=smtps
|
||||
smtp.username=AKIAJIKXZAQFFJDXI4VQ
|
||||
smtp.password=
|
||||
support.email=eugen@baeldung.com
|
|
@ -1,20 +0,0 @@
|
|||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -1,79 +0,0 @@
|
|||
message.username=Username required
|
||||
message.password=Password required
|
||||
message.unauth=Unauthorized Access !!
|
||||
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 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)
|
||||
label.form.resendRegistrationToken=Re-send Token
|
||||
message.resendToken=We will send an email with a new registration token to your email account
|
||||
message.forgetPassword=Forget Password
|
||||
message.resetPassword=Reset Password
|
||||
message.updatePassword=Update Password
|
||||
message.userNotFound=User Not Found
|
||||
auth.message.blocked=This ip is blocked for 24 hours
|
||||
message.accountVerified=Your account verified successfully
|
||||
message.resetPasswordSuc=Password reset successfully
|
||||
message.resetYourPassword=Reset your password
|
||||
message.resetPasswordEmail=You should receive an Password Reset Email shortly
|
||||
message.error=Error Occurred
|
||||
message.updatePasswordSuc=Password updated successfully
|
||||
message.changePassword=Change Password
|
||||
message.invalidOldPassword=Invalid Old Password
|
||||
label.user.newPassword=New Password
|
||||
label.user.oldPassword=Old Password
|
||||
error.wordLength=Your password is too short
|
||||
error.wordNotEmail=Do not use your email as your password
|
||||
error.wordSequences=Your password contains sequences
|
||||
error.wordLowercase=Use lower case characters
|
||||
error.wordUppercase=Use upper case characters
|
||||
error.wordOneNumber=Use numbers
|
||||
error.wordOneSpecialChar=Use special characters
|
|
@ -1,79 +0,0 @@
|
|||
message.username=Por favor ingrese el nombre de usuario
|
||||
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 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
|
||||
label.form.resendRegistrationToken=Reenviar mensaje de emergencia
|
||||
message.resendToken=Te enviaremos un correo electrónico con un nuevo token de registro en su cuenta de correo electrónico
|
||||
message.forgetPassword=Olvide la contraseña
|
||||
message.resetPassword=Restablecer contraseña
|
||||
message.updatePassword=Actualizar contraseña
|
||||
message.userNotFound=Usuario no encontrado
|
||||
auth.message.blocked=Esta IP se bloquea durante 24 horas
|
||||
message.accountVerified=Su cuenta verificada con éxito
|
||||
message.resetPasswordSuc=Contraseña reajusta correctamente
|
||||
message.resetYourPassword=Restablecer su contraseña
|
||||
message.resetPasswordEmail=Te enviaremos un correo electrónico para restablecer su contraseña
|
||||
message.error=Se produjo un error
|
||||
message.updatePasswordSuc=Contraseña actualizado correctamente
|
||||
message.changePassword=Cambiar La Contraseña
|
||||
message.invalidOldPassword=Inválida contraseña antigua
|
||||
label.user.newPassword=Nueva Contraseña
|
||||
label.user.oldPassword=Contraseña Anterior
|
||||
error.wordLength=Tu contraseña es demasiado corta
|
||||
error.wordNotEmail=No utilice su dirección de correo electrónico como contraseña
|
||||
error.wordSequences=Su contraseña contiene secuencias
|
||||
error.wordLowercase=Utilice caracteres en minúsculas
|
||||
error.wordUppercase=Utilice mayúsculas
|
||||
error.wordOneNumber=Utilice números
|
||||
error.wordOneSpecialChar=Utilice los caracteres especiales
|
|
@ -1,10 +0,0 @@
|
|||
################### DataSource Configuration ##########################
|
||||
jdbc.driverClassName=com.mysql.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/registration_02?createDatabaseIfNotExist=true
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
init-db=false
|
||||
################### Hibernate Configuration ##########################
|
||||
hibernate.dialect=org.hibernate.dialect.MySQLDialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
|
@ -1,41 +0,0 @@
|
|||
<?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"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.2.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="/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"
|
||||
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" />
|
||||
</http>
|
||||
|
||||
<beans:bean id="myAuthenticationSuccessHandler"
|
||||
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider user-service-ref="userDetailsService" />
|
||||
</authentication-manager>
|
||||
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService" />
|
||||
|
||||
</beans:beans>
|
|
@ -1,57 +0,0 @@
|
|||
<?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"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security-4.0.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.2.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="/user/resendRegistrationToken*" access="permitAll"/>
|
||||
<intercept-url pattern="/forgetPassword*" access="permitAll"/>
|
||||
<intercept-url pattern="/user/resetPassword*" access="permitAll"/>
|
||||
<intercept-url pattern="/user/changePassword*" access="permitAll"/>
|
||||
<intercept-url pattern="/updatePassword*" access="isAuthenticated()"/>
|
||||
<intercept-url pattern="/user/savePassword*" access="isAuthenticated()"/>
|
||||
|
||||
<intercept-url pattern="/emailError*" access="permitAll"/>
|
||||
<intercept-url pattern="/resources/**" access="permitAll"/>
|
||||
<intercept-url pattern="/invalidSession*" access="isAnonymous()"/>
|
||||
<intercept-url pattern="/**" access="isAuthenticated()"/>
|
||||
|
||||
<csrf disabled="true"/>
|
||||
|
||||
<form-login login-page='/login'
|
||||
authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
authentication-failure-handler-ref="authenticationFailureHandler"
|
||||
default-target-url="/homepage"/>
|
||||
|
||||
<session-management invalid-session-url="/invalidSession" session-fixation-protection="none"/>
|
||||
|
||||
<logout invalidate-session="false" logout-success-url="/logoutPage?logSucc=true" delete-cookies="JSESSIONID"/>
|
||||
</http>
|
||||
|
||||
<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="passwordEncoder"/>
|
||||
</beans:bean>
|
||||
|
||||
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
|
||||
<beans:constructor-arg value="11"/>
|
||||
</beans:bean>
|
||||
|
||||
</beans:beans>
|
|
@ -1,3 +0,0 @@
|
|||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
<?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.2.xsd"
|
||||
>
|
||||
|
||||
</beans>
|
|
@ -1,34 +0,0 @@
|
|||
<%@ 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"%>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand"href="<c:url value="/home.html" />"><spring:message code="label.pages.home.title"></spring:message></a>
|
||||
</div>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="<c:url value="/logout" />"><spring:message code="label.pages.logout"></spring:message></a> </li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container">
|
||||
<sec:authorize ifNotGranted="WRITE_PRIVILEGE">
|
||||
<spring:message code="message.unauth"></spring:message>
|
||||
</sec:authorize>
|
||||
<sec:authorize ifAnyGranted="WRITE_PRIVILEGE">
|
||||
<h1>
|
||||
<spring:message code="label.pages.admin.message"></spring:message>
|
||||
</h1>
|
||||
</sec:authorize>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,54 +0,0 @@
|
|||
<%@ 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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message
|
||||
code="label.badUser.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 class="alert alert-danger">
|
||||
${param.message}
|
||||
</h1>
|
||||
<br>
|
||||
<a class="btn btn-default" href="<c:url value="/registration.html" />"><spring:message
|
||||
code="label.form.loginSignUp"></spring:message></a>
|
||||
|
||||
<c:if test="${param.expired}">
|
||||
<br>
|
||||
<h1>${label.form.resendRegistrationToken}</h1>
|
||||
<button onclick="resendToken()">
|
||||
<spring:message code="label.form.resendRegistrationToken"></spring:message>
|
||||
</button>
|
||||
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
function resendToken(){
|
||||
$.get("<c:url value="/user/resendRegistrationToken"><c:param name="token" value="${param.token}"/></c:url>", function(data){
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message;
|
||||
})
|
||||
.fail(function(data) {
|
||||
if(data.responseJSON.error.indexOf("MailError") > -1)
|
||||
{
|
||||
window.location.href = "<c:url value="/emailError.html"></c:url>";
|
||||
}
|
||||
else{
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.responseJSON.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(document).ajaxStart(function() {
|
||||
$("title").html("LOADING ...");
|
||||
});
|
||||
</script>
|
||||
</c:if>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,70 +0,0 @@
|
|||
<!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"%>
|
||||
<%@ page session="false"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title><spring:message code="message.changePassword"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand"href="#"><spring:message code="label.pages.home.title"></spring:message></a>
|
||||
</div>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="<c:url value="/logout" />"><spring:message code="label.pages.logout"></spring:message></a> </li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div id="errormsg" class="alert alert-danger" style="display:none"></div>
|
||||
<h1> <spring:message code="message.changePassword"></spring:message> </h1>
|
||||
<div >
|
||||
<br>
|
||||
|
||||
<label class="col-sm-2"><spring:message code="label.user.oldPassword"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="oldpass" name="oldpassword" type="password" value="" /></span>
|
||||
<span class="col-sm-5"></span>
|
||||
<br><br>
|
||||
<label class="col-sm-2"><spring:message code="label.user.newPassword"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="pass" name="password" type="password" value="" /></span>
|
||||
<span class="col-sm-5"></span>
|
||||
<br><br>
|
||||
<label class="col-sm-2"><spring:message code="label.user.confirmPass"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="passConfirm" type="password" value="" /></span>
|
||||
<span id="error" class="alert alert-danger" style="display:none"><spring:message code="PasswordMatches.user"></spring:message></span>
|
||||
|
||||
<br><br>
|
||||
<button class="btn btn-primary" type="submit" onclick="savePass()">
|
||||
<spring:message code="message.changePassword"></spring:message>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
function savePass(){
|
||||
var pass = $("#pass").val();
|
||||
var valid = pass == $("#passConfirm").val();
|
||||
if(!valid) {
|
||||
$("#error").show();
|
||||
return;
|
||||
}
|
||||
$.post("<c:url value="/user/updatePassword"></c:url>",{password: pass, oldpassword: $("#oldpass").val()} ,function(data){
|
||||
window.location.href = "<c:url value="/console.html"></c:url>" + "?message="+data.message;
|
||||
})
|
||||
.fail(function(data) {
|
||||
$("#errormsg").show().html(data.responseJSON.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,42 +0,0 @@
|
|||
<%@ 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"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand"href="<c:url value="/home.html" />"><spring:message code="label.pages.home.title"></spring:message></a>
|
||||
</div>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="<c:url value="/logout" />"><spring:message code="label.pages.logout"></spring:message></a> </li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container">
|
||||
<c:if test="${param.message != null}">
|
||||
<div class="alert alert-info">
|
||||
${param.message}
|
||||
</div>
|
||||
</c:if>
|
||||
<h1>This is the landing page for the admin</h1>
|
||||
<sec:authorize access="hasRole('READ_PRIVILEGE')">
|
||||
This text is only visible to a user
|
||||
<br />
|
||||
</sec:authorize>
|
||||
<sec:authorize access="hasRole('WRITE_PRIVILEGE')">
|
||||
This text is only visible to an admin
|
||||
<br />
|
||||
</sec:authorize>
|
||||
<a class="btn btn-default" href="<c:url value="/changePassword.html" />"><spring:message code="message.changePassword"></spring:message></a>
|
||||
|
||||
<a class="btn btn-default" href="<c:url value="/admin.html" />"><spring:message code="label.pages.admin"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,17 +0,0 @@
|
|||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 class="alert alert-danger">
|
||||
<spring:message code="message.email.config.error"></spring:message>
|
||||
</h1>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,24 +0,0 @@
|
|||
<%@ 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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 class="alert alert-info">
|
||||
<spring:message code="auth.message.expired"></spring:message>
|
||||
</h1>
|
||||
<br>
|
||||
<a class="btn btn-default" href="<c:url value="registration.html" />"><spring:message
|
||||
code="label.form.loginSignUp"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,55 +0,0 @@
|
|||
<!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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title><spring:message code="message.resetPassword"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1><spring:message code="message.resetPassword"></spring:message></h1>
|
||||
<br>
|
||||
<div class="row">
|
||||
<label class="col-sm-1"><spring:message code="label.user.email"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="email" name="email" type="email" value="" /></span>
|
||||
<button class="btn btn-primary" type="submit" onclick="resetPass()"><spring:message code="message.resetPassword"></spring:message></button>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
<a class="btn btn-default" href="<c:url value="registration.html" />"><spring:message code="label.form.loginSignUp"></spring:message></a>
|
||||
<br><br>
|
||||
<a class="btn btn-default" href="<c:url value="login.html" />"><spring:message code="label.form.loginLink"></spring:message></a>
|
||||
|
||||
</div>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
function resetPass(){
|
||||
var email = $("#email").val();
|
||||
$.post("<c:url value="/user/resetPassword"></c:url>",{email: email} ,function(data){
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message;
|
||||
})
|
||||
.fail(function(data) {
|
||||
if(data.responseJSON.error.indexOf("MailError") > -1)
|
||||
{
|
||||
window.location.href = "<c:url value="/emailError.html"></c:url>";
|
||||
}
|
||||
else{
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.responseJSON.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(document).ajaxStart(function() {
|
||||
$("title").html("LOADING ...");
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,29 +0,0 @@
|
|||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
|
||||
<%@ page session="true"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand"href="#"><spring:message code="label.pages.home.title"></spring:message></a>
|
||||
</div>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="<c:url value="/logout" />"><spring:message code="label.pages.logout"></spring:message></a> </li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="container">
|
||||
<h1>
|
||||
<spring:message code="label.pages.home.message"></spring:message>
|
||||
</h1>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
<%@ 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"%>
|
||||
<%@ page session="true"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-default">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand"href="<c:url value="/home.html" />"><spring:message code="label.pages.home.title"></spring:message></a>
|
||||
</div>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="<c:url value="/logout" />"><spring:message code="label.pages.logout"></spring:message></a> </li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container">
|
||||
|
||||
<sec:authorize access="hasRole('READ_PRIVILEGE')">
|
||||
<spring:message code="label.pages.user.message"></spring:message>
|
||||
<br />
|
||||
</sec:authorize>
|
||||
|
||||
<sec:authorize access="hasRole('WRITE_PRIVILEGE')">
|
||||
<spring:message code="label.pages.admin.message"></spring:message>
|
||||
<br />
|
||||
</sec:authorize>
|
||||
${param.user}
|
||||
<a class="btn btn-default" href="<c:url value="/admin.html" />"><spring:message code="label.pages.admin"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,18 +0,0 @@
|
|||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 class="alert alert-danger">
|
||||
<spring:message code="message.sessionExpired"></spring:message>
|
||||
</h1>
|
||||
<a class="btn btn-primary" href="<c:url value="login.html" />"><spring:message
|
||||
code="label.form.loginLink"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,88 +0,0 @@
|
|||
<%@ 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"%>
|
||||
<fmt:message key="message.password" var="noPass" />
|
||||
<fmt:message key="message.username" var="noUser" />
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<title><spring:message code="label.pages.home.title"></spring:message></title>
|
||||
<script type="text/javascript">
|
||||
function validate() {
|
||||
if (document.f.username.value == ""
|
||||
&& document.f.password.value == "") {
|
||||
alert("${noUser} & ${noPass}");
|
||||
document.f.username.focus();
|
||||
return false;
|
||||
}
|
||||
if (document.f.username.value == "") {
|
||||
alert("${noUser}");
|
||||
document.f.username.focus();
|
||||
return false;
|
||||
}
|
||||
if (document.f.password.value == "") {
|
||||
alert("${noPass}");
|
||||
document.f.password.focus();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<style type="text/css">
|
||||
.wrapper{width:500px;margin-left:auto;margin-right:auto}
|
||||
label{padding-left:0 !important}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<c:if test="${param.message != null}">
|
||||
<div class="alert alert-info">
|
||||
${param.message}
|
||||
</div>
|
||||
</c:if>
|
||||
|
||||
|
||||
<c:if test="${param.error != null}">
|
||||
<div class="alert alert-danger">
|
||||
${SPRING_SECURITY_LAST_EXCEPTION}
|
||||
</div>
|
||||
</c:if>
|
||||
|
||||
<div class="container">
|
||||
<div class="row wrapper">
|
||||
<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>
|
||||
<br><br>
|
||||
|
||||
<form name='f' action="login" method='POST' onsubmit="return validate();">
|
||||
|
||||
<label class="col-sm-4"><spring:message code="label.form.loginEmail"></spring:message></label>
|
||||
<span class="col-sm-8"><input class="form-control" type='text' name='username' value=''></span>
|
||||
|
||||
<br><br>
|
||||
<label class="col-sm-4"><spring:message code="label.form.loginPass"></spring:message></label>
|
||||
<span class="col-sm-8"><input class="form-control" type='password' name='password' /></span>
|
||||
|
||||
<br><br>
|
||||
<input class="btn btn-primary" name="submit" type="submit"
|
||||
value=<spring:message code="label.form.submit"></spring:message> />
|
||||
|
||||
</form>
|
||||
<br> Current Locale : ${pageContext.response.locale} <br><br>
|
||||
<a class="btn btn-default" href="<c:url value="registration.html" />"><spring:message
|
||||
code="label.form.loginSignUp"></spring:message></a>
|
||||
<br><br>
|
||||
<a class="btn btn-default" href="<c:url value="/forgetPassword.html" />"><spring:message
|
||||
code="message.resetPassword"></spring:message></a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,31 +0,0 @@
|
|||
<%@ 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"%>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
|
||||
<h1 id="error" class="alert alert-danger">
|
||||
<spring:message code="message.logoutError"></spring:message>
|
||||
</h1>
|
||||
</c:if>
|
||||
<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">
|
||||
|
||||
<c:if test="${param.logSucc == true}">
|
||||
<h1 id="success" class="alert alert-info">
|
||||
<spring:message code="message.logoutSucc"></spring:message>
|
||||
</h1>
|
||||
</c:if>
|
||||
<a class="btn btn-primary" href="<c:url value="login" />"><spring:message
|
||||
code="label.form.loginLink"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,139 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
|
||||
<%@ page session="false"%>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<style>
|
||||
.password-verdict{
|
||||
color:#000;
|
||||
}
|
||||
</style>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script src="<c:url value="/resources/pwstrength.js" />"></script>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title><spring:message code="label.form.title"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div >
|
||||
<h1>
|
||||
<spring:message code="label.form.title"></spring:message>
|
||||
</h1>
|
||||
<br>
|
||||
<form action="/" method="POST" enctype="utf8">
|
||||
<div class="form-group row" >
|
||||
<label class="col-sm-3"><spring:message code="label.user.firstName"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" name="firstName" value="" required/></span>
|
||||
<span id="firstNameError" class="alert alert-danger col-sm-4" style="display:none"></span>
|
||||
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label class="col-sm-3"><spring:message code="label.user.lastName"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" name="lastName" value="" required/></span>
|
||||
<span id="lastNameError" class="alert alert-danger col-sm-4" style="display:none"></span>
|
||||
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label class="col-sm-3"><spring:message code="label.user.email"></spring:message></label>
|
||||
<span class="col-sm-5"><input type="email" class="form-control" name="email" value="" required/></span>
|
||||
<span id="emailError" class="alert alert-danger col-sm-4" style="display:none"></span>
|
||||
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label class="col-sm-3"><spring:message code="label.user.password"></spring:message></label>
|
||||
<span class="col-sm-5"><input id="password" class="form-control" name="password" value="" type="password" required/></span>
|
||||
<span id="passwordError" class="alert alert-danger col-sm-4" style="display:none"></span>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label class="col-sm-3"><spring:message code="label.user.confirmPass"></spring:message></label>
|
||||
<span class="col-sm-5"><input id="matchPassword" class="form-control" name="matchingPassword" value="" type="password" required/></span>
|
||||
<span id="globalError" class="alert alert-danger col-sm-4" style="display:none"></span>
|
||||
</div>
|
||||
<br>
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<spring:message code="label.form.submit"></spring:message>
|
||||
</button>
|
||||
</form>
|
||||
<br>
|
||||
<a href="<c:url value="login.html" />"><spring:message code="label.form.loginLink"></spring:message></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function () {
|
||||
$('form').submit(function(event) {
|
||||
register(event);
|
||||
});
|
||||
|
||||
$(":password").keyup(function(){
|
||||
if($("#password").val() != $("#matchPassword").val()){
|
||||
$("#globalError").show().html('<spring:message code="PasswordMatches.user"></spring:message>');
|
||||
}else{
|
||||
$("#globalError").html("").hide();
|
||||
}
|
||||
});
|
||||
|
||||
options = {
|
||||
common: {minChar:8},
|
||||
ui: {
|
||||
showVerdictsInsideProgressBar:true,
|
||||
showErrors:true,
|
||||
errorMessages:{
|
||||
wordLength: '<spring:message code="error.wordLength"/>',
|
||||
wordNotEmail: '<spring:message code="error.wordNotEmail"/>',
|
||||
wordSequences: '<spring:message code="error.wordSequences"/>',
|
||||
wordLowercase: '<spring:message code="error.wordLowercase"/>',
|
||||
wordUppercase: '<spring:message code="error.wordUppercase"/>',
|
||||
wordOneNumber: '<spring:message code="error.wordOneNumber"/>',
|
||||
wordOneSpecialChar: '<spring:message code="error.wordOneSpecialChar"/>'
|
||||
}
|
||||
}
|
||||
};
|
||||
$('#password').pwstrength(options);
|
||||
});
|
||||
|
||||
function register(event){
|
||||
event.preventDefault();
|
||||
$(".alert").html("").hide();
|
||||
$(".error-list").html("");
|
||||
if($("#password").val() != $("#matchPassword").val()){
|
||||
$("#globalError").show().html('<spring:message code="PasswordMatches.user"></spring:message>');
|
||||
return;
|
||||
}
|
||||
var formData= $('form').serialize();
|
||||
$.post("<c:url value="/user/registration"/>",formData ,function(data){
|
||||
if(data.message == "success"){
|
||||
window.location.href = "<c:url value="/successRegister.html"></c:url>";
|
||||
}
|
||||
|
||||
})
|
||||
.fail(function(data) {
|
||||
if(data.responseJSON.error.indexOf("MailError") > -1)
|
||||
{
|
||||
window.location.href = "<c:url value="/emailError.html"></c:url>";
|
||||
}
|
||||
else if(data.responseJSON.error == "UserAlreadyExist"){
|
||||
$("#emailError").show().html(data.responseJSON.message);
|
||||
}
|
||||
else if(data.responseJSON.error.indexOf("InternalError") > -1){
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.responseJSON.message;
|
||||
}
|
||||
else{
|
||||
var errors = $.parseJSON(data.responseJSON.message);
|
||||
$.each( errors, function( index,item ){
|
||||
$("#"+item.field+"Error").show().html(item.defaultMessage);
|
||||
});
|
||||
errors = $.parseJSON(data.responseJSON.error);
|
||||
$.each( errors, function( index,item ){
|
||||
$("#globalError").show().append(item.defaultMessage+"<br>");
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,23 +0,0 @@
|
|||
<%@ 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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<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>
|
||||
<h1 class="alert alert-info"><spring:message code="message.regSucc"></spring:message></h1>
|
||||
<a class="btn btn-primary" href="<c:url value="login.html" />"><spring:message code="label.login"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,25 +0,0 @@
|
|||
<%@ 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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<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">
|
||||
<h1 class="alert alert-success">
|
||||
<spring:message code="message.regSucc"></spring:message>
|
||||
</h1>
|
||||
<a href="<c:url value="/login.html" />"><spring:message
|
||||
code="label.login"></spring:message></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,60 +0,0 @@
|
|||
<!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 rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title><spring:message code="message.updatePassword"></spring:message></title>
|
||||
</head>
|
||||
<body>
|
||||
<sec:authorize access="hasRole('READ_PRIVILEGE')">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<h1> <spring:message code="message.resetYourPassword"></spring:message> </h1>
|
||||
<div >
|
||||
<br>
|
||||
|
||||
<label class="col-sm-2"><spring:message code="label.user.password"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="pass" name="password" type="password" value="" /></span>
|
||||
<span class="col-sm-5"></span>
|
||||
<br><br>
|
||||
<label class="col-sm-2"><spring:message code="label.user.confirmPass"></spring:message></label>
|
||||
<span class="col-sm-5"><input class="form-control" id="passConfirm" type="password" value="" /></span>
|
||||
<span id="error" class="alert alert-danger" style="display:none"><spring:message code="PasswordMatches.user"></spring:message></span>
|
||||
|
||||
<br><br>
|
||||
<button class="btn btn-primary" type="submit" onclick="savePass()">
|
||||
<spring:message code="message.updatePassword"></spring:message>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
function savePass(){
|
||||
var pass = $("#pass").val();
|
||||
var valid = pass == $("#passConfirm").val();
|
||||
if(!valid) {
|
||||
$("#error").show();
|
||||
return;
|
||||
}
|
||||
$.post("<c:url value="/user/savePassword"></c:url>",{password: pass} ,function(data){
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message="+data.message;
|
||||
})
|
||||
.fail(function(data) {
|
||||
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.responseJSON.message;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</sec:authorize>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,52 +0,0 @@
|
|||
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
xsi:schemaLocation="
|
||||
http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
|
||||
>
|
||||
|
||||
<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>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.request.RequestContextListener</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>
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
@ -1,23 +0,0 @@
|
|||
package org.baeldung.spring;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
// @ComponentScan("org.baeldung.test")
|
||||
public class ConfigTest extends WebMvcConfigurerAdapter {
|
||||
|
||||
public ConfigTest() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
@Bean
|
||||
public PasswordEncoder encoder() {
|
||||
return new BCryptPasswordEncoder(11);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,102 +0,0 @@
|
|||
package org.baeldung.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.baeldung.spring.ConfigTest;
|
||||
import org.baeldung.spring.PersistenceJPAConfig;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.jayway.restassured.RestAssured;
|
||||
import com.jayway.restassured.authentication.FormAuthConfig;
|
||||
import com.jayway.restassured.response.Response;
|
||||
import com.jayway.restassured.specification.RequestSpecification;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { ConfigTest.class, PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class ChangePasswordLiveTest {
|
||||
|
||||
private final String URL_PREFIX = "http://localhost:8080/spring-security-login-and-registration";
|
||||
private final String URL = URL_PREFIX + "/user/updatePassword";
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private final FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "username", "password");
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
User user = userRepository.findByEmail("test@test.com");
|
||||
if (user == null) {
|
||||
user = new User();
|
||||
user.setFirstName("Test");
|
||||
user.setLastName("Test");
|
||||
user.setPassword(passwordEncoder.encode("test"));
|
||||
user.setEmail("test@test.com");
|
||||
user.setEnabled(true);
|
||||
userRepository.save(user);
|
||||
} else {
|
||||
user.setPassword(passwordEncoder.encode("test"));
|
||||
userRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
||||
// test
|
||||
|
||||
@Test
|
||||
public void givenLoggedInUser_whenChangingPassword_thenCorrect() {
|
||||
final RequestSpecification request = RestAssured.given().auth().form("test@test.com", "test", formConfig);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("oldpassword", "test");
|
||||
params.put("password", "newtest");
|
||||
|
||||
final Response response = request.with().params(params).post(URL);
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
assertTrue(response.body().asString().contains("Password updated successfully"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongOldPassword_whenChangingPassword_thenBadRequest() {
|
||||
final RequestSpecification request = RestAssured.given().auth().form("test@test.com", "test", formConfig);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("oldpassword", "abc");
|
||||
params.put("password", "newtest");
|
||||
|
||||
final Response response = request.with().params(params).post(URL);
|
||||
|
||||
assertEquals(400, response.statusCode());
|
||||
assertTrue(response.body().asString().contains("Invalid Old Password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAuthenticatedUser_whenChangingPassword_thenRedirect() {
|
||||
final Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("oldpassword", "abc");
|
||||
params.put("password", "xyz");
|
||||
|
||||
final Response response = RestAssured.with().params(params).post(URL);
|
||||
|
||||
assertEquals(302, response.statusCode());
|
||||
assertFalse(response.body().asString().contains("Password updated successfully"));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,121 +0,0 @@
|
|||
package org.baeldung.test;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.persistence.dao.PrivilegeRepository;
|
||||
import org.baeldung.persistence.dao.RoleRepository;
|
||||
import org.baeldung.persistence.dao.UserRepository;
|
||||
import org.baeldung.persistence.model.Privilege;
|
||||
import org.baeldung.persistence.model.Role;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.test.context.transaction.TransactionConfiguration;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@Transactional
|
||||
@TransactionConfiguration
|
||||
public class SpringSecurityRolesIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
@Autowired
|
||||
private PrivilegeRepository privilegeRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private User user;
|
||||
private Role role;
|
||||
private Privilege privilege;
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void testDeleteUser() {
|
||||
role = new Role("TEST_ROLE");
|
||||
roleRepository.save(role);
|
||||
|
||||
user = new User();
|
||||
user.setFirstName("John");
|
||||
user.setLastName("Doe");
|
||||
user.setPassword(passwordEncoder.encode("123"));
|
||||
user.setEmail("john@doe.com");
|
||||
user.setRoles(Arrays.asList(role));
|
||||
user.setEnabled(true);
|
||||
userRepository.save(user);
|
||||
|
||||
assertNotNull(userRepository.findByEmail(user.getEmail()));
|
||||
assertNotNull(roleRepository.findByName(role.getName()));
|
||||
user.setRoles(null);
|
||||
userRepository.delete(user);
|
||||
|
||||
assertNull(userRepository.findByEmail(user.getEmail()));
|
||||
assertNotNull(roleRepository.findByName(role.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteRole() {
|
||||
privilege = new Privilege("TEST_PRIVILEGE");
|
||||
privilegeRepository.save(privilege);
|
||||
|
||||
role = new Role("TEST_ROLE");
|
||||
role.setPrivileges(Arrays.asList(privilege));
|
||||
roleRepository.save(role);
|
||||
|
||||
user = new User();
|
||||
user.setFirstName("John");
|
||||
user.setLastName("Doe");
|
||||
user.setPassword(passwordEncoder.encode("123"));
|
||||
user.setEmail("john@doe.com");
|
||||
user.setRoles(Arrays.asList(role));
|
||||
user.setEnabled(true);
|
||||
userRepository.save(user);
|
||||
|
||||
assertNotNull(privilegeRepository.findByName(privilege.getName()));
|
||||
assertNotNull(userRepository.findByEmail(user.getEmail()));
|
||||
assertNotNull(roleRepository.findByName(role.getName()));
|
||||
|
||||
user.setRoles(new ArrayList<Role>());
|
||||
role.setPrivileges(new ArrayList<Privilege>());
|
||||
roleRepository.delete(role);
|
||||
|
||||
assertNull(roleRepository.findByName(role.getName()));
|
||||
assertNotNull(privilegeRepository.findByName(privilege.getName()));
|
||||
assertNotNull(userRepository.findByEmail(user.getEmail()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeletePrivilege() {
|
||||
privilege = new Privilege("TEST_PRIVILEGE");
|
||||
privilegeRepository.save(privilege);
|
||||
|
||||
role = new Role("TEST_ROLE");
|
||||
role.setPrivileges(Arrays.asList(privilege));
|
||||
roleRepository.save(role);
|
||||
|
||||
assertNotNull(roleRepository.findByName(role.getName()));
|
||||
assertNotNull(privilegeRepository.findByName(privilege.getName()));
|
||||
|
||||
role.setPrivileges(new ArrayList<Privilege>());
|
||||
privilegeRepository.delete(privilege);
|
||||
|
||||
assertNull(privilegeRepository.findByName(privilege.getName()));
|
||||
assertNotNull(roleRepository.findByName(role.getName()));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue