diff --git a/package.json b/package.json index 8467f64de233d418e41767f06fac32b66aec3498..0736e4e271819e4efd681bdeddf1affc928bd8a5 100644 --- a/package.json +++ b/package.json @@ -94,6 +94,12 @@ "engines": { "node": ">=12.16.1" }, + "lint-staged": { + "{,src/**/,webpack/}*.{md,json,js,ts,tsx,css,scss,yml,yaml,java}": [ + "prettier --write", + "git add" + ] + }, "scripts": { "prettier:format": "prettier --write \"{,src/**/}*.{md,json,ts,css,scss,yml}\"", "lint": "eslint . --ext .js,.ts", diff --git a/src/main/java/com/ippon/pouet/ApplicationWebXml.java b/src/main/java/com/ippon/pouet/ApplicationWebXml.java index b3efc8d7bc4901931db13ff3a6b66a61218dd65f..35dc59c835fb87fcb07b846787faab8f1d448b4d 100644 --- a/src/main/java/com/ippon/pouet/ApplicationWebXml.java +++ b/src/main/java/com/ippon/pouet/ApplicationWebXml.java @@ -1,12 +1,10 @@ package com.ippon.pouet; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.DefaultProfileUtil; - import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import com.ippon.pouet.common.domain.Generated; - /** * This is a helper Java class that provides an alternative to creating a {@code web.xml}. * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc. @@ -14,10 +12,10 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class ApplicationWebXml extends SpringBootServletInitializer { - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - // set a default to use when no profile is configured. - DefaultProfileUtil.addDefaultProfile(application.application()); - return application.sources(PouetApp.class); - } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + // set a default to use when no profile is configured. + DefaultProfileUtil.addDefaultProfile(application.application()); + return application.sources(PouetApp.class); + } } diff --git a/src/main/java/com/ippon/pouet/PouetApp.java b/src/main/java/com/ippon/pouet/PouetApp.java index 6d77037756b27bb0df2ebd107b6008843b2b3523..5e105098121ae7a206f515a30568909510575789 100644 --- a/src/main/java/com/ippon/pouet/PouetApp.java +++ b/src/main/java/com/ippon/pouet/PouetApp.java @@ -2,10 +2,13 @@ package com.ippon.pouet; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.ApplicationProperties; - import io.github.jhipster.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; - +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Collection; +import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,86 +18,89 @@ import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.env.Environment; -import javax.annotation.PostConstruct; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collection; - @Generated @SpringBootApplication -@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) +@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) public class PouetApp { + private static final Logger log = LoggerFactory.getLogger(PouetApp.class); - private static final Logger log = LoggerFactory.getLogger(PouetApp.class); + private final Environment env; - private final Environment env; + public PouetApp(Environment env) { + this.env = env; + } - public PouetApp(Environment env) { - this.env = env; + /** + * Initializes pouet. + * <p> + * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile + * <p> + * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>. + */ + @PostConstruct + public void initApplication() { + Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles()); + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION) + ) { + log.error( + "You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time." + ); } - - /** - * Initializes pouet. - * <p> - * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile - * <p> - * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>. - */ - @PostConstruct - public void initApplication() { - Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles()); - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { - log.error("You have misconfigured your application! It should not run " + - "with both the 'dev' and 'prod' profiles at the same time."); - } - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { - log.error("You have misconfigured your application! It should not " + - "run with both the 'dev' and 'cloud' profiles at the same time."); - } + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD) + ) { + log.error( + "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time." + ); } + } - /** - * Main method, used to run the application. - * - * @param args the command line arguments. - */ - public static void main(String[] args) { - SpringApplication app = new SpringApplication(PouetApp.class); - DefaultProfileUtil.addDefaultProfile(app); - Environment env = app.run(args).getEnvironment(); - logApplicationStartup(env); - } + /** + * Main method, used to run the application. + * + * @param args the command line arguments. + */ + public static void main(String[] args) { + SpringApplication app = new SpringApplication(PouetApp.class); + DefaultProfileUtil.addDefaultProfile(app); + Environment env = app.run(args).getEnvironment(); + logApplicationStartup(env); + } - private static void logApplicationStartup(Environment env) { - String protocol = "http"; - if (env.getProperty("server.ssl.key-store") != null) { - protocol = "https"; - } - String serverPort = env.getProperty("server.port"); - String contextPath = env.getProperty("server.servlet.context-path"); - if (StringUtils.isBlank(contextPath)) { - contextPath = "/"; - } - String hostAddress = "localhost"; - try { - hostAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - log.warn("The host name could not be determined, using `localhost` as fallback"); - } - log.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\t{}://localhost:{}{}\n\t" + - "External: \t{}://{}:{}{}\n\t" + - "Profile(s): \t{}\n----------------------------------------------------------", - env.getProperty("spring.application.name"), - protocol, - serverPort, - contextPath, - protocol, - hostAddress, - serverPort, - contextPath, - env.getActiveProfiles()); + private static void logApplicationStartup(Environment env) { + String protocol = "http"; + if (env.getProperty("server.ssl.key-store") != null) { + protocol = "https"; + } + String serverPort = env.getProperty("server.port"); + String contextPath = env.getProperty("server.servlet.context-path"); + if (StringUtils.isBlank(contextPath)) { + contextPath = "/"; + } + String hostAddress = "localhost"; + try { + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + log.warn("The host name could not be determined, using `localhost` as fallback"); } + log.info( + "\n----------------------------------------------------------\n\t" + + "Application '{}' is running! Access URLs:\n\t" + + "Local: \t\t{}://localhost:{}{}\n\t" + + "External: \t{}://{}:{}{}\n\t" + + "Profile(s): \t{}\n----------------------------------------------------------", + env.getProperty("spring.application.name"), + protocol, + serverPort, + contextPath, + protocol, + hostAddress, + serverPort, + contextPath, + env.getActiveProfiles() + ); + } } diff --git a/src/main/java/com/ippon/pouet/aop/logging/LoggingAspect.java b/src/main/java/com/ippon/pouet/aop/logging/LoggingAspect.java index 5828e3befbdfef1abfc848949c02bbb93345dae9..65f5f0bb8b34108626df7817ead7235517148a03 100644 --- a/src/main/java/com/ippon/pouet/aop/logging/LoggingAspect.java +++ b/src/main/java/com/ippon/pouet/aop/logging/LoggingAspect.java @@ -1,7 +1,8 @@ package com.ippon.pouet.aop.logging; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; - +import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; @@ -13,10 +14,6 @@ import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; -import com.ippon.pouet.common.domain.Generated; - -import java.util.Arrays; - /** * Aspect for logging execution of service and repository Spring components. * @@ -25,92 +22,87 @@ import java.util.Arrays; @Aspect @Generated public class LoggingAspect { + private final Environment env; - private final Environment env; + public LoggingAspect(Environment env) { + this.env = env; + } - public LoggingAspect(Environment env) { - this.env = env; - } + /** + * Pointcut that matches all repositories, services and Web REST endpoints. + */ + @Pointcut( + "within(@org.springframework.stereotype.Repository *)" + + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)" + ) + public void springBeanPointcut() { + // Method is empty as this is just a Pointcut, the implementations are in the advices. + } - /** - * Pointcut that matches all repositories, services and Web REST endpoints. - */ - @Pointcut("within(@org.springframework.stereotype.Repository *)" + - " || within(@org.springframework.stereotype.Service *)" + - " || within(@org.springframework.web.bind.annotation.RestController *)") - public void springBeanPointcut() { - // Method is empty as this is just a Pointcut, the implementations are in the advices. - } + /** + * Pointcut that matches all Spring beans in the application's main packages. + */ + @Pointcut("within(com.ippon.pouet.repository..*)" + " || within(com.ippon.pouet.service..*)" + " || within(com.ippon.pouet.web.rest..*)") + public void applicationPackagePointcut() { + // Method is empty as this is just a Pointcut, the implementations are in the advices. + } - /** - * Pointcut that matches all Spring beans in the application's main packages. - */ - @Pointcut("within(com.ippon.pouet.repository..*)"+ - " || within(com.ippon.pouet.service..*)"+ - " || within(com.ippon.pouet.web.rest..*)") - public void applicationPackagePointcut() { - // Method is empty as this is just a Pointcut, the implementations are in the advices. - } + /** + * Retrieves the {@link Logger} associated to the given {@link JoinPoint}. + * + * @param joinPoint join point we want the logger for. + * @return {@link Logger} associated to the given {@link JoinPoint}. + */ + private Logger logger(JoinPoint joinPoint) { + return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName()); + } - /** - * Retrieves the {@link Logger} associated to the given {@link JoinPoint}. - * - * @param joinPoint join point we want the logger for. - * @return {@link Logger} associated to the given {@link JoinPoint}. - */ - private Logger logger(JoinPoint joinPoint) { - return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName()); + /** + * Advice that logs methods throwing exceptions. + * + * @param joinPoint join point for advice. + * @param e exception. + */ + @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") + public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { + if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { + logger(joinPoint) + .error( + "Exception in {}() with cause = \'{}\' and exception = \'{}\'", + joinPoint.getSignature().getName(), + e.getCause() != null ? e.getCause() : "NULL", + e.getMessage(), + e + ); + } else { + logger(joinPoint) + .error("Exception in {}() with cause = {}", joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL"); } + } - /** - * Advice that logs methods throwing exceptions. - * - * @param joinPoint join point for advice. - * @param e exception. - */ - @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") - public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { - if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { - logger(joinPoint) - .error( - "Exception in {}() with cause = \'{}\' and exception = \'{}\'", - joinPoint.getSignature().getName(), - e.getCause() != null ? e.getCause() : "NULL", - e.getMessage(), - e - ); - } else { - logger(joinPoint) - .error( - "Exception in {}() with cause = {}", - joinPoint.getSignature().getName(), - e.getCause() != null ? e.getCause() : "NULL" - ); - } + /** + * Advice that logs when a method is entered and exited. + * + * @param joinPoint join point for advice. + * @return result. + * @throws Throwable throws {@link IllegalArgumentException}. + */ + @Around("applicationPackagePointcut() && springBeanPointcut()") + public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { + Logger log = logger(joinPoint); + if (log.isDebugEnabled()) { + log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } - - /** - * Advice that logs when a method is entered and exited. - * - * @param joinPoint join point for advice. - * @return result. - * @throws Throwable throws {@link IllegalArgumentException}. - */ - @Around("applicationPackagePointcut() && springBeanPointcut()") - public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { - Logger log = logger(joinPoint); - if (log.isDebugEnabled()) { - log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); - } - try { - Object result = joinPoint.proceed(); - if (log.isDebugEnabled()) { - log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); - } - return result; - } catch (IllegalArgumentException e) { - log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); - throw e; - } + try { + Object result = joinPoint.proceed(); + if (log.isDebugEnabled()) { + log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); + } + return result; + } catch (IllegalArgumentException e) { + log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); + throw e; } + } } diff --git a/src/main/java/com/ippon/pouet/config/ApplicationProperties.java b/src/main/java/com/ippon/pouet/config/ApplicationProperties.java index c02aef97788d45a0362a00b1f14d86993ed3fc3c..81a40d40258f5a3a8ddae42ef651bfbf4549c589 100644 --- a/src/main/java/com/ippon/pouet/config/ApplicationProperties.java +++ b/src/main/java/com/ippon/pouet/config/ApplicationProperties.java @@ -1,8 +1,7 @@ package com.ippon.pouet.config; -import org.springframework.boot.context.properties.ConfigurationProperties; - import com.ippon.pouet.common.domain.Generated; +import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to Pouet. @@ -12,5 +11,4 @@ import com.ippon.pouet.common.domain.Generated; */ @Generated @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) -public class ApplicationProperties { -} +public class ApplicationProperties {} diff --git a/src/main/java/com/ippon/pouet/config/AsyncConfiguration.java b/src/main/java/com/ippon/pouet/config/AsyncConfiguration.java index 9263c50a951fe6c1016cf0ab3757247b9219aad2..f3fd135150d5b8acecb9bc4dfa83b421c935228b 100644 --- a/src/main/java/com/ippon/pouet/config/AsyncConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/AsyncConfiguration.java @@ -1,6 +1,8 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor; +import java.util.concurrent.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; @@ -13,38 +15,33 @@ import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import com.ippon.pouet.common.domain.Generated; - -import java.util.concurrent.Executor; - @Generated @EnableAsync @Configuration @EnableScheduling public class AsyncConfiguration implements AsyncConfigurer { - - private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); - - private final TaskExecutionProperties taskExecutionProperties; - - public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { - this.taskExecutionProperties = taskExecutionProperties; - } - - @Override - @Bean(name = "taskExecutor") - public Executor getAsyncExecutor() { - log.debug("Creating Async Task Executor"); - ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); - executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); - executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity()); - executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix()); - return new ExceptionHandlingAsyncTaskExecutor(executor); - } - - @Override - public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { - return new SimpleAsyncUncaughtExceptionHandler(); - } + private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); + + private final TaskExecutionProperties taskExecutionProperties; + + public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { + this.taskExecutionProperties = taskExecutionProperties; + } + + @Override + @Bean(name = "taskExecutor") + public Executor getAsyncExecutor() { + log.debug("Creating Async Task Executor"); + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); + executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); + executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity()); + executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix()); + return new ExceptionHandlingAsyncTaskExecutor(executor); + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new SimpleAsyncUncaughtExceptionHandler(); + } } diff --git a/src/main/java/com/ippon/pouet/config/CloudDatabaseConfiguration.java b/src/main/java/com/ippon/pouet/config/CloudDatabaseConfiguration.java index 8e9169859fd6d691415321c0b4c21df52af1e9ca..65b932697663e4cd85c64e7162a9f8d45369c658 100644 --- a/src/main/java/com/ippon/pouet/config/CloudDatabaseConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/CloudDatabaseConfiguration.java @@ -1,30 +1,26 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; - +import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.*; -import com.ippon.pouet.common.domain.Generated; - -import javax.sql.DataSource; -import org.springframework.boot.context.properties.ConfigurationProperties; - @Generated @Configuration @Profile(JHipsterConstants.SPRING_PROFILE_CLOUD) public class CloudDatabaseConfiguration extends AbstractCloudConfig { + private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class); - private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class); - - private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari"; + private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari"; - @Bean - @ConfigurationProperties(CLOUD_CONFIGURATION_HIKARI_PREFIX) - public DataSource dataSource() { - log.info("Configuring JDBC datasource from a cloud provider"); - return connectionFactory().dataSource(); - } + @Bean + @ConfigurationProperties(CLOUD_CONFIGURATION_HIKARI_PREFIX) + public DataSource dataSource() { + log.info("Configuring JDBC datasource from a cloud provider"); + return connectionFactory().dataSource(); + } } diff --git a/src/main/java/com/ippon/pouet/config/Constants.java b/src/main/java/com/ippon/pouet/config/Constants.java index 26d6410cd371148bd14630c08070e7a6e063abb4..f7dacc386f887f03b1554ccec057ba575bdb2205 100644 --- a/src/main/java/com/ippon/pouet/config/Constants.java +++ b/src/main/java/com/ippon/pouet/config/Constants.java @@ -7,14 +7,12 @@ import com.ippon.pouet.common.domain.Generated; */ @Generated public final class Constants { + // Regex for acceptable logins + public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$"; - // Regex for acceptable logins - public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$"; + public static final String SYSTEM_ACCOUNT = "system"; + public static final String DEFAULT_LANGUAGE = "fr"; + public static final String ANONYMOUS_USER = "anonymoususer"; - public static final String SYSTEM_ACCOUNT = "system"; - public static final String DEFAULT_LANGUAGE = "fr"; - public static final String ANONYMOUS_USER = "anonymoususer"; - - private Constants() { - } + private Constants() {} } diff --git a/src/main/java/com/ippon/pouet/config/DatabaseConfiguration.java b/src/main/java/com/ippon/pouet/config/DatabaseConfiguration.java index 656908763cbd1412d617d2deb4ec278ff0616e6d..7972a70157d8fd1e0c63e5b4d263f1e73cb9c4c5 100644 --- a/src/main/java/com/ippon/pouet/config/DatabaseConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/DatabaseConfiguration.java @@ -1,62 +1,58 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.h2.H2ConfigurationHelper; +import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; - import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.ippon.pouet.common.domain.Generated; - -import java.sql.SQLException; - @Generated @Configuration @EnableJpaRepositories("com.ippon.pouet.repository") @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { - - private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); - - private final Environment env; - - public DatabaseConfiguration(Environment env) { - this.env = env; - } - - /** - * Open the TCP port for the H2 database, so it is available remotely. - * - * @return the H2 database TCP server. - * @throws SQLException if the server failed to start. - */ - @Bean(initMethod = "start", destroyMethod = "stop") - @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) - public Object h2TCPServer() throws SQLException { - String port = getValidPortForH2(); - log.debug("H2 database is available on port {}", port); - return H2ConfigurationHelper.createServer(port); - } - - private String getValidPortForH2() { - int port = Integer.parseInt(env.getProperty("server.port")); - if (port < 10000) { - port = 10000 + port; - } else { - if (port < 63536) { - port = port + 2000; - } else { - port = port - 2000; - } - } - return String.valueOf(port); + private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); + + private final Environment env; + + public DatabaseConfiguration(Environment env) { + this.env = env; + } + + /** + * Open the TCP port for the H2 database, so it is available remotely. + * + * @return the H2 database TCP server. + * @throws SQLException if the server failed to start. + */ + @Bean(initMethod = "start", destroyMethod = "stop") + @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) + public Object h2TCPServer() throws SQLException { + String port = getValidPortForH2(); + log.debug("H2 database is available on port {}", port); + return H2ConfigurationHelper.createServer(port); + } + + private String getValidPortForH2() { + int port = Integer.parseInt(env.getProperty("server.port")); + if (port < 10000) { + port = 10000 + port; + } else { + if (port < 63536) { + port = port + 2000; + } else { + port = port - 2000; + } } + return String.valueOf(port); + } } diff --git a/src/main/java/com/ippon/pouet/config/DateTimeFormatConfiguration.java b/src/main/java/com/ippon/pouet/config/DateTimeFormatConfiguration.java index c3caedc2164d404a37dd13d8531409f374f7bb86..68a8edb110a839bf89f2cc371776eaf36b0cdb81 100644 --- a/src/main/java/com/ippon/pouet/config/DateTimeFormatConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/DateTimeFormatConfiguration.java @@ -1,12 +1,11 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.ippon.pouet.common.domain.Generated; - /** * Configure the converters to use the ISO format for dates by default. */ @@ -14,10 +13,10 @@ import com.ippon.pouet.common.domain.Generated; @Configuration public class DateTimeFormatConfiguration implements WebMvcConfigurer { - @Override - public void addFormatters(FormatterRegistry registry) { - DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); - registrar.setUseIsoFormat(true); - registrar.registerFormatters(registry); - } + @Override + public void addFormatters(FormatterRegistry registry) { + DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); + registrar.setUseIsoFormat(true); + registrar.registerFormatters(registry); + } } diff --git a/src/main/java/com/ippon/pouet/config/JacksonConfiguration.java b/src/main/java/com/ippon/pouet/config/JacksonConfiguration.java index 7253000d7d7d1752e29ed093143464d1f3632ab9..59f745dcea476c77585f67cfdc56605a5f19214f 100644 --- a/src/main/java/com/ippon/pouet/config/JacksonConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/JacksonConfiguration.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.ippon.pouet.common.domain.Generated; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.problem.ProblemModule; @@ -14,41 +13,41 @@ import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { - /** - * Support for Java date and time API. - * @return the corresponding Jackson module. - */ - @Bean - public JavaTimeModule javaTimeModule() { - return new JavaTimeModule(); - } - - @Bean - public Jdk8Module jdk8TimeModule() { - return new Jdk8Module(); - } - - /* - * Support for Hibernate types in Jackson. - */ - @Bean - public Hibernate5Module hibernate5Module() { - return new Hibernate5Module(); - } - - /* - * Module for serialization/deserialization of RFC7807 Problem. - */ - @Bean - public ProblemModule problemModule() { - return new ProblemModule(); - } - - /* - * Module for serialization/deserialization of ConstraintViolationProblem. - */ - @Bean - public ConstraintViolationProblemModule constraintViolationProblemModule() { - return new ConstraintViolationProblemModule(); - } + /** + * Support for Java date and time API. + * @return the corresponding Jackson module. + */ + @Bean + public JavaTimeModule javaTimeModule() { + return new JavaTimeModule(); + } + + @Bean + public Jdk8Module jdk8TimeModule() { + return new Jdk8Module(); + } + + /* + * Support for Hibernate types in Jackson. + */ + @Bean + public Hibernate5Module hibernate5Module() { + return new Hibernate5Module(); + } + + /* + * Module for serialization/deserialization of RFC7807 Problem. + */ + @Bean + public ProblemModule problemModule() { + return new ProblemModule(); + } + + /* + * Module for serialization/deserialization of ConstraintViolationProblem. + */ + @Bean + public ConstraintViolationProblemModule constraintViolationProblemModule() { + return new ConstraintViolationProblemModule(); + } } diff --git a/src/main/java/com/ippon/pouet/config/LiquibaseConfiguration.java b/src/main/java/com/ippon/pouet/config/LiquibaseConfiguration.java index 73a7bc0ceb5f3185d1456550168242b8c07c9761..6388abd1eec899c39a45d6017daeb69ef80c7aaf 100644 --- a/src/main/java/com/ippon/pouet/config/LiquibaseConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/LiquibaseConfiguration.java @@ -1,7 +1,10 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.liquibase.SpringLiquibaseUtil; +import java.util.concurrent.Executor; +import javax.sql.DataSource; import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,49 +18,53 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; -import com.ippon.pouet.common.domain.Generated; - -import javax.sql.DataSource; -import java.util.concurrent.Executor; - @Generated @Configuration public class LiquibaseConfiguration { + private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); - private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); - - private final Environment env; - - public LiquibaseConfiguration(Environment env) { - this.env = env; - } + private final Environment env; - @Bean - public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor, - @LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, LiquibaseProperties liquibaseProperties, - ObjectProvider<DataSource> dataSource, DataSourceProperties dataSourceProperties) { + public LiquibaseConfiguration(Environment env) { + this.env = env; + } - // If you don't want Liquibase to start asynchronously, substitute by this: - // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); - SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); - liquibase.setChangeLog("classpath:config/liquibase/master.xml"); - liquibase.setContexts(liquibaseProperties.getContexts()); - liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); - liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema()); - liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace()); - liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); - liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); - liquibase.setDropFirst(liquibaseProperties.isDropFirst()); - liquibase.setLabels(liquibaseProperties.getLabels()); - liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); - liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); - liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); - if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) { - liquibase.setShouldRun(false); - } else { - liquibase.setShouldRun(liquibaseProperties.isEnabled()); - log.debug("Configuring Liquibase"); - } - return liquibase; + @Bean + public SpringLiquibase liquibase( + @Qualifier("taskExecutor") Executor executor, + @LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, + LiquibaseProperties liquibaseProperties, + ObjectProvider<DataSource> dataSource, + DataSourceProperties dataSourceProperties + ) { + // If you don't want Liquibase to start asynchronously, substitute by this: + // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); + SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( + this.env, + executor, + liquibaseDataSource.getIfAvailable(), + liquibaseProperties, + dataSource.getIfUnique(), + dataSourceProperties + ); + liquibase.setChangeLog("classpath:config/liquibase/master.xml"); + liquibase.setContexts(liquibaseProperties.getContexts()); + liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); + liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema()); + liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace()); + liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); + liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); + liquibase.setDropFirst(liquibaseProperties.isDropFirst()); + liquibase.setLabels(liquibaseProperties.getLabels()); + liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); + liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); + liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); + if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) { + liquibase.setShouldRun(false); + } else { + liquibase.setShouldRun(liquibaseProperties.isEnabled()); + log.debug("Configuring Liquibase"); } + return liquibase; + } } diff --git a/src/main/java/com/ippon/pouet/config/LocaleConfiguration.java b/src/main/java/com/ippon/pouet/config/LocaleConfiguration.java index a6f32b4b869c04a684e7562f45c34f2d12074084..b97ddbec0410ee7b35ef550a9397c7632e85c230 100644 --- a/src/main/java/com/ippon/pouet/config/LocaleConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/LocaleConfiguration.java @@ -1,30 +1,28 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.locale.AngularCookieLocaleResolver; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import com.ippon.pouet.common.domain.Generated; - @Generated @Configuration public class LocaleConfiguration implements WebMvcConfigurer { - @Bean - public LocaleResolver localeResolver() { - AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); - cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); - return cookieLocaleResolver; - } + @Bean + public LocaleResolver localeResolver() { + AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); + cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); + return cookieLocaleResolver; + } - @Override - public void addInterceptors(InterceptorRegistry registry) { - LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); - localeChangeInterceptor.setParamName("language"); - registry.addInterceptor(localeChangeInterceptor); - } + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("language"); + registry.addInterceptor(localeChangeInterceptor); + } } diff --git a/src/main/java/com/ippon/pouet/config/LoggingAspectConfiguration.java b/src/main/java/com/ippon/pouet/config/LoggingAspectConfiguration.java index acc5c117b5c9c717a1bc591110320eff7d643b1c..73d20c8b5d5a7e339a306e2bd296f297100ee3e7 100644 --- a/src/main/java/com/ippon/pouet/config/LoggingAspectConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/LoggingAspectConfiguration.java @@ -2,9 +2,7 @@ package com.ippon.pouet.config; import com.ippon.pouet.aop.logging.LoggingAspect; import com.ippon.pouet.common.domain.Generated; - import io.github.jhipster.config.JHipsterConstants; - import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; @@ -13,9 +11,9 @@ import org.springframework.core.env.Environment; @EnableAspectJAutoProxy public class LoggingAspectConfiguration { - @Bean - @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) - public LoggingAspect loggingAspect(Environment env) { - return new LoggingAspect(env); - } + @Bean + @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) + public LoggingAspect loggingAspect(Environment env) { + return new LoggingAspect(env); + } } diff --git a/src/main/java/com/ippon/pouet/config/LoggingConfiguration.java b/src/main/java/com/ippon/pouet/config/LoggingConfiguration.java index 98a172290136b8f63560a4fd3cd445e4d775db8d..88199be37d0a3cf64c10c592483fbe74d26c6015 100644 --- a/src/main/java/com/ippon/pouet/config/LoggingConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/LoggingConfiguration.java @@ -1,20 +1,18 @@ package com.ippon.pouet.config; +import static io.github.jhipster.config.logging.LoggingUtils.*; + import ch.qos.logback.classic.LoggerContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ippon.pouet.common.domain.Generated; - import io.github.jhipster.config.JHipsterProperties; +import java.util.HashMap; +import java.util.Map; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; -import java.util.HashMap; -import java.util.Map; - -import static io.github.jhipster.config.logging.LoggingUtils.*; - /* * Configures the console and Logstash log appenders from the app properties */ @@ -22,32 +20,34 @@ import static io.github.jhipster.config.logging.LoggingUtils.*; @Configuration public class LoggingConfiguration { - public LoggingConfiguration(@Value("${spring.application.name}") String appName, - @Value("${server.port}") String serverPort, - JHipsterProperties jHipsterProperties, - ObjectMapper mapper) throws JsonProcessingException { - - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - - Map<String, String> map = new HashMap<>(); - map.put("app_name", appName); - map.put("app_port", serverPort); - String customFields = mapper.writeValueAsString(map); - - JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging(); - JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash(); - - if (loggingProperties.isUseJsonFormat()) { - addJsonConsoleAppender(context, customFields); - } - if (logstashProperties.isEnabled()) { - addLogstashTcpSocketAppender(context, customFields, logstashProperties); - } - if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) { - addContextListener(context, customFields, loggingProperties); - } - if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { - setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat()); - } + public LoggingConfiguration( + @Value("${spring.application.name}") String appName, + @Value("${server.port}") String serverPort, + JHipsterProperties jHipsterProperties, + ObjectMapper mapper + ) + throws JsonProcessingException { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + + Map<String, String> map = new HashMap<>(); + map.put("app_name", appName); + map.put("app_port", serverPort); + String customFields = mapper.writeValueAsString(map); + + JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging(); + JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash(); + + if (loggingProperties.isUseJsonFormat()) { + addJsonConsoleAppender(context, customFields); + } + if (logstashProperties.isEnabled()) { + addLogstashTcpSocketAppender(context, customFields, logstashProperties); + } + if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) { + addContextListener(context, customFields, loggingProperties); + } + if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { + setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat()); } + } } diff --git a/src/main/java/com/ippon/pouet/config/SecurityConfiguration.java b/src/main/java/com/ippon/pouet/config/SecurityConfiguration.java index 8a632743e415dda535addcf3c99af7346a7809be..a3370565801e25692528183f04afff3e10611562 100644 --- a/src/main/java/com/ippon/pouet/config/SecurityConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/SecurityConfiguration.java @@ -3,7 +3,6 @@ package com.ippon.pouet.config; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.security.*; import com.ippon.pouet.security.jwt.*; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; @@ -25,38 +24,38 @@ import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport; @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @Import(SecurityProblemSupport.class) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + private final TokenProvider tokenProvider; - private final TokenProvider tokenProvider; - - private final CorsFilter corsFilter; - private final SecurityProblemSupport problemSupport; + private final CorsFilter corsFilter; + private final SecurityProblemSupport problemSupport; - public SecurityConfiguration(TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) { - this.tokenProvider = tokenProvider; - this.corsFilter = corsFilter; - this.problemSupport = problemSupport; - } + public SecurityConfiguration(TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) { + this.tokenProvider = tokenProvider; + this.corsFilter = corsFilter; + this.problemSupport = problemSupport; + } - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } - @Override - public void configure(WebSecurity web) { - web.ignoring() - .antMatchers(HttpMethod.OPTIONS, "/**") - .antMatchers("/app/**/*.{js,html}") - .antMatchers("/i18n/**") - .antMatchers("/content/**") - .antMatchers("/h2-console/**") - .antMatchers("/swagger-ui/index.html") - .antMatchers("/test/**"); - } + @Override + public void configure(WebSecurity web) { + web + .ignoring() + .antMatchers(HttpMethod.OPTIONS, "/**") + .antMatchers("/app/**/*.{js,html}") + .antMatchers("/i18n/**") + .antMatchers("/content/**") + .antMatchers("/h2-console/**") + .antMatchers("/swagger-ui/index.html") + .antMatchers("/test/**"); + } - @Override - public void configure(HttpSecurity http) throws Exception { - // @formatter:off + @Override + public void configure(HttpSecurity http) throws Exception { + // @formatter:off http .csrf() .disable() @@ -93,10 +92,10 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .httpBasic() .and() .apply(securityConfigurerAdapter()); - // @formatter:on - } + // @formatter:on + } - private JWTConfigurer securityConfigurerAdapter() { - return new JWTConfigurer(tokenProvider); - } + private JWTConfigurer securityConfigurerAdapter() { + return new JWTConfigurer(tokenProvider); + } } diff --git a/src/main/java/com/ippon/pouet/config/StaticResourcesWebConfiguration.java b/src/main/java/com/ippon/pouet/config/StaticResourcesWebConfiguration.java index c59a94dd292c47d5bd9493d4c72cb0efce152c64..0952549ab0d73d30a18513fd03bcdad2b0d7d77d 100644 --- a/src/main/java/com/ippon/pouet/config/StaticResourcesWebConfiguration.java +++ b/src/main/java/com/ippon/pouet/config/StaticResourcesWebConfiguration.java @@ -1,7 +1,9 @@ package com.ippon.pouet.config; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; +import java.util.concurrent.TimeUnit; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.http.CacheControl; @@ -9,44 +11,42 @@ import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistra import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.ippon.pouet.common.domain.Generated; - -import java.util.concurrent.TimeUnit; - @Generated @Configuration -@Profile({JHipsterConstants.SPRING_PROFILE_PRODUCTION}) +@Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION }) public class StaticResourcesWebConfiguration implements WebMvcConfigurer { - - protected static final String[] RESOURCE_LOCATIONS = new String[]{"classpath:/static/app/", "classpath:/static/content/", "classpath:/static/i18n/"}; - protected static final String[] RESOURCE_PATHS = new String[]{"/app/*", "/content/*", "/i18n/*"}; - - private final JHipsterProperties jhipsterProperties; - - public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) { - this.jhipsterProperties = jHipsterProperties; - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry); - initializeResourceHandler(resourceHandlerRegistration); - } - - protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) { - return registry.addResourceHandler(RESOURCE_PATHS); - } - - protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) { - resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl()); - } - - protected CacheControl getCacheControl() { - return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic(); - } - - private int getJHipsterHttpCacheProperty() { - return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays(); - } - + protected static final String[] RESOURCE_LOCATIONS = new String[] { + "classpath:/static/app/", + "classpath:/static/content/", + "classpath:/static/i18n/", + }; + protected static final String[] RESOURCE_PATHS = new String[] { "/app/*", "/content/*", "/i18n/*" }; + + private final JHipsterProperties jhipsterProperties; + + public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) { + this.jhipsterProperties = jHipsterProperties; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry); + initializeResourceHandler(resourceHandlerRegistration); + } + + protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) { + return registry.addResourceHandler(RESOURCE_PATHS); + } + + protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) { + resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl()); + } + + protected CacheControl getCacheControl() { + return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic(); + } + + private int getJHipsterHttpCacheProperty() { + return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays(); + } } diff --git a/src/main/java/com/ippon/pouet/config/WebConfigurer.java b/src/main/java/com/ippon/pouet/config/WebConfigurer.java index f3461ea5b40434bec3c39d953b5bf693410d83a6..9c219ab5bdfc5135437a79e7ef774863a2251ce1 100644 --- a/src/main/java/com/ippon/pouet/config/WebConfigurer.java +++ b/src/main/java/com/ippon/pouet/config/WebConfigurer.java @@ -1,8 +1,16 @@ package com.ippon.pouet.config; +import static java.net.URLDecoder.decode; + +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.config.h2.H2ConfigurationHelper; +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import javax.servlet.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.server.*; @@ -17,120 +25,107 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; -import com.ippon.pouet.common.domain.Generated; - -import javax.servlet.*; -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; - -import static java.net.URLDecoder.decode; - /** * Configuration of web application with Servlet 3.0 APIs. */ @Generated @Configuration public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { + private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); - private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); + private final Environment env; - private final Environment env; - - private final JHipsterProperties jHipsterProperties; - - public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { - this.env = env; - this.jHipsterProperties = jHipsterProperties; - } + private final JHipsterProperties jHipsterProperties; - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - if (env.getActiveProfiles().length != 0) { - log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); - } + public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { + this.env = env; + this.jHipsterProperties = jHipsterProperties; + } - if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { - initH2Console(servletContext); - } - log.info("Web application fully configured"); + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + if (env.getActiveProfiles().length != 0) { + log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } - /** - * Customize the Servlet engine: Mime types, the document root, the cache. - */ - @Override - public void customize(WebServerFactory server) { - setMimeMappings(server); - // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. - setLocationForStaticAssets(server); + if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { + initH2Console(servletContext); } - - private void setMimeMappings(WebServerFactory server) { - if (server instanceof ConfigurableServletWebServerFactory) { - MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); - // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 - mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); - // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64 - mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); - ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; - servletWebServer.setMimeMappings(mappings); - } + log.info("Web application fully configured"); + } + + /** + * Customize the Servlet engine: Mime types, the document root, the cache. + */ + @Override + public void customize(WebServerFactory server) { + setMimeMappings(server); + // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. + setLocationForStaticAssets(server); + } + + private void setMimeMappings(WebServerFactory server) { + if (server instanceof ConfigurableServletWebServerFactory) { + MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); + // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 + mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); + // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64 + mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); + ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; + servletWebServer.setMimeMappings(mappings); } - - private void setLocationForStaticAssets(WebServerFactory server) { - if (server instanceof ConfigurableServletWebServerFactory) { - ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; - File root; - String prefixPath = resolvePathPrefix(); - root = new File(prefixPath + "target/classes/static/"); - if (root.exists() && root.isDirectory()) { - servletWebServer.setDocumentRoot(root); - } - } + } + + private void setLocationForStaticAssets(WebServerFactory server) { + if (server instanceof ConfigurableServletWebServerFactory) { + ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; + File root; + String prefixPath = resolvePathPrefix(); + root = new File(prefixPath + "target/classes/static/"); + if (root.exists() && root.isDirectory()) { + servletWebServer.setDocumentRoot(root); + } } - - /** - * Resolve path prefix to static resources. - */ - private String resolvePathPrefix() { - String fullExecutablePath; - try { - fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - /* try without decoding if this ever happens */ - fullExecutablePath = this.getClass().getResource("").getPath(); - } - String rootPath = Paths.get(".").toUri().normalize().getPath(); - String extractedPath = fullExecutablePath.replace(rootPath, ""); - int extractionEndIndex = extractedPath.indexOf("target/"); - if (extractionEndIndex <= 0) { - return ""; - } - return extractedPath.substring(0, extractionEndIndex); + } + + /** + * Resolve path prefix to static resources. + */ + private String resolvePathPrefix() { + String fullExecutablePath; + try { + fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + /* try without decoding if this ever happens */ + fullExecutablePath = this.getClass().getResource("").getPath(); } - - - @Bean - public CorsFilter corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = jHipsterProperties.getCors(); - if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { - log.debug("Registering CORS filter"); - source.registerCorsConfiguration("/api/**", config); - source.registerCorsConfiguration("/management/**", config); - source.registerCorsConfiguration("/v2/api-docs", config); - } - return new CorsFilter(source); + String rootPath = Paths.get(".").toUri().normalize().getPath(); + String extractedPath = fullExecutablePath.replace(rootPath, ""); + int extractionEndIndex = extractedPath.indexOf("target/"); + if (extractionEndIndex <= 0) { + return ""; } - - /** - * Initializes H2 console. - */ - private void initH2Console(ServletContext servletContext) { - log.debug("Initialize H2 console"); - H2ConfigurationHelper.initH2Console(servletContext); + return extractedPath.substring(0, extractionEndIndex); + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = jHipsterProperties.getCors(); + if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { + log.debug("Registering CORS filter"); + source.registerCorsConfiguration("/api/**", config); + source.registerCorsConfiguration("/management/**", config); + source.registerCorsConfiguration("/v2/api-docs", config); } - + return new CorsFilter(source); + } + + /** + * Initializes H2 console. + */ + private void initH2Console(ServletContext servletContext) { + log.debug("Initialize H2 console"); + H2ConfigurationHelper.initH2Console(servletContext); + } } diff --git a/src/main/java/com/ippon/pouet/config/audit/AuditEventConverter.java b/src/main/java/com/ippon/pouet/config/audit/AuditEventConverter.java index 2b3947132cf2b02b991c854c3e080cbae3b5dd97..00fba4303c268259a5b9926de889e9d49af4d720 100644 --- a/src/main/java/com/ippon/pouet/config/audit/AuditEventConverter.java +++ b/src/main/java/com/ippon/pouet/config/audit/AuditEventConverter.java @@ -2,87 +2,89 @@ package com.ippon.pouet.config.audit; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.domain.PersistentAuditEvent; - +import java.util.*; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; -import java.util.*; - @Generated @Component public class AuditEventConverter { - /** - * Convert a list of {@link PersistentAuditEvent}s to a list of {@link AuditEvent}s. - * - * @param persistentAuditEvents the list to convert. - * @return the converted list. - */ - public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) { - if (persistentAuditEvents == null) { - return Collections.emptyList(); - } - List<AuditEvent> auditEvents = new ArrayList<>(); - for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) { - auditEvents.add(convertToAuditEvent(persistentAuditEvent)); - } - return auditEvents; + /** + * Convert a list of {@link PersistentAuditEvent}s to a list of {@link AuditEvent}s. + * + * @param persistentAuditEvents the list to convert. + * @return the converted list. + */ + public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) { + if (persistentAuditEvents == null) { + return Collections.emptyList(); + } + List<AuditEvent> auditEvents = new ArrayList<>(); + for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) { + auditEvents.add(convertToAuditEvent(persistentAuditEvent)); } + return auditEvents; + } - /** - * Convert a {@link PersistentAuditEvent} to an {@link AuditEvent}. - * - * @param persistentAuditEvent the event to convert. - * @return the converted list. - */ - public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) { - if (persistentAuditEvent == null) { - return null; - } - return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(), - persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); + /** + * Convert a {@link PersistentAuditEvent} to an {@link AuditEvent}. + * + * @param persistentAuditEvent the event to convert. + * @return the converted list. + */ + public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) { + if (persistentAuditEvent == null) { + return null; } + return new AuditEvent( + persistentAuditEvent.getAuditEventDate(), + persistentAuditEvent.getPrincipal(), + persistentAuditEvent.getAuditEventType(), + convertDataToObjects(persistentAuditEvent.getData()) + ); + } - /** - * Internal conversion. This is needed to support the current SpringBoot actuator {@code AuditEventRepository} interface. - * - * @param data the data to convert. - * @return a map of {@link String}, {@link Object}. - */ - public Map<String, Object> convertDataToObjects(Map<String, String> data) { - Map<String, Object> results = new HashMap<>(); + /** + * Internal conversion. This is needed to support the current SpringBoot actuator {@code AuditEventRepository} interface. + * + * @param data the data to convert. + * @return a map of {@link String}, {@link Object}. + */ + public Map<String, Object> convertDataToObjects(Map<String, String> data) { + Map<String, Object> results = new HashMap<>(); - if (data != null) { - for (Map.Entry<String, String> entry : data.entrySet()) { - results.put(entry.getKey(), entry.getValue()); - } - } - return results; + if (data != null) { + for (Map.Entry<String, String> entry : data.entrySet()) { + results.put(entry.getKey(), entry.getValue()); + } } + return results; + } - /** - * Internal conversion. This method will allow to save additional data. - * By default, it will save the object as string. - * - * @param data the data to convert. - * @return a map of {@link String}, {@link String}. - */ - public Map<String, String> convertDataToStrings(Map<String, Object> data) { - Map<String, String> results = new HashMap<>(); + /** + * Internal conversion. This method will allow to save additional data. + * By default, it will save the object as string. + * + * @param data the data to convert. + * @return a map of {@link String}, {@link String}. + */ + public Map<String, String> convertDataToStrings(Map<String, Object> data) { + Map<String, String> results = new HashMap<>(); - if (data != null) { - for (Map.Entry<String, Object> entry : data.entrySet()) { - // Extract the data that will be saved. - if (entry.getValue() instanceof WebAuthenticationDetails) { - WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue(); - results.put("remoteAddress", authenticationDetails.getRemoteAddress()); - results.put("sessionId", authenticationDetails.getSessionId()); - } else { - results.put(entry.getKey(), Objects.toString(entry.getValue())); - } - } + if (data != null) { + for (Map.Entry<String, Object> entry : data.entrySet()) { + // Extract the data that will be saved. + if (entry.getValue() instanceof WebAuthenticationDetails) { + WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue(); + results.put("remoteAddress", authenticationDetails.getRemoteAddress()); + results.put("sessionId", authenticationDetails.getSessionId()); + } else { + results.put(entry.getKey(), Objects.toString(entry.getValue())); } - return results; + } } + return results; + } } diff --git a/src/main/java/com/ippon/pouet/domain/AbstractAuditingEntity.java b/src/main/java/com/ippon/pouet/domain/AbstractAuditingEntity.java index 6ef947c04af49b000ba819fdb5cecb7f419a9e0f..48907c7599560a07b1c701298c0af9fa40b1f071 100644 --- a/src/main/java/com/ippon/pouet/domain/AbstractAuditingEntity.java +++ b/src/main/java/com/ippon/pouet/domain/AbstractAuditingEntity.java @@ -2,18 +2,16 @@ package com.ippon.pouet.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.ippon.pouet.common.domain.Generated; - -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - import java.io.Serializable; import java.time.Instant; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; /** * Base abstract class for entities which will hold definitions for created, last modified, created by, @@ -23,58 +21,57 @@ import javax.persistence.MappedSuperclass; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity implements Serializable { - - private static final long serialVersionUID = 1L; - - @CreatedBy - @Column(name = "created_by", nullable = false, length = 50, updatable = false) - @JsonIgnore - private String createdBy; - - @CreatedDate - @Column(name = "created_date", updatable = false) - @JsonIgnore - private Instant createdDate = Instant.now(); - - @LastModifiedBy - @Column(name = "last_modified_by", length = 50) - @JsonIgnore - private String lastModifiedBy; - - @LastModifiedDate - @Column(name = "last_modified_date") - @JsonIgnore - private Instant lastModifiedDate = Instant.now(); - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Instant getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Instant createdDate) { - this.createdDate = createdDate; - } - - public String getLastModifiedBy() { - return lastModifiedBy; - } - - public void setLastModifiedBy(String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } - - public Instant getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(Instant lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } + private static final long serialVersionUID = 1L; + + @CreatedBy + @Column(name = "created_by", nullable = false, length = 50, updatable = false) + @JsonIgnore + private String createdBy; + + @CreatedDate + @Column(name = "created_date", updatable = false) + @JsonIgnore + private Instant createdDate = Instant.now(); + + @LastModifiedBy + @Column(name = "last_modified_by", length = 50) + @JsonIgnore + private String lastModifiedBy; + + @LastModifiedDate + @Column(name = "last_modified_date") + @JsonIgnore + private Instant lastModifiedDate = Instant.now(); + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Instant getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Instant createdDate) { + this.createdDate = createdDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } } diff --git a/src/main/java/com/ippon/pouet/domain/Authority.java b/src/main/java/com/ippon/pouet/domain/Authority.java index 8d645de092b348258e3d8506f61356aa5c542e58..479df7a704d3e9df39c31bd743565f25e0906c13 100644 --- a/src/main/java/com/ippon/pouet/domain/Authority.java +++ b/src/main/java/com/ippon/pouet/domain/Authority.java @@ -1,17 +1,15 @@ package com.ippon.pouet.domain; +import com.ippon.pouet.common.domain.Generated; +import java.io.Serializable; +import java.util.Objects; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import javax.persistence.Column; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import com.ippon.pouet.common.domain.Generated; - -import java.io.Serializable; -import java.util.Objects; - /** * An authority (a security role) used by Spring Security. */ @@ -19,40 +17,39 @@ import java.util.Objects; @Generated @Table(name = "jhi_authority") public class Authority implements Serializable { - - private static final long serialVersionUID = 1L; - - @NotNull - @Size(max = 50) - @Id - @Column(length = 50) - private String name; - - public String getName() { - return name; + private static final long serialVersionUID = 1L; + + @NotNull + @Size(max = 50) + @Id + @Column(length = 50) + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - public void setName(String name) { - this.name = name; + if (!(o instanceof Authority)) { + return false; } + return Objects.equals(name, ((Authority) o).name); + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Authority)) { - return false; - } - return Objects.equals(name, ((Authority) o).name); - } - - @Override - public int hashCode() { - return Objects.hashCode(name); - } + @Override + public int hashCode() { + return Objects.hashCode(name); + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "Authority{" + diff --git a/src/main/java/com/ippon/pouet/domain/PersistentAuditEvent.java b/src/main/java/com/ippon/pouet/domain/PersistentAuditEvent.java index d2ecc625bf2c4d20c486cbe7b125f519098fb463..b8fb7af85e2e3a8cb3cb60a5e37e738df687ded4 100644 --- a/src/main/java/com/ippon/pouet/domain/PersistentAuditEvent.java +++ b/src/main/java/com/ippon/pouet/domain/PersistentAuditEvent.java @@ -1,11 +1,11 @@ package com.ippon.pouet.domain; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.HashMap; import java.util.Map; +import javax.persistence.*; +import javax.validation.constraints.NotNull; /** * Persist AuditEvent managed by the Spring Boot actuator. @@ -15,88 +15,87 @@ import java.util.Map; @Entity @Table(name = "jhi_persistent_audit_event") public class PersistentAuditEvent implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") - @SequenceGenerator(name = "sequenceGenerator") - @Column(name = "event_id") - private Long id; - - @NotNull - @Column(nullable = false) - private String principal; - - @Column(name = "event_date") - private Instant auditEventDate; - - @Column(name = "event_type") - private String auditEventType; - - @ElementCollection - @MapKeyColumn(name = "name") - @Column(name = "value") - @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) - private Map<String, String> data = new HashMap<>(); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @Column(name = "event_id") + private Long id; + + @NotNull + @Column(nullable = false) + private String principal; + + @Column(name = "event_date") + private Instant auditEventDate; + + @Column(name = "event_type") + private String auditEventType; + + @ElementCollection + @MapKeyColumn(name = "name") + @Column(name = "value") + @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns = @JoinColumn(name = "event_id")) + private Map<String, String> data = new HashMap<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getPrincipal() { + return principal; + } + + public void setPrincipal(String principal) { + this.principal = principal; + } + + public Instant getAuditEventDate() { + return auditEventDate; + } + + public void setAuditEventDate(Instant auditEventDate) { + this.auditEventDate = auditEventDate; + } + + public String getAuditEventType() { + return auditEventType; + } + + public void setAuditEventType(String auditEventType) { + this.auditEventType = auditEventType; + } + + public Map<String, String> getData() { + return data; + } + + public void setData(Map<String, String> data) { + this.data = data; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - public String getPrincipal() { - return principal; - } - - public void setPrincipal(String principal) { - this.principal = principal; + if (!(o instanceof PersistentAuditEvent)) { + return false; } + return id != null && id.equals(((PersistentAuditEvent) o).id); + } - public Instant getAuditEventDate() { - return auditEventDate; - } - - public void setAuditEventDate(Instant auditEventDate) { - this.auditEventDate = auditEventDate; - } - - public String getAuditEventType() { - return auditEventType; - } - - public void setAuditEventType(String auditEventType) { - this.auditEventType = auditEventType; - } - - public Map<String, String> getData() { - return data; - } - - public void setData(Map<String, String> data) { - this.data = data; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof PersistentAuditEvent)) { - return false; - } - return id != null && id.equals(((PersistentAuditEvent) o).id); - } - - @Override - public int hashCode() { - return 31; - } + @Override + public int hashCode() { + return 31; + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "PersistentAuditEvent{" + diff --git a/src/main/java/com/ippon/pouet/domain/User.java b/src/main/java/com/ippon/pouet/domain/User.java index f967248cf96ae8bead463d59a9d2b5cfa1b4b92f..7c7b39e62eeea206ced2a43c06334faeee6a1109 100644 --- a/src/main/java/com/ippon/pouet/domain/User.java +++ b/src/main/java/com/ippon/pouet/domain/User.java @@ -1,22 +1,20 @@ package com.ippon.pouet.domain; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.Constants; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.annotations.BatchSize; - -import javax.persistence.*; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Locale; import java.util.Set; +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.annotations.BatchSize; /** * A user. @@ -25,196 +23,195 @@ import java.util.Set; @Generated @Table(name = "jhi_user") public class User extends AbstractAuditingEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + private Long id; + + @NotNull + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + @Column(length = 50, unique = true, nullable = false) + private String login; + + @JsonIgnore + @NotNull + @Size(min = 60, max = 60) + @Column(name = "password_hash", length = 60, nullable = false) + private String password; + + @Size(max = 50) + @Column(name = "first_name", length = 50) + private String firstName; + + @Size(max = 50) + @Column(name = "last_name", length = 50) + private String lastName; + + @Email + @Size(min = 5, max = 254) + @Column(length = 254, unique = true) + private String email; + + @NotNull + @Column(nullable = false) + private boolean activated = false; + + @Size(min = 2, max = 10) + @Column(name = "lang_key", length = 10) + private String langKey; + + @Size(max = 256) + @Column(name = "image_url", length = 256) + private String imageUrl; + + @Size(max = 20) + @Column(name = "activation_key", length = 20) + @JsonIgnore + private String activationKey; + + @Size(max = 20) + @Column(name = "reset_key", length = 20) + @JsonIgnore + private String resetKey; + + @Column(name = "reset_date") + private Instant resetDate = null; + + @JsonIgnore + @ManyToMany + @JoinTable( + name = "jhi_user_authority", + joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, + inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") } + ) + @BatchSize(size = 20) + private Set<Authority> authorities = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + // Lowercase the login before saving it in database + public void setLogin(String login) { + this.login = StringUtils.lowerCase(login, Locale.ENGLISH); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public boolean getActivated() { + return activated; + } + + public void setActivated(boolean activated) { + this.activated = activated; + } + + public String getActivationKey() { + return activationKey; + } + + public void setActivationKey(String activationKey) { + this.activationKey = activationKey; + } + + public String getResetKey() { + return resetKey; + } + + public void setResetKey(String resetKey) { + this.resetKey = resetKey; + } + + public Instant getResetDate() { + return resetDate; + } + + public void setResetDate(Instant resetDate) { + this.resetDate = resetDate; + } + + public String getLangKey() { + return langKey; + } + + public void setLangKey(String langKey) { + this.langKey = langKey; + } - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") - @SequenceGenerator(name = "sequenceGenerator") - private Long id; - - @NotNull - @Pattern(regexp = Constants.LOGIN_REGEX) - @Size(min = 1, max = 50) - @Column(length = 50, unique = true, nullable = false) - private String login; - - @JsonIgnore - @NotNull - @Size(min = 60, max = 60) - @Column(name = "password_hash", length = 60, nullable = false) - private String password; - - @Size(max = 50) - @Column(name = "first_name", length = 50) - private String firstName; - - @Size(max = 50) - @Column(name = "last_name", length = 50) - private String lastName; - - @Email - @Size(min = 5, max = 254) - @Column(length = 254, unique = true) - private String email; - - @NotNull - @Column(nullable = false) - private boolean activated = false; - - @Size(min = 2, max = 10) - @Column(name = "lang_key", length = 10) - private String langKey; - - @Size(max = 256) - @Column(name = "image_url", length = 256) - private String imageUrl; - - @Size(max = 20) - @Column(name = "activation_key", length = 20) - @JsonIgnore - private String activationKey; - - @Size(max = 20) - @Column(name = "reset_key", length = 20) - @JsonIgnore - private String resetKey; - - @Column(name = "reset_date") - private Instant resetDate = null; - - @JsonIgnore - @ManyToMany - @JoinTable( - name = "jhi_user_authority", - joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) - @BatchSize(size = 20) - private Set<Authority> authorities = new HashSet<>(); - - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getLogin() { - return login; - } - - // Lowercase the login before saving it in database - public void setLogin(String login) { - this.login = StringUtils.lowerCase(login, Locale.ENGLISH); - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getImageUrl() { - return imageUrl; - } - - public void setImageUrl(String imageUrl) { - this.imageUrl = imageUrl; - } + public Set<Authority> getAuthorities() { + return authorities; + } - public boolean getActivated() { - return activated; - } + public void setAuthorities(Set<Authority> authorities) { + this.authorities = authorities; + } - public void setActivated(boolean activated) { - this.activated = activated; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - public String getActivationKey() { - return activationKey; - } - - public void setActivationKey(String activationKey) { - this.activationKey = activationKey; - } - - public String getResetKey() { - return resetKey; - } - - public void setResetKey(String resetKey) { - this.resetKey = resetKey; + if (!(o instanceof User)) { + return false; } + return id != null && id.equals(((User) o).id); + } - public Instant getResetDate() { - return resetDate; - } - - public void setResetDate(Instant resetDate) { - this.resetDate = resetDate; - } - - public String getLangKey() { - return langKey; - } - - public void setLangKey(String langKey) { - this.langKey = langKey; - } - - public Set<Authority> getAuthorities() { - return authorities; - } - - public void setAuthorities(Set<Authority> authorities) { - this.authorities = authorities; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof User)) { - return false; - } - return id != null && id.equals(((User) o).id); - } - - @Override - public int hashCode() { - return 31; - } + @Override + public int hashCode() { + return 31; + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "User{" + diff --git a/src/main/java/com/ippon/pouet/repository/AuthorityRepository.java b/src/main/java/com/ippon/pouet/repository/AuthorityRepository.java index 9736636fe7f21a1ab71f9c83c55c7f909e67bc92..4cd874b87ebd39b552c7b673db687b65c5bb95ab 100644 --- a/src/main/java/com/ippon/pouet/repository/AuthorityRepository.java +++ b/src/main/java/com/ippon/pouet/repository/AuthorityRepository.java @@ -1,11 +1,9 @@ package com.ippon.pouet.repository; import com.ippon.pouet.domain.Authority; - import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the {@link Authority} entity. */ -public interface AuthorityRepository extends JpaRepository<Authority, String> { -} +public interface AuthorityRepository extends JpaRepository<Authority, String> {} diff --git a/src/main/java/com/ippon/pouet/repository/CustomAuditEventRepository.java b/src/main/java/com/ippon/pouet/repository/CustomAuditEventRepository.java index 8071827751cc9894088802c5092041b8e4deae93..2c38bd0449d2ec3cc751224af7a0e6d0af4566ca 100644 --- a/src/main/java/com/ippon/pouet/repository/CustomAuditEventRepository.java +++ b/src/main/java/com/ippon/pouet/repository/CustomAuditEventRepository.java @@ -4,7 +4,8 @@ import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.Constants; import com.ippon.pouet.config.audit.AuditEventConverter; import com.ippon.pouet.domain.PersistentAuditEvent; - +import java.time.Instant; +import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; @@ -13,79 +14,81 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.*; - /** * An implementation of Spring Boot's {@link AuditEventRepository}. */ @Generated @Repository public class CustomAuditEventRepository implements AuditEventRepository { - - private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE"; - - /** - * Should be the same as in Liquibase migration. - */ - protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255; - - private final PersistenceAuditEventRepository persistenceAuditEventRepository; - - private final AuditEventConverter auditEventConverter; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter) { - - this.persistenceAuditEventRepository = persistenceAuditEventRepository; - this.auditEventConverter = auditEventConverter; - } - - @Override - public List<AuditEvent> find(String principal, Instant after, String type) { - Iterable<PersistentAuditEvent> persistentAuditEvents = - persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type); - return auditEventConverter.convertToAuditEvent(persistentAuditEvents); - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public void add(AuditEvent event) { - if (!AUTHORIZATION_FAILURE.equals(event.getType()) && - !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { - - PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); - persistentAuditEvent.setPrincipal(event.getPrincipal()); - persistentAuditEvent.setAuditEventType(event.getType()); - persistentAuditEvent.setAuditEventDate(event.getTimestamp()); - Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData()); - persistentAuditEvent.setData(truncate(eventData)); - persistenceAuditEventRepository.save(persistentAuditEvent); - } + private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE"; + + /** + * Should be the same as in Liquibase migration. + */ + protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255; + + private final PersistenceAuditEventRepository persistenceAuditEventRepository; + + private final AuditEventConverter auditEventConverter; + + private final Logger log = LoggerFactory.getLogger(getClass()); + + public CustomAuditEventRepository( + PersistenceAuditEventRepository persistenceAuditEventRepository, + AuditEventConverter auditEventConverter + ) { + this.persistenceAuditEventRepository = persistenceAuditEventRepository; + this.auditEventConverter = auditEventConverter; + } + + @Override + public List<AuditEvent> find(String principal, Instant after, String type) { + Iterable<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType( + principal, + after, + type + ); + return auditEventConverter.convertToAuditEvent(persistentAuditEvents); + } + + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void add(AuditEvent event) { + if (!AUTHORIZATION_FAILURE.equals(event.getType()) && !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { + PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); + persistentAuditEvent.setPrincipal(event.getPrincipal()); + persistentAuditEvent.setAuditEventType(event.getType()); + persistentAuditEvent.setAuditEventDate(event.getTimestamp()); + Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData()); + persistentAuditEvent.setData(truncate(eventData)); + persistenceAuditEventRepository.save(persistentAuditEvent); } - - /** - * Truncate event data that might exceed column length. - */ - private Map<String, String> truncate(Map<String, String> data) { - Map<String, String> results = new HashMap<>(); - - if (data != null) { - for (Map.Entry<String, String> entry : data.entrySet()) { - String value = entry.getValue(); - if (value != null) { - int length = value.length(); - if (length > EVENT_DATA_COLUMN_MAX_LENGTH) { - value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH); - log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", - entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH); - } - } - results.put(entry.getKey(), value); - } + } + + /** + * Truncate event data that might exceed column length. + */ + private Map<String, String> truncate(Map<String, String> data) { + Map<String, String> results = new HashMap<>(); + + if (data != null) { + for (Map.Entry<String, String> entry : data.entrySet()) { + String value = entry.getValue(); + if (value != null) { + int length = value.length(); + if (length > EVENT_DATA_COLUMN_MAX_LENGTH) { + value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH); + log.warn( + "Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", + entry.getKey(), + length, + EVENT_DATA_COLUMN_MAX_LENGTH + ); + } } - return results; + results.put(entry.getKey(), value); + } } + return results; + } } diff --git a/src/main/java/com/ippon/pouet/repository/PersistenceAuditEventRepository.java b/src/main/java/com/ippon/pouet/repository/PersistenceAuditEventRepository.java index 7487fff962b459755330b914d2d169f2559d04be..efcfeecf73074ed8af73064f46193eba3ef8476f 100644 --- a/src/main/java/com/ippon/pouet/repository/PersistenceAuditEventRepository.java +++ b/src/main/java/com/ippon/pouet/repository/PersistenceAuditEventRepository.java @@ -1,23 +1,21 @@ package com.ippon.pouet.repository; import com.ippon.pouet.domain.PersistentAuditEvent; +import java.time.Instant; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; -import java.time.Instant; -import java.util.List; - /** * Spring Data JPA repository for the {@link PersistentAuditEvent} entity. */ public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> { + List<PersistentAuditEvent> findByPrincipal(String principal); - List<PersistentAuditEvent> findByPrincipal(String principal); - - List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type); + List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type); - Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable); + Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable); - List<PersistentAuditEvent> findByAuditEventDateBefore(Instant before); + List<PersistentAuditEvent> findByAuditEventDateBefore(Instant before); } diff --git a/src/main/java/com/ippon/pouet/repository/UserRepository.java b/src/main/java/com/ippon/pouet/repository/UserRepository.java index f83322ead0338251be3614c05c90e2833b3c2fd6..99c7f69eb72ed34554729d70ec23d2541695342e 100644 --- a/src/main/java/com/ippon/pouet/repository/UserRepository.java +++ b/src/main/java/com/ippon/pouet/repository/UserRepository.java @@ -1,38 +1,35 @@ package com.ippon.pouet.repository; import com.ippon.pouet.domain.User; - +import java.time.Instant; +import java.util.List; +import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.List; -import java.util.Optional; -import java.time.Instant; - /** * Spring Data JPA repository for the {@link User} entity. */ @Repository public interface UserRepository extends JpaRepository<User, Long> { + Optional<User> findOneByActivationKey(String activationKey); - Optional<User> findOneByActivationKey(String activationKey); - - List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime); + List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime); - Optional<User> findOneByResetKey(String resetKey); + Optional<User> findOneByResetKey(String resetKey); - Optional<User> findOneByEmailIgnoreCase(String email); + Optional<User> findOneByEmailIgnoreCase(String email); - Optional<User> findOneByLogin(String login); + Optional<User> findOneByLogin(String login); - @EntityGraph(attributePaths = "authorities") - Optional<User> findOneWithAuthoritiesByLogin(String login); + @EntityGraph(attributePaths = "authorities") + Optional<User> findOneWithAuthoritiesByLogin(String login); - @EntityGraph(attributePaths = "authorities") - Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email); + @EntityGraph(attributePaths = "authorities") + Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email); - Page<User> findAllByLoginNot(Pageable pageable, String login); + Page<User> findAllByLoginNot(Pageable pageable, String login); } diff --git a/src/main/java/com/ippon/pouet/security/AuthoritiesConstants.java b/src/main/java/com/ippon/pouet/security/AuthoritiesConstants.java index 9e08f0f4e1e4f4bbb9b4bfff6c2607c38a71e9e7..673b82858f233d09a266d10a84d1d2df65ad0de7 100644 --- a/src/main/java/com/ippon/pouet/security/AuthoritiesConstants.java +++ b/src/main/java/com/ippon/pouet/security/AuthoritiesConstants.java @@ -7,13 +7,11 @@ import com.ippon.pouet.common.domain.Generated; */ @Generated public final class AuthoritiesConstants { + public static final String ADMIN = "ROLE_ADMIN"; - public static final String ADMIN = "ROLE_ADMIN"; + public static final String USER = "ROLE_USER"; - public static final String USER = "ROLE_USER"; + public static final String ANONYMOUS = "ROLE_ANONYMOUS"; - public static final String ANONYMOUS = "ROLE_ANONYMOUS"; - - private AuthoritiesConstants() { - } + private AuthoritiesConstants() {} } diff --git a/src/main/java/com/ippon/pouet/security/DomainUserDetailsService.java b/src/main/java/com/ippon/pouet/security/DomainUserDetailsService.java index a254894477c7215bc107d37c9aa2195f7367c197..fc9a79e46344745d485d8bb512d12b2d5488ef94 100644 --- a/src/main/java/com/ippon/pouet/security/DomainUserDetailsService.java +++ b/src/main/java/com/ippon/pouet/security/DomainUserDetailsService.java @@ -3,6 +3,8 @@ package com.ippon.pouet.security; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.domain.User; import com.ippon.pouet.repository.UserRepository; +import java.util.*; +import java.util.stream.Collectors; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,51 +16,48 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -import java.util.*; -import java.util.stream.Collectors; - /** * Authenticate a user from the database. */ @Generated @Component("userDetailsService") public class DomainUserDetailsService implements UserDetailsService { + private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); - private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); + private final UserRepository userRepository; - private final UserRepository userRepository; + public DomainUserDetailsService(UserRepository userRepository) { + this.userRepository = userRepository; + } - public DomainUserDetailsService(UserRepository userRepository) { - this.userRepository = userRepository; - } - - @Override - @Transactional - public UserDetails loadUserByUsername(final String login) { - log.debug("Authenticating {}", login); - - if (new EmailValidator().isValid(login, null)) { - return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login) - .map(user -> createSpringSecurityUser(login, user)) - .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); - } - - String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); - return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) - .map(user -> createSpringSecurityUser(lowercaseLogin, user)) - .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); + @Override + @Transactional + public UserDetails loadUserByUsername(final String login) { + log.debug("Authenticating {}", login); + if (new EmailValidator().isValid(login, null)) { + return userRepository + .findOneWithAuthoritiesByEmailIgnoreCase(login) + .map(user -> createSpringSecurityUser(login, user)) + .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } - private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { - if (!user.getActivated()) { - throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); - } - List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() - .map(authority -> new SimpleGrantedAuthority(authority.getName())) - .collect(Collectors.toList()); - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - grantedAuthorities); + String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); + return userRepository + .findOneWithAuthoritiesByLogin(lowercaseLogin) + .map(user -> createSpringSecurityUser(lowercaseLogin, user)) + .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); + } + + private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { + if (!user.getActivated()) { + throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } + List<GrantedAuthority> grantedAuthorities = user + .getAuthorities() + .stream() + .map(authority -> new SimpleGrantedAuthority(authority.getName())) + .collect(Collectors.toList()); + return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); + } } diff --git a/src/main/java/com/ippon/pouet/security/SecurityUtils.java b/src/main/java/com/ippon/pouet/security/SecurityUtils.java index db5a533de1909f32ee2314784d1c020f7d230169..4c0f804bf943fecb45e35bb4cae701d95ee41cf9 100644 --- a/src/main/java/com/ippon/pouet/security/SecurityUtils.java +++ b/src/main/java/com/ippon/pouet/security/SecurityUtils.java @@ -1,88 +1,81 @@ package com.ippon.pouet.security; +import com.ippon.pouet.common.domain.Generated; +import java.util.Optional; +import java.util.stream.Stream; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; -import com.ippon.pouet.common.domain.Generated; - -import java.util.Optional; -import java.util.stream.Stream; - /** * Utility class for Spring Security. */ @Generated public final class SecurityUtils { - private SecurityUtils() { - } - - /** - * Get the login of the current user. - * - * @return the login of the current user. - */ - public static Optional<String> getCurrentUserLogin() { - SecurityContext securityContext = SecurityContextHolder.getContext(); - return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); - } - - private static String extractPrincipal(Authentication authentication) { - if (authentication == null) { - return null; - } else if (authentication.getPrincipal() instanceof UserDetails) { - UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); - return springSecurityUser.getUsername(); - } else if (authentication.getPrincipal() instanceof String) { - return (String) authentication.getPrincipal(); - } - return null; - } + private SecurityUtils() {} + /** + * Get the login of the current user. + * + * @return the login of the current user. + */ + public static Optional<String> getCurrentUserLogin() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); + } - /** - * Get the JWT of the current user. - * - * @return the JWT of the current user. - */ - public static Optional<String> getCurrentUserJWT() { - SecurityContext securityContext = SecurityContextHolder.getContext(); - return Optional.ofNullable(securityContext.getAuthentication()) - .filter(authentication -> authentication.getCredentials() instanceof String) - .map(authentication -> (String) authentication.getCredentials()); + private static String extractPrincipal(Authentication authentication) { + if (authentication == null) { + return null; + } else if (authentication.getPrincipal() instanceof UserDetails) { + UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); + return springSecurityUser.getUsername(); + } else if (authentication.getPrincipal() instanceof String) { + return (String) authentication.getPrincipal(); } + return null; + } - /** - * Check if a user is authenticated. - * - * @return true if the user is authenticated, false otherwise. - */ - public static boolean isAuthenticated() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && - getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); - } + /** + * Get the JWT of the current user. + * + * @return the JWT of the current user. + */ + public static Optional<String> getCurrentUserJWT() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional + .ofNullable(securityContext.getAuthentication()) + .filter(authentication -> authentication.getCredentials() instanceof String) + .map(authentication -> (String) authentication.getCredentials()); + } - /** - * If the current user has a specific authority (security role). - * <p> - * The name of this method comes from the {@code isUserInRole()} method in the Servlet API. - * - * @param authority the authority to check. - * @return true if the current user has the authority, false otherwise. - */ - public static boolean isCurrentUserInRole(String authority) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && - getAuthorities(authentication).anyMatch(authority::equals); - } + /** + * Check if a user is authenticated. + * + * @return true if the user is authenticated, false otherwise. + */ + public static boolean isAuthenticated() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); + } - private static Stream<String> getAuthorities(Authentication authentication) { - return authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority); - } + /** + * If the current user has a specific authority (security role). + * <p> + * The name of this method comes from the {@code isUserInRole()} method in the Servlet API. + * + * @param authority the authority to check. + * @return true if the current user has the authority, false otherwise. + */ + public static boolean isCurrentUserInRole(String authority) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && getAuthorities(authentication).anyMatch(authority::equals); + } + private static Stream<String> getAuthorities(Authentication authentication) { + return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority); + } } diff --git a/src/main/java/com/ippon/pouet/security/SpringSecurityAuditorAware.java b/src/main/java/com/ippon/pouet/security/SpringSecurityAuditorAware.java index 658ae973c374a7abd0e837dde6f31fc79fe97530..251394d99761f03ea90f966daca7a08141019597 100644 --- a/src/main/java/com/ippon/pouet/security/SpringSecurityAuditorAware.java +++ b/src/main/java/com/ippon/pouet/security/SpringSecurityAuditorAware.java @@ -2,9 +2,7 @@ package com.ippon.pouet.security; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.Constants; - import java.util.Optional; - import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; @@ -15,8 +13,8 @@ import org.springframework.stereotype.Component; @Generated public class SpringSecurityAuditorAware implements AuditorAware<String> { - @Override - public Optional<String> getCurrentAuditor() { - return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT)); - } + @Override + public Optional<String> getCurrentAuditor() { + return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT)); + } } diff --git a/src/main/java/com/ippon/pouet/security/UserNotActivatedException.java b/src/main/java/com/ippon/pouet/security/UserNotActivatedException.java index a240abf87cedfa8920d60e5c5b2749bc80b4d6f4..5adb8a2fdf8c6c143467ef84847c062c0b1f3344 100644 --- a/src/main/java/com/ippon/pouet/security/UserNotActivatedException.java +++ b/src/main/java/com/ippon/pouet/security/UserNotActivatedException.java @@ -1,22 +1,20 @@ package com.ippon.pouet.security; -import org.springframework.security.core.AuthenticationException; - import com.ippon.pouet.common.domain.Generated; +import org.springframework.security.core.AuthenticationException; /** * This exception is thrown in case of a not activated user trying to authenticate. */ @Generated public class UserNotActivatedException extends AuthenticationException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public UserNotActivatedException(String message) { - super(message); - } + public UserNotActivatedException(String message) { + super(message); + } - public UserNotActivatedException(String message, Throwable t) { - super(message, t); - } + public UserNotActivatedException(String message, Throwable t) { + super(message, t); + } } diff --git a/src/main/java/com/ippon/pouet/security/jwt/JWTConfigurer.java b/src/main/java/com/ippon/pouet/security/jwt/JWTConfigurer.java index 6da0303b14c0774d9c350d53f77cf697ec45ef53..b72947ed0cf7aa17da9cc49bb369df48fef3037e 100644 --- a/src/main/java/com/ippon/pouet/security/jwt/JWTConfigurer.java +++ b/src/main/java/com/ippon/pouet/security/jwt/JWTConfigurer.java @@ -1,24 +1,22 @@ package com.ippon.pouet.security.jwt; +import com.ippon.pouet.common.domain.Generated; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import com.ippon.pouet.common.domain.Generated; - @Generated public class JWTConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { + private final TokenProvider tokenProvider; - private final TokenProvider tokenProvider; - - public JWTConfigurer(TokenProvider tokenProvider) { - this.tokenProvider = tokenProvider; - } + public JWTConfigurer(TokenProvider tokenProvider) { + this.tokenProvider = tokenProvider; + } - @Override - public void configure(HttpSecurity http) { - JWTFilter customFilter = new JWTFilter(tokenProvider); - http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); - } + @Override + public void configure(HttpSecurity http) { + JWTFilter customFilter = new JWTFilter(tokenProvider); + http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); + } } diff --git a/src/main/java/com/ippon/pouet/security/jwt/JWTFilter.java b/src/main/java/com/ippon/pouet/security/jwt/JWTFilter.java index 394a7f379b18a46b7aa106afd387920932f64b16..83adfd1c2838491d494174b1969e1d5b3aa9f3d8 100644 --- a/src/main/java/com/ippon/pouet/security/jwt/JWTFilter.java +++ b/src/main/java/com/ippon/pouet/security/jwt/JWTFilter.java @@ -1,18 +1,16 @@ package com.ippon.pouet.security.jwt; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.GenericFilterBean; - import com.ippon.pouet.common.domain.Generated; - +import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.GenericFilterBean; /** * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is @@ -20,32 +18,31 @@ import java.io.IOException; */ @Generated public class JWTFilter extends GenericFilterBean { - - public static final String AUTHORIZATION_HEADER = "Authorization"; - - private final TokenProvider tokenProvider; - - public JWTFilter(TokenProvider tokenProvider) { - this.tokenProvider = tokenProvider; - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; - String jwt = resolveToken(httpServletRequest); - if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) { - Authentication authentication = this.tokenProvider.getAuthentication(jwt); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - filterChain.doFilter(servletRequest, servletResponse); + public static final String AUTHORIZATION_HEADER = "Authorization"; + + private final TokenProvider tokenProvider; + + public JWTFilter(TokenProvider tokenProvider) { + this.tokenProvider = tokenProvider; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + String jwt = resolveToken(httpServletRequest); + if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) { + Authentication authentication = this.tokenProvider.getAuthentication(jwt); + SecurityContextHolder.getContext().setAuthentication(authentication); } + filterChain.doFilter(servletRequest, servletResponse); + } - private String resolveToken(HttpServletRequest request) { - String bearerToken = request.getHeader(AUTHORIZATION_HEADER); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { - return bearerToken.substring(7); - } - return null; + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader(AUTHORIZATION_HEADER); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); } + return null; + } } diff --git a/src/main/java/com/ippon/pouet/security/jwt/TokenProvider.java b/src/main/java/com/ippon/pouet/security/jwt/TokenProvider.java index c2ee37eff607b7a7d68d67ee314fd82d6909808e..6d9255f3987e3a73d18eca09ff9b652bd0d44da4 100644 --- a/src/main/java/com/ippon/pouet/security/jwt/TokenProvider.java +++ b/src/main/java/com/ippon/pouet/security/jwt/TokenProvider.java @@ -1,11 +1,15 @@ package com.ippon.pouet.security.jwt; +import com.ippon.pouet.common.domain.Generated; +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; import java.nio.charset.StandardCharsets; import java.security.Key; import java.util.*; import java.util.stream.Collectors; import javax.annotation.PostConstruct; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -16,99 +20,86 @@ import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import com.ippon.pouet.common.domain.Generated; - -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.*; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - @Component @Generated public class TokenProvider { + private final Logger log = LoggerFactory.getLogger(TokenProvider.class); - private final Logger log = LoggerFactory.getLogger(TokenProvider.class); - - private static final String AUTHORITIES_KEY = "auth"; + private static final String AUTHORITIES_KEY = "auth"; - private Key key; + private Key key; - private long tokenValidityInMilliseconds; + private long tokenValidityInMilliseconds; - private long tokenValidityInMillisecondsForRememberMe; + private long tokenValidityInMillisecondsForRememberMe; - private final JHipsterProperties jHipsterProperties; - - public TokenProvider(JHipsterProperties jHipsterProperties) { - this.jHipsterProperties = jHipsterProperties; - } + private final JHipsterProperties jHipsterProperties; - @PostConstruct - public void init() { - byte[] keyBytes; - String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret(); - if (!StringUtils.isEmpty(secret)) { - log.warn("Warning: the JWT key used is not Base64-encoded. " + - "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."); - keyBytes = secret.getBytes(StandardCharsets.UTF_8); - } else { - log.debug("Using a Base64-encoded JWT secret key"); - keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret()); - } - this.key = Keys.hmacShaKeyFor(keyBytes); - this.tokenValidityInMilliseconds = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); - this.tokenValidityInMillisecondsForRememberMe = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt() - .getTokenValidityInSecondsForRememberMe(); - } + public TokenProvider(JHipsterProperties jHipsterProperties) { + this.jHipsterProperties = jHipsterProperties; + } - public String createToken(Authentication authentication, boolean rememberMe) { - String authorities = authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.joining(",")); - - long now = (new Date()).getTime(); - Date validity; - if (rememberMe) { - validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); - } else { - validity = new Date(now + this.tokenValidityInMilliseconds); - } - - return Jwts.builder() - .setSubject(authentication.getName()) - .claim(AUTHORITIES_KEY, authorities) - .signWith(key, SignatureAlgorithm.HS512) - .setExpiration(validity) - .compact(); + @PostConstruct + public void init() { + byte[] keyBytes; + String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret(); + if (!StringUtils.isEmpty(secret)) { + log.warn( + "Warning: the JWT key used is not Base64-encoded. " + + "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security." + ); + keyBytes = secret.getBytes(StandardCharsets.UTF_8); + } else { + log.debug("Using a Base64-encoded JWT secret key"); + keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret()); } - - public Authentication getAuthentication(String token) { - Claims claims = Jwts.parserBuilder() - .setSigningKey(key) - .build() - .parseClaimsJws(token) - .getBody(); - - Collection<? extends GrantedAuthority> authorities = - Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) - .map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()); - - User principal = new User(claims.getSubject(), "", authorities); - - return new UsernamePasswordAuthenticationToken(principal, token, authorities); + this.key = Keys.hmacShaKeyFor(keyBytes); + this.tokenValidityInMilliseconds = 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); + this.tokenValidityInMillisecondsForRememberMe = + 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe(); + } + + public String createToken(Authentication authentication, boolean rememberMe) { + String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")); + + long now = (new Date()).getTime(); + Date validity; + if (rememberMe) { + validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); + } else { + validity = new Date(now + this.tokenValidityInMilliseconds); } - public boolean validateToken(String authToken) { - try { - Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken); - return true; - } catch (JwtException | IllegalArgumentException e) { - log.info("Invalid JWT token."); - log.trace("Invalid JWT token trace.", e); - } - return false; + return Jwts + .builder() + .setSubject(authentication.getName()) + .claim(AUTHORITIES_KEY, authorities) + .signWith(key, SignatureAlgorithm.HS512) + .setExpiration(validity) + .compact(); + } + + public Authentication getAuthentication(String token) { + Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); + + Collection<? extends GrantedAuthority> authorities = Arrays + .stream(claims.get(AUTHORITIES_KEY).toString().split(",")) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + User principal = new User(claims.getSubject(), "", authorities); + + return new UsernamePasswordAuthenticationToken(principal, token, authorities); + } + + public boolean validateToken(String authToken) { + try { + Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken); + return true; + } catch (JwtException | IllegalArgumentException e) { + log.info("Invalid JWT token."); + log.trace("Invalid JWT token trace.", e); } + return false; + } } diff --git a/src/main/java/com/ippon/pouet/service/AuditEventService.java b/src/main/java/com/ippon/pouet/service/AuditEventService.java index 6e0469a59353e58986d7e72e583b8fbb21a53d43..f4ed0264a6052de8b7acb2abf2e113b1d147ae03 100644 --- a/src/main/java/com/ippon/pouet/service/AuditEventService.java +++ b/src/main/java/com/ippon/pouet/service/AuditEventService.java @@ -1,10 +1,12 @@ package com.ippon.pouet.service; -import io.github.jhipster.config.JHipsterProperties; - import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.audit.AuditEventConverter; import com.ippon.pouet.repository.PersistenceAuditEventRepository; +import io.github.jhipster.config.JHipsterProperties; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; @@ -14,10 +16,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Optional; - /** * Service for managing audit events. * <p> @@ -27,54 +25,55 @@ import java.util.Optional; @Generated @Transactional public class AuditEventService { + private final Logger log = LoggerFactory.getLogger(AuditEventService.class); - private final Logger log = LoggerFactory.getLogger(AuditEventService.class); - - private final JHipsterProperties jHipsterProperties; - - private final PersistenceAuditEventRepository persistenceAuditEventRepository; + private final JHipsterProperties jHipsterProperties; - private final AuditEventConverter auditEventConverter; + private final PersistenceAuditEventRepository persistenceAuditEventRepository; - public AuditEventService( - PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) { + private final AuditEventConverter auditEventConverter; - this.persistenceAuditEventRepository = persistenceAuditEventRepository; - this.auditEventConverter = auditEventConverter; - this.jHipsterProperties = jhipsterProperties; - } + public AuditEventService( + PersistenceAuditEventRepository persistenceAuditEventRepository, + AuditEventConverter auditEventConverter, + JHipsterProperties jhipsterProperties + ) { + this.persistenceAuditEventRepository = persistenceAuditEventRepository; + this.auditEventConverter = auditEventConverter; + this.jHipsterProperties = jhipsterProperties; + } - /** - * Old audit events should be automatically deleted after 30 days. - * - * This is scheduled to get fired at 12:00 (am). - */ - @Scheduled(cron = "0 0 12 * * ?") - public void removeOldAuditEvents() { - persistenceAuditEventRepository - .findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS)) - .forEach(auditEvent -> { - log.debug("Deleting audit data {}", auditEvent); - persistenceAuditEventRepository.delete(auditEvent); - }); - } + /** + * Old audit events should be automatically deleted after 30 days. + * + * This is scheduled to get fired at 12:00 (am). + */ + @Scheduled(cron = "0 0 12 * * ?") + public void removeOldAuditEvents() { + persistenceAuditEventRepository + .findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS)) + .forEach( + auditEvent -> { + log.debug("Deleting audit data {}", auditEvent); + persistenceAuditEventRepository.delete(auditEvent); + } + ); + } - @Transactional(readOnly = true) - public Page<AuditEvent> findAll(Pageable pageable) { - return persistenceAuditEventRepository.findAll(pageable) - .map(auditEventConverter::convertToAuditEvent); - } + @Transactional(readOnly = true) + public Page<AuditEvent> findAll(Pageable pageable) { + return persistenceAuditEventRepository.findAll(pageable).map(auditEventConverter::convertToAuditEvent); + } - @Transactional(readOnly = true) - public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { - return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) - .map(auditEventConverter::convertToAuditEvent); - } + @Transactional(readOnly = true) + public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { + return persistenceAuditEventRepository + .findAllByAuditEventDateBetween(fromDate, toDate, pageable) + .map(auditEventConverter::convertToAuditEvent); + } - @Transactional(readOnly = true) - public Optional<AuditEvent> find(Long id) { - return persistenceAuditEventRepository.findById(id) - .map(auditEventConverter::convertToAuditEvent); - } + @Transactional(readOnly = true) + public Optional<AuditEvent> find(Long id) { + return persistenceAuditEventRepository.findById(id).map(auditEventConverter::convertToAuditEvent); + } } diff --git a/src/main/java/com/ippon/pouet/service/EmailAlreadyUsedException.java b/src/main/java/com/ippon/pouet/service/EmailAlreadyUsedException.java index abd46c5fe26c96aa76ae23e9ddb38a47f11927b7..f4559ff53ce8e04e0d80d26396618c8ce205863e 100644 --- a/src/main/java/com/ippon/pouet/service/EmailAlreadyUsedException.java +++ b/src/main/java/com/ippon/pouet/service/EmailAlreadyUsedException.java @@ -4,11 +4,9 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class EmailAlreadyUsedException extends RuntimeException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public EmailAlreadyUsedException() { - super("Email is already in use!"); - } - + public EmailAlreadyUsedException() { + super("Email is already in use!"); + } } diff --git a/src/main/java/com/ippon/pouet/service/InvalidPasswordException.java b/src/main/java/com/ippon/pouet/service/InvalidPasswordException.java index 5d313358f278ef5e26bb3e10295005e24494cffa..4871e691a5cc3077b24ee97124ea4c85369e51fd 100644 --- a/src/main/java/com/ippon/pouet/service/InvalidPasswordException.java +++ b/src/main/java/com/ippon/pouet/service/InvalidPasswordException.java @@ -4,11 +4,9 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class InvalidPasswordException extends RuntimeException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public InvalidPasswordException() { - super("Incorrect password"); - } - + public InvalidPasswordException() { + super("Incorrect password"); + } } diff --git a/src/main/java/com/ippon/pouet/service/MailService.java b/src/main/java/com/ippon/pouet/service/MailService.java index 0594d1a666914d205413e2c1ddee1619de78c391..efa6fa3c2b956a3fe908c4778221aa0701450188 100644 --- a/src/main/java/com/ippon/pouet/service/MailService.java +++ b/src/main/java/com/ippon/pouet/service/MailService.java @@ -2,14 +2,11 @@ package com.ippon.pouet.service; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.domain.User; - import io.github.jhipster.config.JHipsterProperties; - import java.nio.charset.StandardCharsets; import java.util.Locale; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; @@ -29,80 +26,88 @@ import org.thymeleaf.spring5.SpringTemplateEngine; @Service @Generated public class MailService { - - private final Logger log = LoggerFactory.getLogger(MailService.class); - - private static final String USER = "user"; - - private static final String BASE_URL = "baseUrl"; - - private final JHipsterProperties jHipsterProperties; - - private final JavaMailSender javaMailSender; - - private final MessageSource messageSource; - - private final SpringTemplateEngine templateEngine; - - public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, - MessageSource messageSource, SpringTemplateEngine templateEngine) { - - this.jHipsterProperties = jHipsterProperties; - this.javaMailSender = javaMailSender; - this.messageSource = messageSource; - this.templateEngine = templateEngine; - } - - @Async - public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { - log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", - isMultipart, isHtml, to, subject, content); - - // Prepare message using a Spring helper - MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - try { - MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); - message.setTo(to); - message.setFrom(jHipsterProperties.getMail().getFrom()); - message.setSubject(subject); - message.setText(content, isHtml); - javaMailSender.send(mimeMessage); - log.debug("Sent email to User '{}'", to); - } catch (MailException | MessagingException e) { - log.warn("Email could not be sent to user '{}'", to, e); - } - } - - @Async - public void sendEmailFromTemplate(User user, String templateName, String titleKey) { - if (user.getEmail() == null) { - log.debug("Email doesn't exist for user '{}'", user.getLogin()); - return; - } - Locale locale = Locale.forLanguageTag(user.getLangKey()); - Context context = new Context(locale); - context.setVariable(USER, user); - context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); - String content = templateEngine.process(templateName, context); - String subject = messageSource.getMessage(titleKey, null, locale); - sendEmail(user.getEmail(), subject, content, false, true); - } - - @Async - public void sendActivationEmail(User user) { - log.debug("Sending activation email to '{}'", user.getEmail()); - sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title"); - } - - @Async - public void sendCreationEmail(User user) { - log.debug("Sending creation email to '{}'", user.getEmail()); - sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title"); + private final Logger log = LoggerFactory.getLogger(MailService.class); + + private static final String USER = "user"; + + private static final String BASE_URL = "baseUrl"; + + private final JHipsterProperties jHipsterProperties; + + private final JavaMailSender javaMailSender; + + private final MessageSource messageSource; + + private final SpringTemplateEngine templateEngine; + + public MailService( + JHipsterProperties jHipsterProperties, + JavaMailSender javaMailSender, + MessageSource messageSource, + SpringTemplateEngine templateEngine + ) { + this.jHipsterProperties = jHipsterProperties; + this.javaMailSender = javaMailSender; + this.messageSource = messageSource; + this.templateEngine = templateEngine; + } + + @Async + public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { + log.debug( + "Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", + isMultipart, + isHtml, + to, + subject, + content + ); + + // Prepare message using a Spring helper + MimeMessage mimeMessage = javaMailSender.createMimeMessage(); + try { + MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); + message.setTo(to); + message.setFrom(jHipsterProperties.getMail().getFrom()); + message.setSubject(subject); + message.setText(content, isHtml); + javaMailSender.send(mimeMessage); + log.debug("Sent email to User '{}'", to); + } catch (MailException | MessagingException e) { + log.warn("Email could not be sent to user '{}'", to, e); } + } - @Async - public void sendPasswordResetMail(User user) { - log.debug("Sending password reset email to '{}'", user.getEmail()); - sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title"); + @Async + public void sendEmailFromTemplate(User user, String templateName, String titleKey) { + if (user.getEmail() == null) { + log.debug("Email doesn't exist for user '{}'", user.getLogin()); + return; } + Locale locale = Locale.forLanguageTag(user.getLangKey()); + Context context = new Context(locale); + context.setVariable(USER, user); + context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); + String content = templateEngine.process(templateName, context); + String subject = messageSource.getMessage(titleKey, null, locale); + sendEmail(user.getEmail(), subject, content, false, true); + } + + @Async + public void sendActivationEmail(User user) { + log.debug("Sending activation email to '{}'", user.getEmail()); + sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title"); + } + + @Async + public void sendCreationEmail(User user) { + log.debug("Sending creation email to '{}'", user.getEmail()); + sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title"); + } + + @Async + public void sendPasswordResetMail(User user) { + log.debug("Sending password reset email to '{}'", user.getEmail()); + sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title"); + } } diff --git a/src/main/java/com/ippon/pouet/service/UserService.java b/src/main/java/com/ippon/pouet/service/UserService.java index b5f611cb2c4e6efe0e9689358194665d3812202e..5fcb7596cdc530462789c66fb8b2f9f3f0d28905 100644 --- a/src/main/java/com/ippon/pouet/service/UserService.java +++ b/src/main/java/com/ippon/pouet/service/UserService.java @@ -9,9 +9,11 @@ import com.ippon.pouet.repository.UserRepository; import com.ippon.pouet.security.AuthoritiesConstants; import com.ippon.pouet.security.SecurityUtils; import com.ippon.pouet.service.dto.UserDTO; - import io.github.jhipster.security.RandomUtil; - +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -21,11 +23,6 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.stream.Collectors; - /** * Service class for managing users. */ @@ -33,251 +30,283 @@ import java.util.stream.Collectors; @Generated @Transactional public class UserService { + private final Logger log = LoggerFactory.getLogger(UserService.class); - private final Logger log = LoggerFactory.getLogger(UserService.class); + private final UserRepository userRepository; - private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; - private final PasswordEncoder passwordEncoder; + private final AuthorityRepository authorityRepository; - private final AuthorityRepository authorityRepository; + public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.authorityRepository = authorityRepository; + } - public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - this.authorityRepository = authorityRepository; - } - - public Optional<User> activateRegistration(String key) { - log.debug("Activating user for activation key {}", key); - return userRepository.findOneByActivationKey(key) - .map(user -> { - // activate given user for the registration key. - user.setActivated(true); - user.setActivationKey(null); - log.debug("Activated user: {}", user); - return user; - }); - } - - public Optional<User> completePasswordReset(String newPassword, String key) { - log.debug("Reset user password for reset key {}", key); - return userRepository.findOneByResetKey(key) - .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))) - .map(user -> { - user.setPassword(passwordEncoder.encode(newPassword)); - user.setResetKey(null); - user.setResetDate(null); - return user; - }); - } - - public Optional<User> requestPasswordReset(String mail) { - return userRepository.findOneByEmailIgnoreCase(mail) - .filter(User::getActivated) - .map(user -> { - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - return user; - }); - } - - public User registerUser(UserDTO userDTO, String password) { - userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> { - boolean removed = removeNonActivatedUser(existingUser); - if (!removed) { - throw new UsernameAlreadyUsedException(); - } - }); - userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> { - boolean removed = removeNonActivatedUser(existingUser); - if (!removed) { - throw new EmailAlreadyUsedException(); - } - }); - User newUser = new User(); - String encryptedPassword = passwordEncoder.encode(password); - newUser.setLogin(userDTO.getLogin().toLowerCase()); - // new user gets initially a generated password - newUser.setPassword(encryptedPassword); - newUser.setFirstName(userDTO.getFirstName()); - newUser.setLastName(userDTO.getLastName()); - if (userDTO.getEmail() != null) { - newUser.setEmail(userDTO.getEmail().toLowerCase()); + public Optional<User> activateRegistration(String key) { + log.debug("Activating user for activation key {}", key); + return userRepository + .findOneByActivationKey(key) + .map( + user -> { + // activate given user for the registration key. + user.setActivated(true); + user.setActivationKey(null); + log.debug("Activated user: {}", user); + return user; } - newUser.setImageUrl(userDTO.getImageUrl()); - newUser.setLangKey(userDTO.getLangKey()); - // new user is not active - newUser.setActivated(false); - // new user gets registration key - newUser.setActivationKey(RandomUtil.generateActivationKey()); - Set<Authority> authorities = new HashSet<>(); - authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); - newUser.setAuthorities(authorities); - userRepository.save(newUser); - log.debug("Created Information for User: {}", newUser); - return newUser; - } + ); + } - private boolean removeNonActivatedUser(User existingUser) { - if (existingUser.getActivated()) { - return false; + public Optional<User> completePasswordReset(String newPassword, String key) { + log.debug("Reset user password for reset key {}", key); + return userRepository + .findOneByResetKey(key) + .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))) + .map( + user -> { + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + return user; } - userRepository.delete(existingUser); - userRepository.flush(); - return true; - } + ); + } - public User createUser(UserDTO userDTO) { - User user = new User(); - user.setLogin(userDTO.getLogin().toLowerCase()); - user.setFirstName(userDTO.getFirstName()); - user.setLastName(userDTO.getLastName()); - if (userDTO.getEmail() != null) { - user.setEmail(userDTO.getEmail().toLowerCase()); + public Optional<User> requestPasswordReset(String mail) { + return userRepository + .findOneByEmailIgnoreCase(mail) + .filter(User::getActivated) + .map( + user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + return user; } - user.setImageUrl(userDTO.getImageUrl()); - if (userDTO.getLangKey() == null) { - user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language - } else { - user.setLangKey(userDTO.getLangKey()); + ); + } + + public User registerUser(UserDTO userDTO, String password) { + userRepository + .findOneByLogin(userDTO.getLogin().toLowerCase()) + .ifPresent( + existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new UsernameAlreadyUsedException(); + } } - String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); - user.setPassword(encryptedPassword); - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - user.setActivated(true); - if (userDTO.getAuthorities() != null) { - Set<Authority> authorities = userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toSet()); - user.setAuthorities(authorities); + ); + userRepository + .findOneByEmailIgnoreCase(userDTO.getEmail()) + .ifPresent( + existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new EmailAlreadyUsedException(); + } } - userRepository.save(user); - log.debug("Created Information for User: {}", user); - return user; + ); + User newUser = new User(); + String encryptedPassword = passwordEncoder.encode(password); + newUser.setLogin(userDTO.getLogin().toLowerCase()); + // new user gets initially a generated password + newUser.setPassword(encryptedPassword); + newUser.setFirstName(userDTO.getFirstName()); + newUser.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + newUser.setEmail(userDTO.getEmail().toLowerCase()); } + newUser.setImageUrl(userDTO.getImageUrl()); + newUser.setLangKey(userDTO.getLangKey()); + // new user is not active + newUser.setActivated(false); + // new user gets registration key + newUser.setActivationKey(RandomUtil.generateActivationKey()); + Set<Authority> authorities = new HashSet<>(); + authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); + newUser.setAuthorities(authorities); + userRepository.save(newUser); + log.debug("Created Information for User: {}", newUser); + return newUser; + } - /** - * Update all information for a specific user, and return the modified user. - * - * @param userDTO user to update. - * @return updated user. - */ - public Optional<UserDTO> updateUser(UserDTO userDTO) { - return Optional.of(userRepository - .findById(userDTO.getId())) - .filter(Optional::isPresent) - .map(Optional::get) - .map(user -> { - user.setLogin(userDTO.getLogin().toLowerCase()); - user.setFirstName(userDTO.getFirstName()); - user.setLastName(userDTO.getLastName()); - if (userDTO.getEmail() != null) { - user.setEmail(userDTO.getEmail().toLowerCase()); - } - user.setImageUrl(userDTO.getImageUrl()); - user.setActivated(userDTO.isActivated()); - user.setLangKey(userDTO.getLangKey()); - Set<Authority> managedAuthorities = user.getAuthorities(); - managedAuthorities.clear(); - userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .forEach(managedAuthorities::add); - log.debug("Changed Information for User: {}", user); - return user; - }) - .map(UserDTO::new); + private boolean removeNonActivatedUser(User existingUser) { + if (existingUser.getActivated()) { + return false; } + userRepository.delete(existingUser); + userRepository.flush(); + return true; + } - public void deleteUser(String login) { - userRepository.findOneByLogin(login).ifPresent(user -> { - userRepository.delete(user); - log.debug("Deleted User: {}", user); - }); + public User createUser(UserDTO userDTO) { + User user = new User(); + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + user.setEmail(userDTO.getEmail().toLowerCase()); } - - /** - * Update basic information (first name, last name, email, language) for the current user. - * - * @param firstName first name of user. - * @param lastName last name of user. - * @param email email id of user. - * @param langKey language key. - * @param imageUrl image URL of user. - */ - public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { - SecurityUtils.getCurrentUserLogin() - .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - user.setFirstName(firstName); - user.setLastName(lastName); - if (email != null) { - user.setEmail(email.toLowerCase()); - } - user.setLangKey(langKey); - user.setImageUrl(imageUrl); - log.debug("Changed Information for User: {}", user); - }); + user.setImageUrl(userDTO.getImageUrl()); + if (userDTO.getLangKey() == null) { + user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language + } else { + user.setLangKey(userDTO.getLangKey()); + } + String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); + user.setPassword(encryptedPassword); + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + user.setActivated(true); + if (userDTO.getAuthorities() != null) { + Set<Authority> authorities = userDTO + .getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + user.setAuthorities(authorities); } + userRepository.save(user); + log.debug("Created Information for User: {}", user); + return user; + } + /** + * Update all information for a specific user, and return the modified user. + * + * @param userDTO user to update. + * @return updated user. + */ + public Optional<UserDTO> updateUser(UserDTO userDTO) { + return Optional + .of(userRepository.findById(userDTO.getId())) + .filter(Optional::isPresent) + .map(Optional::get) + .map( + user -> { + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + user.setEmail(userDTO.getEmail().toLowerCase()); + } + user.setImageUrl(userDTO.getImageUrl()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set<Authority> managedAuthorities = user.getAuthorities(); + managedAuthorities.clear(); + userDTO + .getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(managedAuthorities::add); + log.debug("Changed Information for User: {}", user); + return user; + } + ) + .map(UserDTO::new); + } - @Transactional - public void changePassword(String currentClearTextPassword, String newPassword) { - SecurityUtils.getCurrentUserLogin() - .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - String currentEncryptedPassword = user.getPassword(); - if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { - throw new InvalidPasswordException(); - } - String encryptedPassword = passwordEncoder.encode(newPassword); - user.setPassword(encryptedPassword); - log.debug("Changed password for User: {}", user); - }); - } + public void deleteUser(String login) { + userRepository + .findOneByLogin(login) + .ifPresent( + user -> { + userRepository.delete(user); + log.debug("Deleted User: {}", user); + } + ); + } - @Transactional(readOnly = true) - public Page<UserDTO> getAllManagedUsers(Pageable pageable) { - return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); - } + /** + * Update basic information (first name, last name, email, language) for the current user. + * + * @param firstName first name of user. + * @param lastName last name of user. + * @param email email id of user. + * @param langKey language key. + * @param imageUrl image URL of user. + */ + public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { + SecurityUtils + .getCurrentUserLogin() + .flatMap(userRepository::findOneByLogin) + .ifPresent( + user -> { + user.setFirstName(firstName); + user.setLastName(lastName); + if (email != null) { + user.setEmail(email.toLowerCase()); + } + user.setLangKey(langKey); + user.setImageUrl(imageUrl); + log.debug("Changed Information for User: {}", user); + } + ); + } - @Transactional(readOnly = true) - public Optional<User> getUserWithAuthoritiesByLogin(String login) { - return userRepository.findOneWithAuthoritiesByLogin(login); - } + @Transactional + public void changePassword(String currentClearTextPassword, String newPassword) { + SecurityUtils + .getCurrentUserLogin() + .flatMap(userRepository::findOneByLogin) + .ifPresent( + user -> { + String currentEncryptedPassword = user.getPassword(); + if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { + throw new InvalidPasswordException(); + } + String encryptedPassword = passwordEncoder.encode(newPassword); + user.setPassword(encryptedPassword); + log.debug("Changed password for User: {}", user); + } + ); + } - @Transactional(readOnly = true) - public Optional<User> getUserWithAuthorities() { - return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); - } + @Transactional(readOnly = true) + public Page<UserDTO> getAllManagedUsers(Pageable pageable) { + return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); + } - /** - * Not activated users should be automatically deleted after 3 days. - * <p> - * This is scheduled to get fired everyday, at 01:00 (am). - */ - @Scheduled(cron = "0 0 1 * * ?") - public void removeNotActivatedUsers() { - userRepository - .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) - .forEach(user -> { - log.debug("Deleting not activated user {}", user.getLogin()); - userRepository.delete(user); - }); - } + @Transactional(readOnly = true) + public Optional<User> getUserWithAuthoritiesByLogin(String login) { + return userRepository.findOneWithAuthoritiesByLogin(login); + } - /** - * Gets a list of all the authorities. - * @return a list of all the authorities. - */ - @Transactional(readOnly = true) - public List<String> getAuthorities() { - return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList()); - } + @Transactional(readOnly = true) + public Optional<User> getUserWithAuthorities() { + return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); + } + + /** + * Not activated users should be automatically deleted after 3 days. + * <p> + * This is scheduled to get fired everyday, at 01:00 (am). + */ + @Scheduled(cron = "0 0 1 * * ?") + public void removeNotActivatedUsers() { + userRepository + .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) + .forEach( + user -> { + log.debug("Deleting not activated user {}", user.getLogin()); + userRepository.delete(user); + } + ); + } + /** + * Gets a list of all the authorities. + * @return a list of all the authorities. + */ + @Transactional(readOnly = true) + public List<String> getAuthorities() { + return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList()); + } } diff --git a/src/main/java/com/ippon/pouet/service/UsernameAlreadyUsedException.java b/src/main/java/com/ippon/pouet/service/UsernameAlreadyUsedException.java index 4829408157a0d02ab2921ade244e211c55756120..ea8f6db74582fb32d068804f8008f095e8d02058 100644 --- a/src/main/java/com/ippon/pouet/service/UsernameAlreadyUsedException.java +++ b/src/main/java/com/ippon/pouet/service/UsernameAlreadyUsedException.java @@ -4,11 +4,9 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class UsernameAlreadyUsedException extends RuntimeException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public UsernameAlreadyUsedException() { - super("Login name already used!"); - } - + public UsernameAlreadyUsedException() { + super("Login name already used!"); + } } diff --git a/src/main/java/com/ippon/pouet/service/dto/PasswordChangeDTO.java b/src/main/java/com/ippon/pouet/service/dto/PasswordChangeDTO.java index cfdf65901ceeb2ca38675bd64b7085a7b988a6f8..22fec6010f8872162c4a87be57c9a547b5bcfe95 100644 --- a/src/main/java/com/ippon/pouet/service/dto/PasswordChangeDTO.java +++ b/src/main/java/com/ippon/pouet/service/dto/PasswordChangeDTO.java @@ -7,32 +7,31 @@ import com.ippon.pouet.common.domain.Generated; */ @Generated public class PasswordChangeDTO { - private String currentPassword; - private String newPassword; + private String currentPassword; + private String newPassword; - public PasswordChangeDTO() { - // Empty constructor needed for Jackson. - } + public PasswordChangeDTO() { + // Empty constructor needed for Jackson. + } - public PasswordChangeDTO(String currentPassword, String newPassword) { - this.currentPassword = currentPassword; - this.newPassword = newPassword; - } + public PasswordChangeDTO(String currentPassword, String newPassword) { + this.currentPassword = currentPassword; + this.newPassword = newPassword; + } - public String getCurrentPassword() { + public String getCurrentPassword() { + return currentPassword; + } - return currentPassword; - } + public void setCurrentPassword(String currentPassword) { + this.currentPassword = currentPassword; + } - public void setCurrentPassword(String currentPassword) { - this.currentPassword = currentPassword; - } + public String getNewPassword() { + return newPassword; + } - public String getNewPassword() { - return newPassword; - } - - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } } diff --git a/src/main/java/com/ippon/pouet/service/dto/UserDTO.java b/src/main/java/com/ippon/pouet/service/dto/UserDTO.java index 83abeeaaa24446c1de5f4adb71a2daea3272c168..6e787d861520ac623641e0e36cb71add5f2193c6 100644 --- a/src/main/java/com/ippon/pouet/service/dto/UserDTO.java +++ b/src/main/java/com/ippon/pouet/service/dto/UserDTO.java @@ -2,183 +2,178 @@ package com.ippon.pouet.service.dto; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.config.Constants; - import com.ippon.pouet.domain.Authority; import com.ippon.pouet.domain.User; - -import javax.validation.constraints.*; import java.time.Instant; import java.util.Set; import java.util.stream.Collectors; +import javax.validation.constraints.*; /** * A DTO representing a user, with his authorities. */ @Generated public class UserDTO { + private Long id; - private Long id; - - @NotBlank - @Pattern(regexp = Constants.LOGIN_REGEX) - @Size(min = 1, max = 50) - private String login; + @NotBlank + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + private String login; - @Size(max = 50) - private String firstName; + @Size(max = 50) + private String firstName; - @Size(max = 50) - private String lastName; + @Size(max = 50) + private String lastName; - @Email - @Size(min = 5, max = 254) - private String email; + @Email + @Size(min = 5, max = 254) + private String email; - @Size(max = 256) - private String imageUrl; + @Size(max = 256) + private String imageUrl; - private boolean activated = false; + private boolean activated = false; - @Size(min = 2, max = 10) - private String langKey; + @Size(min = 2, max = 10) + private String langKey; - private String createdBy; + private String createdBy; - private Instant createdDate; + private Instant createdDate; - private String lastModifiedBy; + private String lastModifiedBy; - private Instant lastModifiedDate; + private Instant lastModifiedDate; - private Set<String> authorities; + private Set<String> authorities; - public UserDTO() { - // Empty constructor needed for Jackson. - } + public UserDTO() { + // Empty constructor needed for Jackson. + } - public UserDTO(User user) { - this.id = user.getId(); - this.login = user.getLogin(); - this.firstName = user.getFirstName(); - this.lastName = user.getLastName(); - this.email = user.getEmail(); - this.activated = user.getActivated(); - this.imageUrl = user.getImageUrl(); - this.langKey = user.getLangKey(); - this.createdBy = user.getCreatedBy(); - this.createdDate = user.getCreatedDate(); - this.lastModifiedBy = user.getLastModifiedBy(); - this.lastModifiedDate = user.getLastModifiedDate(); - this.authorities = user.getAuthorities().stream() - .map(Authority::getName) - .collect(Collectors.toSet()); - } + public UserDTO(User user) { + this.id = user.getId(); + this.login = user.getLogin(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.email = user.getEmail(); + this.activated = user.getActivated(); + this.imageUrl = user.getImageUrl(); + this.langKey = user.getLangKey(); + this.createdBy = user.getCreatedBy(); + this.createdDate = user.getCreatedDate(); + this.lastModifiedBy = user.getLastModifiedBy(); + this.lastModifiedDate = user.getLastModifiedDate(); + this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet()); + } - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } + public Long getId() { + return id; + } - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } + public void setId(Long id) { + this.id = id; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getLogin() { + return login; + } - public String getEmail() { - return email; - } + public void setLogin(String login) { + this.login = login; + } - public void setEmail(String email) { - this.email = email; - } + public String getFirstName() { + return firstName; + } - public String getImageUrl() { - return imageUrl; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setImageUrl(String imageUrl) { - this.imageUrl = imageUrl; - } + public String getLastName() { + return lastName; + } - public boolean isActivated() { - return activated; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setActivated(boolean activated) { - this.activated = activated; - } + public String getEmail() { + return email; + } - public String getLangKey() { - return langKey; - } + public void setEmail(String email) { + this.email = email; + } - public void setLangKey(String langKey) { - this.langKey = langKey; - } + public String getImageUrl() { + return imageUrl; + } - public String getCreatedBy() { - return createdBy; - } + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public boolean isActivated() { + return activated; + } - public Instant getCreatedDate() { - return createdDate; - } + public void setActivated(boolean activated) { + this.activated = activated; + } - public void setCreatedDate(Instant createdDate) { - this.createdDate = createdDate; - } + public String getLangKey() { + return langKey; + } - public String getLastModifiedBy() { - return lastModifiedBy; - } + public void setLangKey(String langKey) { + this.langKey = langKey; + } - public void setLastModifiedBy(String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } + public String getCreatedBy() { + return createdBy; + } - public Instant getLastModifiedDate() { - return lastModifiedDate; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public void setLastModifiedDate(Instant lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } + public Instant getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Instant createdDate) { + this.createdDate = createdDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } - public Set<String> getAuthorities() { - return authorities; - } + public Set<String> getAuthorities() { + return authorities; + } - public void setAuthorities(Set<String> authorities) { - this.authorities = authorities; - } + public void setAuthorities(Set<String> authorities) { + this.authorities = authorities; + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "UserDTO{" + diff --git a/src/main/java/com/ippon/pouet/service/mapper/UserMapper.java b/src/main/java/com/ippon/pouet/service/mapper/UserMapper.java index baa0280edc1683f44050af20d380c1a099c47885..337c2aa653c7354e3a4f20a302aee1e3ac1987e9 100644 --- a/src/main/java/com/ippon/pouet/service/mapper/UserMapper.java +++ b/src/main/java/com/ippon/pouet/service/mapper/UserMapper.java @@ -4,11 +4,9 @@ import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.domain.Authority; import com.ippon.pouet.domain.User; import com.ippon.pouet.service.dto.UserDTO; - -import org.springframework.stereotype.Service; - import java.util.*; import java.util.stream.Collectors; +import org.springframework.stereotype.Service; /** * Mapper for the entity {@link User} and its DTO called {@link UserDTO}. @@ -20,64 +18,63 @@ import java.util.stream.Collectors; @Generated public class UserMapper { - public List<UserDTO> usersToUserDTOs(List<User> users) { - return users.stream() - .filter(Objects::nonNull) - .map(this::userToUserDTO) - .collect(Collectors.toList()); - } + public List<UserDTO> usersToUserDTOs(List<User> users) { + return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).collect(Collectors.toList()); + } - public UserDTO userToUserDTO(User user) { - return new UserDTO(user); - } + public UserDTO userToUserDTO(User user) { + return new UserDTO(user); + } - public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { - return userDTOs.stream() - .filter(Objects::nonNull) - .map(this::userDTOToUser) - .collect(Collectors.toList()); - } + public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { + return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).collect(Collectors.toList()); + } - public User userDTOToUser(UserDTO userDTO) { - if (userDTO == null) { - return null; - } else { - User user = new User(); - user.setId(userDTO.getId()); - user.setLogin(userDTO.getLogin()); - user.setFirstName(userDTO.getFirstName()); - user.setLastName(userDTO.getLastName()); - user.setEmail(userDTO.getEmail()); - user.setImageUrl(userDTO.getImageUrl()); - user.setActivated(userDTO.isActivated()); - user.setLangKey(userDTO.getLangKey()); - Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); - user.setAuthorities(authorities); - return user; - } + public User userDTOToUser(UserDTO userDTO) { + if (userDTO == null) { + return null; + } else { + User user = new User(); + user.setId(userDTO.getId()); + user.setLogin(userDTO.getLogin()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + user.setEmail(userDTO.getEmail()); + user.setImageUrl(userDTO.getImageUrl()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); + user.setAuthorities(authorities); + return user; } + } + private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) { + Set<Authority> authorities = new HashSet<>(); - private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) { - Set<Authority> authorities = new HashSet<>(); - - if (authoritiesAsString != null) { - authorities = authoritiesAsString.stream().map(string -> { - Authority auth = new Authority(); - auth.setName(string); - return auth; - }).collect(Collectors.toSet()); - } - - return authorities; + if (authoritiesAsString != null) { + authorities = + authoritiesAsString + .stream() + .map( + string -> { + Authority auth = new Authority(); + auth.setName(string); + return auth; + } + ) + .collect(Collectors.toSet()); } - public User userFromId(Long id) { - if (id == null) { - return null; - } - User user = new User(); - user.setId(id); - return user; + return authorities; + } + + public User userFromId(Long id) { + if (id == null) { + return null; } + User user = new User(); + user.setId(id); + return user; + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/AccountResource.java b/src/main/java/com/ippon/pouet/web/rest/AccountResource.java index 6f9ea73712b4217b7d53f6047061603c50ff575b..ef161deb15c2813bcdeb9987479f3dc033e38359 100644 --- a/src/main/java/com/ippon/pouet/web/rest/AccountResource.java +++ b/src/main/java/com/ippon/pouet/web/rest/AccountResource.java @@ -11,17 +11,15 @@ import com.ippon.pouet.service.dto.UserDTO; import com.ippon.pouet.web.rest.errors.*; import com.ippon.pouet.web.rest.vm.KeyAndPasswordVM; import com.ippon.pouet.web.rest.vm.ManagedUserVM; - +import java.util.*; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.*; - /** * REST controller for managing the current user's account. */ @@ -32,6 +30,7 @@ public class AccountResource { @Generated private static class AccountResourceException extends RuntimeException { + private AccountResourceException(String message) { super(message); } @@ -45,9 +44,7 @@ public class AccountResource { private final MailService mailService; - public AccountResource(UserRepository userRepository, UserService userService, - MailService mailService) { - + public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) { this.userRepository = userRepository; this.userService = userService; this.mailService = mailService; @@ -71,8 +68,7 @@ public class AccountResource { if (!checkPasswordLength(managedUserVM.getPassword())) { throw new InvalidPasswordException(); } - User user = userService.registerUser(managedUserVM, - managedUserVM.getPassword()); + User user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); mailService.sendActivationEmail(user); } @@ -88,8 +84,7 @@ public class AccountResource { public void activateAccount(@RequestParam(value = "key") String key) { Optional<User> user = userService.activateRegistration(key); if (!user.isPresent()) { - throw new AccountResourceException( - "No user was found for this activation key"); + throw new AccountResourceException("No user was found for this activation key"); } } @@ -115,10 +110,10 @@ public class AccountResource { */ @GetMapping("/account") public UserDTO getAccount() { - return userService.getUserWithAuthorities() - .map(UserDTO::new) - .orElseThrow( - () -> new AccountResourceException("User could not be found")); + return userService + .getUserWithAuthorities() + .map(UserDTO::new) + .orElseThrow(() -> new AccountResourceException("User could not be found")); } /** @@ -133,21 +128,16 @@ public class AccountResource { */ @PostMapping("/account") public void saveAccount(@Valid @RequestBody UserDTO userDTO) { - String userLogin = SecurityUtils.getCurrentUserLogin() - .orElseThrow( - () -> new AccountResourceException("Current user login not found")); - Optional<User> existingUser = userRepository - .findOneByEmailIgnoreCase(userDTO.getEmail()); - if (existingUser.isPresent() - && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { + String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found")); + Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); } Optional<User> user = userRepository.findOneByLogin(userLogin); if (!user.isPresent()) { throw new AccountResourceException("User could not be found"); } - userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), - userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl()); + userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl()); } /** @@ -163,8 +153,7 @@ public class AccountResource { if (!checkPasswordLength(passwordChangeDto.getNewPassword())) { throw new InvalidPasswordException(); } - userService.changePassword(passwordChangeDto.getCurrentPassword(), - passwordChangeDto.getNewPassword()); + userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword()); } /** @@ -196,23 +185,22 @@ public class AccountResource { * {@code 500 (Internal Server Error)} if the password could not be reset. */ @PostMapping(path = "/account/reset-password/finish") - public void finishPasswordReset( - @RequestBody KeyAndPasswordVM keyAndPassword) { + public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } - Optional<User> user = userService.completePasswordReset( - keyAndPassword.getNewPassword(), keyAndPassword.getKey()); + Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { - throw new AccountResourceException( - "No user was found for this reset key"); + throw new AccountResourceException("No user was found for this reset key"); } } private static boolean checkPasswordLength(String password) { - return !StringUtils.isEmpty(password) - && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH - && password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; + return ( + !StringUtils.isEmpty(password) && + password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && + password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH + ); } } diff --git a/src/main/java/com/ippon/pouet/web/rest/AuditResource.java b/src/main/java/com/ippon/pouet/web/rest/AuditResource.java index 294b61ba326f2ee8bdd7978155e587a6af064142..040e9ce9a74beb4b09b42b4d920d28b87b2f020c 100644 --- a/src/main/java/com/ippon/pouet/web/rest/AuditResource.java +++ b/src/main/java/com/ippon/pouet/web/rest/AuditResource.java @@ -2,9 +2,12 @@ package com.ippon.pouet.web.rest; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.service.AuditEventService; - import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.List; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -14,11 +17,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.List; - /** * REST controller for getting the {@link AuditEvent}s. */ @@ -26,56 +24,55 @@ import java.util.List; @RestController @RequestMapping("/management/audits") public class AuditResource { + private final AuditEventService auditEventService; - private final AuditEventService auditEventService; - - public AuditResource(AuditEventService auditEventService) { - this.auditEventService = auditEventService; - } - - /** - * {@code GET /audits} : get a page of {@link AuditEvent}s. - * - * @param pageable the pagination information. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body. - */ - @GetMapping - public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) { - Page<AuditEvent> page = auditEventService.findAll(pageable); - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); - return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); - } + public AuditResource(AuditEventService auditEventService) { + this.auditEventService = auditEventService; + } - /** - * {@code GET /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}. - * - * @param fromDate the start of the time period of {@link AuditEvent} to get. - * @param toDate the end of the time period of {@link AuditEvent} to get. - * @param pageable the pagination information. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body. - */ - @GetMapping(params = {"fromDate", "toDate"}) - public ResponseEntity<List<AuditEvent>> getByDates( - @RequestParam(value = "fromDate") LocalDate fromDate, - @RequestParam(value = "toDate") LocalDate toDate, - Pageable pageable) { + /** + * {@code GET /audits} : get a page of {@link AuditEvent}s. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body. + */ + @GetMapping + public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) { + Page<AuditEvent> page = auditEventService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + } - Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); - Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(); + /** + * {@code GET /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}. + * + * @param fromDate the start of the time period of {@link AuditEvent} to get. + * @param toDate the end of the time period of {@link AuditEvent} to get. + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body. + */ + @GetMapping(params = { "fromDate", "toDate" }) + public ResponseEntity<List<AuditEvent>> getByDates( + @RequestParam(value = "fromDate") LocalDate fromDate, + @RequestParam(value = "toDate") LocalDate toDate, + Pageable pageable + ) { + Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); + Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(); - Page<AuditEvent> page = auditEventService.findByDates(from, to, pageable); - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); - return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); - } + Page<AuditEvent> page = auditEventService.findByDates(from, to, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + } - /** - * {@code GET /audits/:id} : get an {@link AuditEvent} by id. - * - * @param id the id of the entity to get. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the {@link AuditEvent} in body, or status {@code 404 (Not Found)}. - */ - @GetMapping("/{id:.+}") - public ResponseEntity<AuditEvent> get(@PathVariable Long id) { - return ResponseUtil.wrapOrNotFound(auditEventService.find(id)); - } + /** + * {@code GET /audits/:id} : get an {@link AuditEvent} by id. + * + * @param id the id of the entity to get. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the {@link AuditEvent} in body, or status {@code 404 (Not Found)}. + */ + @GetMapping("/{id:.+}") + public ResponseEntity<AuditEvent> get(@PathVariable Long id) { + return ResponseUtil.wrapOrNotFound(auditEventService.find(id)); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/ClientForwardController.java b/src/main/java/com/ippon/pouet/web/rest/ClientForwardController.java index e5596324b841697e215c64313c9d859fc028eb2d..ea5b31b1c3773c0f1700fd07233b44d271cde306 100644 --- a/src/main/java/com/ippon/pouet/web/rest/ClientForwardController.java +++ b/src/main/java/com/ippon/pouet/web/rest/ClientForwardController.java @@ -1,20 +1,19 @@ package com.ippon.pouet.web.rest; +import com.ippon.pouet.common.domain.Generated; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import com.ippon.pouet.common.domain.Generated; - @Generated @Controller public class ClientForwardController { - /** - * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. - * @return forward to client {@code index.html}. - */ - @GetMapping(value = "/**/{path:[^\\.]*}") - public String forward() { - return "forward:/"; - } + /** + * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. + * @return forward to client {@code index.html}. + */ + @GetMapping(value = "/**/{path:[^\\.]*}") + public String forward() { + return "forward:/"; + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/UserJWTController.java b/src/main/java/com/ippon/pouet/web/rest/UserJWTController.java index e92423ff2aeac6574d6ce41ddc77c52502590693..a71ef839df465c21cd97358c1821501db7c0733e 100644 --- a/src/main/java/com/ippon/pouet/web/rest/UserJWTController.java +++ b/src/main/java/com/ippon/pouet/web/rest/UserJWTController.java @@ -1,12 +1,11 @@ package com.ippon.pouet.web.rest; +import com.fasterxml.jackson.annotation.JsonProperty; import com.ippon.pouet.common.domain.Generated; import com.ippon.pouet.security.jwt.JWTFilter; import com.ippon.pouet.security.jwt.TokenProvider; import com.ippon.pouet.web.rest.vm.LoginVM; - -import com.fasterxml.jackson.annotation.JsonProperty; - +import javax.validation.Valid; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -16,8 +15,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; - /** * Controller to authenticate users. */ @@ -25,49 +22,49 @@ import javax.validation.Valid; @RestController @RequestMapping("/api") public class UserJWTController { + private final TokenProvider tokenProvider; - private final TokenProvider tokenProvider; + private final AuthenticationManagerBuilder authenticationManagerBuilder; - private final AuthenticationManagerBuilder authenticationManagerBuilder; + public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { + this.tokenProvider = tokenProvider; + this.authenticationManagerBuilder = authenticationManagerBuilder; + } - public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { - this.tokenProvider = tokenProvider; - this.authenticationManagerBuilder = authenticationManagerBuilder; - } + @PostMapping("/authenticate") + public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + loginVM.getUsername(), + loginVM.getPassword() + ); - @PostMapping("/authenticate") - public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) { + Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); + SecurityContextHolder.getContext().setAuthentication(authentication); + boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); + String jwt = tokenProvider.createToken(authentication, rememberMe); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); + } - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); + /** + * Object to return as body in JWT Authentication. + */ + @Generated + static class JWTToken { + private String idToken; - Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); - SecurityContextHolder.getContext().setAuthentication(authentication); - boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); - String jwt = tokenProvider.createToken(authentication, rememberMe); - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); + JWTToken(String idToken) { + this.idToken = idToken; } - /** - * Object to return as body in JWT Authentication. - */ - @Generated - static class JWTToken { - - private String idToken; - JWTToken(String idToken) { - this.idToken = idToken; - } - - @JsonProperty("id_token") - String getIdToken() { - return idToken; - } + @JsonProperty("id_token") + String getIdToken() { + return idToken; + } - void setIdToken(String idToken) { - this.idToken = idToken; - } + void setIdToken(String idToken) { + this.idToken = idToken; } + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/UserResource.java b/src/main/java/com/ippon/pouet/web/rest/UserResource.java index 5569c2413a85ddb98ff5f37d9e1cd086bd5c8bab..051a4a54c7519df3ec00e5d1def8ac05c2b3b0a5 100644 --- a/src/main/java/com/ippon/pouet/web/rest/UserResource.java +++ b/src/main/java/com/ippon/pouet/web/rest/UserResource.java @@ -11,11 +11,13 @@ import com.ippon.pouet.service.dto.UserDTO; import com.ippon.pouet.web.rest.errors.BadRequestAlertException; import com.ippon.pouet.web.rest.errors.EmailAlreadyUsedException; import com.ippon.pouet.web.rest.errors.LoginAlreadyUsedException; - import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; - +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -28,11 +30,6 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import javax.validation.Valid; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; - /** * REST controller for managing users. * <p> @@ -61,131 +58,128 @@ import java.util.*; @RestController @RequestMapping("/api") public class UserResource { - - private final Logger log = LoggerFactory.getLogger(UserResource.class); - - @Value("${jhipster.clientApp.name}") - private String applicationName; - - private final UserService userService; - - private final UserRepository userRepository; - - private final MailService mailService; - - public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { - this.userService = userService; - this.userRepository = userRepository; - this.mailService = mailService; - } - - /** - * {@code POST /users} : Creates a new user. - * <p> - * Creates a new user if the login and email are not already used, and sends an - * mail with an activation link. - * The user needs to be activated on creation. - * - * @param userDTO the user to create. - * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use. - * @throws URISyntaxException if the Location URI syntax is incorrect. - * @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use. - */ - @PostMapping("/users") - @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { - log.debug("REST request to save User : {}", userDTO); - - if (userDTO.getId() != null) { - throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); - // Lowercase the user login before comparing with database - } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { - throw new LoginAlreadyUsedException(); - } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { - throw new EmailAlreadyUsedException(); - } else { - User newUser = userService.createUser(userDTO); - mailService.sendCreationEmail(newUser); - return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) - .headers(HeaderUtil.createAlert(applicationName, "userManagement.created", newUser.getLogin())) - .body(newUser); - } - } - - /** - * {@code PUT /users} : Updates an existing User. - * - * @param userDTO the user to update. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user. - * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use. - * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use. - */ - @PutMapping("/users") - @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { - log.debug("REST request to update User : {}", userDTO); - Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); - if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { - throw new EmailAlreadyUsedException(); - } - existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); - if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { - throw new LoginAlreadyUsedException(); - } - Optional<UserDTO> updatedUser = userService.updateUser(userDTO); - - return ResponseUtil.wrapOrNotFound(updatedUser, - HeaderUtil.createAlert(applicationName, "userManagement.updated", userDTO.getLogin())); - } - - /** - * {@code GET /users} : get all users. - * - * @param pageable the pagination information. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. - */ - @GetMapping("/users") - public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) { - final Page<UserDTO> page = userService.getAllManagedUsers(pageable); - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); - return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + private final Logger log = LoggerFactory.getLogger(UserResource.class); + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final UserService userService; + + private final UserRepository userRepository; + + private final MailService mailService; + + public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { + this.userService = userService; + this.userRepository = userRepository; + this.mailService = mailService; + } + + /** + * {@code POST /users} : Creates a new user. + * <p> + * Creates a new user if the login and email are not already used, and sends an + * mail with an activation link. + * The user needs to be activated on creation. + * + * @param userDTO the user to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use. + * @throws URISyntaxException if the Location URI syntax is incorrect. + * @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use. + */ + @PostMapping("/users") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { + log.debug("REST request to save User : {}", userDTO); + + if (userDTO.getId() != null) { + throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); + // Lowercase the user login before comparing with database + } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { + throw new LoginAlreadyUsedException(); + } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { + throw new EmailAlreadyUsedException(); + } else { + User newUser = userService.createUser(userDTO); + mailService.sendCreationEmail(newUser); + return ResponseEntity + .created(new URI("/api/users/" + newUser.getLogin())) + .headers(HeaderUtil.createAlert(applicationName, "userManagement.created", newUser.getLogin())) + .body(newUser); } - - /** - * Gets a list of all roles. - * @return a string list of all roles. - */ - @GetMapping("/users/authorities") - @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - public List<String> getAuthorities() { - return userService.getAuthorities(); + } + + /** + * {@code PUT /users} : Updates an existing User. + * + * @param userDTO the user to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user. + * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use. + * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use. + */ + @PutMapping("/users") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { + log.debug("REST request to update User : {}", userDTO); + Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { + throw new EmailAlreadyUsedException(); } - - /** - * {@code GET /users/:login} : get the "login" user. - * - * @param login the login of the user to find. - * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. - */ - @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") - public ResponseEntity<UserDTO> getUser(@PathVariable String login) { - log.debug("REST request to get User : {}", login); - return ResponseUtil.wrapOrNotFound( - userService.getUserWithAuthoritiesByLogin(login) - .map(UserDTO::new)); - } - - /** - * {@code DELETE /users/:login} : delete the "login" User. - * - * @param login the login of the user to delete. - * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. - */ - @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") - @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - public ResponseEntity<Void> deleteUser(@PathVariable String login) { - log.debug("REST request to delete User: {}", login); - userService.deleteUser(login); - return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, "userManagement.deleted", login)).build(); + existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); + if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { + throw new LoginAlreadyUsedException(); } + Optional<UserDTO> updatedUser = userService.updateUser(userDTO); + + return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert(applicationName, "userManagement.updated", userDTO.getLogin())); + } + + /** + * {@code GET /users} : get all users. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. + */ + @GetMapping("/users") + public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) { + final Page<UserDTO> page = userService.getAllManagedUsers(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + } + + /** + * Gets a list of all roles. + * @return a string list of all roles. + */ + @GetMapping("/users/authorities") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public List<String> getAuthorities() { + return userService.getAuthorities(); + } + + /** + * {@code GET /users/:login} : get the "login" user. + * + * @param login the login of the user to find. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") + public ResponseEntity<UserDTO> getUser(@PathVariable String login) { + log.debug("REST request to get User : {}", login); + return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(UserDTO::new)); + } + + /** + * {@code DELETE /users/:login} : delete the "login" User. + * + * @param login the login of the user to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity<Void> deleteUser(@PathVariable String login) { + log.debug("REST request to delete User: {}", login); + userService.deleteUser(login); + return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, "userManagement.deleted", login)).build(); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/BadRequestAlertException.java b/src/main/java/com/ippon/pouet/web/rest/errors/BadRequestAlertException.java index ded6041835414e8ba9b91a86e1f7eeddcc0f9747..8259bdb1a096ac35a0017054fc07bb00f05952eb 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/BadRequestAlertException.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/BadRequestAlertException.java @@ -1,45 +1,42 @@ package com.ippon.pouet.web.rest.errors; -import org.zalando.problem.AbstractThrowableProblem; -import org.zalando.problem.Status; - import com.ippon.pouet.common.domain.Generated; - import java.net.URI; import java.util.HashMap; import java.util.Map; +import org.zalando.problem.AbstractThrowableProblem; +import org.zalando.problem.Status; @Generated public class BadRequestAlertException extends AbstractThrowableProblem { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - private final String entityName; + private final String entityName; - private final String errorKey; + private final String errorKey; - public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { - this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); - } + public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { + this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); + } - public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { - super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey)); - this.entityName = entityName; - this.errorKey = errorKey; - } + public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { + super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey)); + this.entityName = entityName; + this.errorKey = errorKey; + } - public String getEntityName() { - return entityName; - } + public String getEntityName() { + return entityName; + } - public String getErrorKey() { - return errorKey; - } + public String getErrorKey() { + return errorKey; + } - private static Map<String, Object> getAlertParameters(String entityName, String errorKey) { - Map<String, Object> parameters = new HashMap<>(); - parameters.put("message", "error." + errorKey); - parameters.put("params", entityName); - return parameters; - } + private static Map<String, Object> getAlertParameters(String entityName, String errorKey) { + Map<String, Object> parameters = new HashMap<>(); + parameters.put("message", "error." + errorKey); + parameters.put("params", entityName); + return parameters; + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/EmailAlreadyUsedException.java b/src/main/java/com/ippon/pouet/web/rest/errors/EmailAlreadyUsedException.java index a77acbbe9bdf7cf053c06631345004542085dc7b..187ca67d650a377c9afdd38d57c9fb8ca0bf9979 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/EmailAlreadyUsedException.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/EmailAlreadyUsedException.java @@ -4,10 +4,9 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class EmailAlreadyUsedException extends BadRequestAlertException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public EmailAlreadyUsedException() { - super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); - } + public EmailAlreadyUsedException() { + super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/ErrorConstants.java b/src/main/java/com/ippon/pouet/web/rest/errors/ErrorConstants.java index 6e6ba6cb95120da44c97cb6d5a6523cb3e477efe..d505d8756bf136d0a370d0ecc4fda10515f1a88e 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/ErrorConstants.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/ErrorConstants.java @@ -1,21 +1,18 @@ package com.ippon.pouet.web.rest.errors; -import java.net.URI; - import com.ippon.pouet.common.domain.Generated; +import java.net.URI; @Generated public final class ErrorConstants { + public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; + public static final String ERR_VALIDATION = "error.validation"; + public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; + public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); + public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); + public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); + public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); + public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); - public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; - public static final String ERR_VALIDATION = "error.validation"; - public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; - public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); - public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); - public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); - public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); - public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); - - private ErrorConstants() { - } + private ErrorConstants() {} } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/ExceptionTranslator.java b/src/main/java/com/ippon/pouet/web/rest/errors/ExceptionTranslator.java index 09a605ee0a76d426f00a4be2c29c74ec1a507f8f..467eb8077f6818acd54ced9a19f214fddc942ce0 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/ExceptionTranslator.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/ExceptionTranslator.java @@ -1,7 +1,12 @@ package com.ippon.pouet.web.rest.errors; +import com.ippon.pouet.common.domain.Generated; import io.github.jhipster.web.util.HeaderUtil; - +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.ResponseEntity; @@ -18,14 +23,6 @@ import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.zalando.problem.violations.ConstraintViolationProblem; -import com.ippon.pouet.common.domain.Generated; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807). @@ -33,95 +30,107 @@ import java.util.stream.Collectors; @Generated @ControllerAdvice public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait { - - private static final String FIELD_ERRORS_KEY = "fieldErrors"; - private static final String MESSAGE_KEY = "message"; - private static final String PATH_KEY = "path"; - private static final String VIOLATIONS_KEY = "violations"; - - @Value("${jhipster.clientApp.name}") - private String applicationName; - - /** - * Post-process the Problem payload to add the message key for the front-end if needed. - */ - @Override - public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) { - if (entity == null) { - return entity; - } - Problem problem = entity.getBody(); - if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { - return entity; - } - ProblemBuilder builder = Problem.builder() - .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) - .withStatus(problem.getStatus()) - .withTitle(problem.getTitle()) - .with(PATH_KEY, request.getNativeRequest(HttpServletRequest.class).getRequestURI()); - - if (problem instanceof ConstraintViolationProblem) { - builder - .with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()) - .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION); - } else { - builder - .withCause(((DefaultProblem) problem).getCause()) - .withDetail(problem.getDetail()) - .withInstance(problem.getInstance()); - problem.getParameters().forEach(builder::with); - if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) { - builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode()); - } - } - return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); + private static final String FIELD_ERRORS_KEY = "fieldErrors"; + private static final String MESSAGE_KEY = "message"; + private static final String PATH_KEY = "path"; + private static final String VIOLATIONS_KEY = "violations"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + /** + * Post-process the Problem payload to add the message key for the front-end if needed. + */ + @Override + public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) { + if (entity == null) { + return entity; } - - @Override - public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { - BindingResult result = ex.getBindingResult(); - List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream() - .map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("DTO$", ""), f.getField(), f.getCode())) - .collect(Collectors.toList()); - - Problem problem = Problem.builder() - .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) - .withTitle("Method argument not valid") - .withStatus(defaultConstraintViolationStatus()) - .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION) - .with(FIELD_ERRORS_KEY, fieldErrors) - .build(); - return create(ex, problem, request); - } - - @ExceptionHandler - public ResponseEntity<Problem> handleEmailAlreadyUsedException(com.ippon.pouet.service.EmailAlreadyUsedException ex, NativeWebRequest request) { - EmailAlreadyUsedException problem = new EmailAlreadyUsedException(); - return create(problem, request, HeaderUtil.createFailureAlert(applicationName, true, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())); + Problem problem = entity.getBody(); + if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { + return entity; } - - @ExceptionHandler - public ResponseEntity<Problem> handleUsernameAlreadyUsedException(com.ippon.pouet.service.UsernameAlreadyUsedException ex, NativeWebRequest request) { - LoginAlreadyUsedException problem = new LoginAlreadyUsedException(); - return create(problem, request, HeaderUtil.createFailureAlert(applicationName, true, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())); - } - - @ExceptionHandler - public ResponseEntity<Problem> handleInvalidPasswordException(com.ippon.pouet.service.InvalidPasswordException ex, NativeWebRequest request) { - return create(new InvalidPasswordException(), request); - } - - @ExceptionHandler - public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { - return create(ex, request, HeaderUtil.createFailureAlert(applicationName, true, ex.getEntityName(), ex.getErrorKey(), ex.getMessage())); - } - - @ExceptionHandler - public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { - Problem problem = Problem.builder() - .withStatus(Status.CONFLICT) - .with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE) - .build(); - return create(ex, problem, request); + ProblemBuilder builder = Problem + .builder() + .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) + .withStatus(problem.getStatus()) + .withTitle(problem.getTitle()) + .with(PATH_KEY, request.getNativeRequest(HttpServletRequest.class).getRequestURI()); + + if (problem instanceof ConstraintViolationProblem) { + builder.with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()).with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION); + } else { + builder.withCause(((DefaultProblem) problem).getCause()).withDetail(problem.getDetail()).withInstance(problem.getInstance()); + problem.getParameters().forEach(builder::with); + if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) { + builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode()); + } } + return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); + } + + @Override + public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { + BindingResult result = ex.getBindingResult(); + List<FieldErrorVM> fieldErrors = result + .getFieldErrors() + .stream() + .map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("DTO$", ""), f.getField(), f.getCode())) + .collect(Collectors.toList()); + + Problem problem = Problem + .builder() + .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) + .withTitle("Method argument not valid") + .withStatus(defaultConstraintViolationStatus()) + .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION) + .with(FIELD_ERRORS_KEY, fieldErrors) + .build(); + return create(ex, problem, request); + } + + @ExceptionHandler + public ResponseEntity<Problem> handleEmailAlreadyUsedException( + com.ippon.pouet.service.EmailAlreadyUsedException ex, + NativeWebRequest request + ) { + EmailAlreadyUsedException problem = new EmailAlreadyUsedException(); + return create( + problem, + request, + HeaderUtil.createFailureAlert(applicationName, true, problem.getEntityName(), problem.getErrorKey(), problem.getMessage()) + ); + } + + @ExceptionHandler + public ResponseEntity<Problem> handleUsernameAlreadyUsedException( + com.ippon.pouet.service.UsernameAlreadyUsedException ex, + NativeWebRequest request + ) { + LoginAlreadyUsedException problem = new LoginAlreadyUsedException(); + return create( + problem, + request, + HeaderUtil.createFailureAlert(applicationName, true, problem.getEntityName(), problem.getErrorKey(), problem.getMessage()) + ); + } + + @ExceptionHandler + public ResponseEntity<Problem> handleInvalidPasswordException( + com.ippon.pouet.service.InvalidPasswordException ex, + NativeWebRequest request + ) { + return create(new InvalidPasswordException(), request); + } + + @ExceptionHandler + public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { + return create(ex, request, HeaderUtil.createFailureAlert(applicationName, true, ex.getEntityName(), ex.getErrorKey(), ex.getMessage())); + } + + @ExceptionHandler + public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { + Problem problem = Problem.builder().withStatus(Status.CONFLICT).with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE).build(); + return create(ex, problem, request); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/FieldErrorVM.java b/src/main/java/com/ippon/pouet/web/rest/errors/FieldErrorVM.java index a307b7635f8e29d820b023aff4e4a676f6839aee..3fcd880cd980664ad38ff07ad09f65fc47563dff 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/FieldErrorVM.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/FieldErrorVM.java @@ -1,36 +1,33 @@ package com.ippon.pouet.web.rest.errors; -import java.io.Serializable; - import com.ippon.pouet.common.domain.Generated; +import java.io.Serializable; @Generated public class FieldErrorVM implements Serializable { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - private final String objectName; - - private final String field; + private final String objectName; - private final String message; + private final String field; - public FieldErrorVM(String dto, String field, String message) { - this.objectName = dto; - this.field = field; - this.message = message; - } + private final String message; - public String getObjectName() { - return objectName; - } + public FieldErrorVM(String dto, String field, String message) { + this.objectName = dto; + this.field = field; + this.message = message; + } - public String getField() { - return field; - } + public String getObjectName() { + return objectName; + } - public String getMessage() { - return message; - } + public String getField() { + return field; + } + public String getMessage() { + return message; + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/InvalidPasswordException.java b/src/main/java/com/ippon/pouet/web/rest/errors/InvalidPasswordException.java index 9f0f59d77528edbdfbdbe44f6dd7683867530f91..6c9ed37b72b5fb66a30532ee0923412df0b4d23a 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/InvalidPasswordException.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/InvalidPasswordException.java @@ -1,16 +1,14 @@ package com.ippon.pouet.web.rest.errors; +import com.ippon.pouet.common.domain.Generated; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; -import com.ippon.pouet.common.domain.Generated; - @Generated public class InvalidPasswordException extends AbstractThrowableProblem { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public InvalidPasswordException() { - super(ErrorConstants.INVALID_PASSWORD_TYPE, "Incorrect password", Status.BAD_REQUEST); - } + public InvalidPasswordException() { + super(ErrorConstants.INVALID_PASSWORD_TYPE, "Incorrect password", Status.BAD_REQUEST); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/errors/LoginAlreadyUsedException.java b/src/main/java/com/ippon/pouet/web/rest/errors/LoginAlreadyUsedException.java index 00e777f46b8963e84a2714ff9433a8a67d9464ae..a6c6eae7f444e11c16bcd2c3d10fcad653e24dee 100644 --- a/src/main/java/com/ippon/pouet/web/rest/errors/LoginAlreadyUsedException.java +++ b/src/main/java/com/ippon/pouet/web/rest/errors/LoginAlreadyUsedException.java @@ -4,10 +4,9 @@ import com.ippon.pouet.common.domain.Generated; @Generated public class LoginAlreadyUsedException extends BadRequestAlertException { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - public LoginAlreadyUsedException() { - super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); - } + public LoginAlreadyUsedException() { + super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/vm/KeyAndPasswordVM.java b/src/main/java/com/ippon/pouet/web/rest/vm/KeyAndPasswordVM.java index 14d8ea1fdf000a5dbd6027a61d9656f4008e7b57..a66cf95769e254c8f105bfe10b234fa04789b9f5 100644 --- a/src/main/java/com/ippon/pouet/web/rest/vm/KeyAndPasswordVM.java +++ b/src/main/java/com/ippon/pouet/web/rest/vm/KeyAndPasswordVM.java @@ -7,24 +7,23 @@ import com.ippon.pouet.common.domain.Generated; */ @Generated public class KeyAndPasswordVM { + private String key; - private String key; + private String newPassword; - private String newPassword; + public String getKey() { + return key; + } - public String getKey() { - return key; - } + public void setKey(String key) { + this.key = key; + } - public void setKey(String key) { - this.key = key; - } + public String getNewPassword() { + return newPassword; + } - public String getNewPassword() { - return newPassword; - } - - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } } diff --git a/src/main/java/com/ippon/pouet/web/rest/vm/LoginVM.java b/src/main/java/com/ippon/pouet/web/rest/vm/LoginVM.java index 1a6d8445b861ab6a21e61f5f5d26c6d4efda3b02..06a319502a758f7ae4135e67ee4cdd7b3f8ae745 100644 --- a/src/main/java/com/ippon/pouet/web/rest/vm/LoginVM.java +++ b/src/main/java/com/ippon/pouet/web/rest/vm/LoginVM.java @@ -1,51 +1,49 @@ package com.ippon.pouet.web.rest.vm; +import com.ippon.pouet.common.domain.Generated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import com.ippon.pouet.common.domain.Generated; - /** * View Model object for storing a user's credentials. */ @Generated public class LoginVM { + @NotNull + @Size(min = 1, max = 50) + private String username; - @NotNull - @Size(min = 1, max = 50) - private String username; + @NotNull + @Size(min = 4, max = 100) + private String password; - @NotNull - @Size(min = 4, max = 100) - private String password; + private Boolean rememberMe; - private Boolean rememberMe; - - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - public Boolean isRememberMe() { - return rememberMe; - } + public Boolean isRememberMe() { + return rememberMe; + } - public void setRememberMe(Boolean rememberMe) { - this.rememberMe = rememberMe; - } + public void setRememberMe(Boolean rememberMe) { + this.rememberMe = rememberMe; + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "LoginVM{" + diff --git a/src/main/java/com/ippon/pouet/web/rest/vm/ManagedUserVM.java b/src/main/java/com/ippon/pouet/web/rest/vm/ManagedUserVM.java index d7cdacabd59becd0aee11f36f78fcf8914cff7f5..f233ae27156345f4e7cac01229a8e2aa9c9ff0ff 100644 --- a/src/main/java/com/ippon/pouet/web/rest/vm/ManagedUserVM.java +++ b/src/main/java/com/ippon/pouet/web/rest/vm/ManagedUserVM.java @@ -9,27 +9,26 @@ import javax.validation.constraints.Size; */ @Generated public class ManagedUserVM extends UserDTO { + public static final int PASSWORD_MIN_LENGTH = 4; - public static final int PASSWORD_MIN_LENGTH = 4; + public static final int PASSWORD_MAX_LENGTH = 100; - public static final int PASSWORD_MAX_LENGTH = 100; + @Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH) + private String password; - @Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH) - private String password; + public ManagedUserVM() { + // Empty constructor needed for Jackson. + } - public ManagedUserVM() { - // Empty constructor needed for Jackson. - } - - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "ManagedUserVM{" + super.toString() + "} "; diff --git a/src/test/java/com/ippon/pouet/config/NoOpMailConfiguration.java b/src/test/java/com/ippon/pouet/config/NoOpMailConfiguration.java index 8c18876cd5f6c1a33d3f75acbd23e43d3a4b7b1a..95ee5e80ed73bb0efb589c1409f399cfb36878db 100644 --- a/src/test/java/com/ippon/pouet/config/NoOpMailConfiguration.java +++ b/src/test/java/com/ippon/pouet/config/NoOpMailConfiguration.java @@ -1,24 +1,24 @@ package com.ippon.pouet.config; -import com.ippon.pouet.service.MailService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; +import com.ippon.pouet.service.MailService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + @Configuration public class NoOpMailConfiguration { - private final MailService mockMailService; + private final MailService mockMailService; - public NoOpMailConfiguration() { - mockMailService = mock(MailService.class); - doNothing().when(mockMailService).sendActivationEmail(any()); - } + public NoOpMailConfiguration() { + mockMailService = mock(MailService.class); + doNothing().when(mockMailService).sendActivationEmail(any()); + } - @Bean - public MailService mailService() { - return mockMailService; - } + @Bean + public MailService mailService() { + return mockMailService; + } } diff --git a/src/test/java/com/ippon/pouet/config/StaticResourcesWebConfigurerTest.java b/src/test/java/com/ippon/pouet/config/StaticResourcesWebConfigurerTest.java index 35d9e1cbf35208bd08cef2f75891ad0e919c5656..ad646ab7a5fe2f238accfbf64bede11f7cce414d 100644 --- a/src/test/java/com/ippon/pouet/config/StaticResourcesWebConfigurerTest.java +++ b/src/test/java/com/ippon/pouet/config/StaticResourcesWebConfigurerTest.java @@ -1,7 +1,12 @@ package com.ippon.pouet.config; +import static com.ippon.pouet.config.StaticResourcesWebConfiguration.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + import io.github.jhipster.config.JHipsterDefaults; import io.github.jhipster.config.JHipsterProperties; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.CacheControl; @@ -10,71 +15,61 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import java.util.concurrent.TimeUnit; - -import static com.ippon.pouet.config.StaticResourcesWebConfiguration.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; - public class StaticResourcesWebConfigurerTest { - public static final int MAX_AGE_TEST = 5; - public StaticResourcesWebConfiguration staticResourcesWebConfiguration; - private ResourceHandlerRegistry resourceHandlerRegistry; - private MockServletContext servletContext; - private WebApplicationContext applicationContext; - private JHipsterProperties props; - - @BeforeEach - void setUp() { - servletContext = spy(new MockServletContext()); - applicationContext = mock(WebApplicationContext.class); - resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext)); - props = new JHipsterProperties(); - staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props)); - } + public static final int MAX_AGE_TEST = 5; + public StaticResourcesWebConfiguration staticResourcesWebConfiguration; + private ResourceHandlerRegistry resourceHandlerRegistry; + private MockServletContext servletContext; + private WebApplicationContext applicationContext; + private JHipsterProperties props; - @Test - public void shouldAppendResourceHandlerAndInitiliazeIt() { + @BeforeEach + void setUp() { + servletContext = spy(new MockServletContext()); + applicationContext = mock(WebApplicationContext.class); + resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext)); + props = new JHipsterProperties(); + staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props)); + } - staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry); + @Test + public void shouldAppendResourceHandlerAndInitiliazeIt() { + staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry); - verify(resourceHandlerRegistry, times(1)) - .addResourceHandler(RESOURCE_PATHS); - verify(staticResourcesWebConfiguration, times(1)) - .initializeResourceHandler(any(ResourceHandlerRegistration.class)); - for (String testingPath : RESOURCE_PATHS) { - assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue(); - } + verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS); + verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.class)); + for (String testingPath : RESOURCE_PATHS) { + assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue(); } + } - @Test - public void shouldInitializeResourceHandlerWithCacheControlAndLocations() { - CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic(); - when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected); - ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS)); + @Test + public void shouldInitializeResourceHandlerWithCacheControlAndLocations() { + CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic(); + when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected); + ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS)); - staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration); - - verify(staticResourcesWebConfiguration, times(1)).getCacheControl(); - verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected); - verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS); - } + staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration); + verify(staticResourcesWebConfiguration, times(1)).getCacheControl(); + verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected); + verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS); + } - @Test - public void shoudCreateCacheControlBasedOnJhipsterDefaultProperties() { - CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic(); - assertThat(staticResourcesWebConfiguration.getCacheControl()) - .extracting(CacheControl::getHeaderValue) - .isEqualTo(cacheExpected.getHeaderValue()); - } + @Test + public void shoudCreateCacheControlBasedOnJhipsterDefaultProperties() { + CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic(); + assertThat(staticResourcesWebConfiguration.getCacheControl()) + .extracting(CacheControl::getHeaderValue) + .isEqualTo(cacheExpected.getHeaderValue()); + } - @Test - public void shoudCreateCacheControlWithSpecificConfigurationInProperties() { - props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST); - CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic(); - assertThat(staticResourcesWebConfiguration.getCacheControl()) - .extracting(CacheControl::getHeaderValue) - .isEqualTo(cacheExpected.getHeaderValue()); - } + @Test + public void shoudCreateCacheControlWithSpecificConfigurationInProperties() { + props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST); + CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic(); + assertThat(staticResourcesWebConfiguration.getCacheControl()) + .extracting(CacheControl::getHeaderValue) + .isEqualTo(cacheExpected.getHeaderValue()); + } } diff --git a/src/test/java/com/ippon/pouet/config/WebConfigurerTest.java b/src/test/java/com/ippon/pouet/config/WebConfigurerTest.java index a7101da287dfc323525a69b21bc9845e2b30af3a..f1a67f7e00080e7e60cc6e55554787d439a53699 100644 --- a/src/test/java/com/ippon/pouet/config/WebConfigurerTest.java +++ b/src/test/java/com/ippon/pouet/config/WebConfigurerTest.java @@ -1,7 +1,19 @@ package com.ippon.pouet.config; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; +import java.io.File; +import java.util.*; +import javax.servlet.*; import org.h2.server.web.WebServlet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,153 +24,123 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import javax.servlet.*; -import java.io.File; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Unit tests for the {@link WebConfigurer} class. */ public class WebConfigurerTest { + private WebConfigurer webConfigurer; - private WebConfigurer webConfigurer; + private MockServletContext servletContext; - private MockServletContext servletContext; + private MockEnvironment env; - private MockEnvironment env; + private JHipsterProperties props; - private JHipsterProperties props; + @BeforeEach + public void setup() { + servletContext = spy(new MockServletContext()); + doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class)); + doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class)); - @BeforeEach - public void setup() { - servletContext = spy(new MockServletContext()); - doReturn(mock(FilterRegistration.Dynamic.class)) - .when(servletContext).addFilter(anyString(), any(Filter.class)); - doReturn(mock(ServletRegistration.Dynamic.class)) - .when(servletContext).addServlet(anyString(), any(Servlet.class)); - - env = new MockEnvironment(); - props = new JHipsterProperties(); - - webConfigurer = new WebConfigurer(env, props); - } + env = new MockEnvironment(); + props = new JHipsterProperties(); - @Test - public void testStartUpProdServletContext() throws ServletException { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); - webConfigurer.onStartup(servletContext); + webConfigurer = new WebConfigurer(env, props); + } + @Test + public void testStartUpProdServletContext() throws ServletException { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); + webConfigurer.onStartup(servletContext); - verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); - } - - @Test - public void testStartUpDevServletContext() throws ServletException { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); - webConfigurer.onStartup(servletContext); - - - verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); - } - - @Test - public void testCustomizeServletContainer() { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); - UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); - webConfigurer.customize(container); - assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); - assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); - assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); - if (container.getDocumentRoot() != null) { - assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/")); - } - } - - @Test - public void testCorsFilterOnApiPath() throws Exception { - props.getCors().setAllowedOrigins(Collections.singletonList("*")); - props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); - props.getCors().setAllowedHeaders(Collections.singletonList("*")); - props.getCors().setMaxAge(1800L); - props.getCors().setAllowCredentials(true); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - options("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) - .andExpect(header().string(HttpHeaders.VARY, "Origin")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); - - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); - } - - @Test - public void testCorsFilterOnOtherPath() throws Exception { - props.getCors().setAllowedOrigins(Collections.singletonList("*")); - props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); - props.getCors().setAllowedHeaders(Collections.singletonList("*")); - props.getCors().setMaxAge(1800L); - props.getCors().setAllowCredentials(true); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - get("/test/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - } - - @Test - public void testCorsFilterDeactivated() throws Exception { - props.getCors().setAllowedOrigins(null); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - } + verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); + } - @Test - public void testCorsFilterDeactivated2() throws Exception { - props.getCors().setAllowedOrigins(new ArrayList<>()); + @Test + public void testStartUpDevServletContext() throws ServletException { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); + webConfigurer.onStartup(servletContext); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); + } - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + @Test + public void testCustomizeServletContainer() { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); + UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); + webConfigurer.customize(container); + assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); + assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); + assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); + if (container.getDocumentRoot() != null) { + assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/")); } + } + + @Test + public void testCorsFilterOnApiPath() throws Exception { + props.getCors().setAllowedOrigins(Collections.singletonList("*")); + props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(Collections.singletonList("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform( + options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + ) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) + .andExpect(header().string(HttpHeaders.VARY, "Origin")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); + } + + @Test + public void testCorsFilterOnOtherPath() throws Exception { + props.getCors().setAllowedOrigins(Collections.singletonList("*")); + props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(Collections.singletonList("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + public void testCorsFilterDeactivated() throws Exception { + props.getCors().setAllowedOrigins(null); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + public void testCorsFilterDeactivated2() throws Exception { + props.getCors().setAllowedOrigins(new ArrayList<>()); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } } diff --git a/src/test/java/com/ippon/pouet/config/WebConfigurerTestController.java b/src/test/java/com/ippon/pouet/config/WebConfigurerTestController.java index 3dab5117acf786097e81261d7f218257a388f4ea..444ff9256433b4214a58063539ad704a9cf6782c 100644 --- a/src/test/java/com/ippon/pouet/config/WebConfigurerTestController.java +++ b/src/test/java/com/ippon/pouet/config/WebConfigurerTestController.java @@ -6,11 +6,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class WebConfigurerTestController { - @GetMapping("/api/test-cors") - public void testCorsOnApiPath() { - } + @GetMapping("/api/test-cors") + public void testCorsOnApiPath() {} - @GetMapping("/test/test-cors") - public void testCorsOnOtherPath() { - } + @GetMapping("/test/test-cors") + public void testCorsOnOtherPath() {} } diff --git a/src/test/java/com/ippon/pouet/config/timezone/HibernateTimeZoneIT.java b/src/test/java/com/ippon/pouet/config/timezone/HibernateTimeZoneIT.java index 12e9cfe73093e7bb4b9f411471a9d10e34a3fe8c..9d90a8ff35b11e14aeb0a5c9f765768245780614 100644 --- a/src/test/java/com/ippon/pouet/config/timezone/HibernateTimeZoneIT.java +++ b/src/test/java/com/ippon/pouet/config/timezone/HibernateTimeZoneIT.java @@ -1,8 +1,13 @@ package com.ippon.pouet.config.timezone; +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.repository.timezone.DateTimeWrapper; import com.ippon.pouet.repository.timezone.DateTimeWrapperRepository; +import java.time.*; +import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -12,166 +17,146 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.transaction.annotation.Transactional; -import java.time.*; -import java.time.format.DateTimeFormatter; - -import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; - /** * Integration tests for the ZoneId Hibernate configuration. */ @SpringBootTest(classes = PouetApp.class) public class HibernateTimeZoneIT { + @Autowired + private DateTimeWrapperRepository dateTimeWrapperRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}") + private String zoneId; + + private DateTimeWrapper dateTimeWrapper; + private DateTimeFormatter dateTimeFormatter; + private DateTimeFormatter timeFormatter; + private DateTimeFormatter dateFormatter; + + @BeforeEach + public void setup() { + dateTimeWrapper = new DateTimeWrapper(); + dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z")); + dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0")); + dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00")); + dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00")); + dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); + + dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId)); + + timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId)); + + dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + } + + @Test + @Transactional + public void storeInstantWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("instant", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetTime() + .toLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } - @Autowired - private DateTimeWrapperRepository dateTimeWrapperRepository; - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}") - private String zoneId; - - private DateTimeWrapper dateTimeWrapper; - private DateTimeFormatter dateTimeFormatter; - private DateTimeFormatter timeFormatter; - private DateTimeFormatter dateFormatter; - - @BeforeEach - public void setup() { - dateTimeWrapper = new DateTimeWrapper(); - dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z")); - dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0")); - dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); - dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z")); - dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00")); - dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00")); - dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); - - dateTimeFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ss.S") - .withZone(ZoneId.of(zoneId)); - - timeFormatter = DateTimeFormatter - .ofPattern("HH:mm:ss") - .withZone(ZoneId.of(zoneId)); - - dateFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd"); - } - - @Test - @Transactional - public void storeInstantWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("instant", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalDateTime() - .atZone(ZoneId.systemDefault()) - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getOffsetDateTime() - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getZonedDateTime() - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getOffsetTime() - .toLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalDate() - .format(dateFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - private String generateSqlRequest(String fieldName, long id) { - return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); - } - - private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) { - while (sqlRowSet.next()) { - String dbValue = sqlRowSet.getString(1); - - assertThat(dbValue).isNotNull(); - assertThat(dbValue).isEqualTo(expectedValue); - } + private String generateSqlRequest(String fieldName, long id) { + return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); + } + + private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) { + while (sqlRowSet.next()) { + String dbValue = sqlRowSet.getString(1); + + assertThat(dbValue).isNotNull(); + assertThat(dbValue).isEqualTo(expectedValue); } + } } diff --git a/src/test/java/com/ippon/pouet/repository/CustomAuditEventRepositoryIT.java b/src/test/java/com/ippon/pouet/repository/CustomAuditEventRepositoryIT.java index d7cc3ed47f757434ec05d90698545eef0701a224..6e74c05c129758f5ff6b8e38cded7952006d525b 100644 --- a/src/test/java/com/ippon/pouet/repository/CustomAuditEventRepositoryIT.java +++ b/src/test/java/com/ippon/pouet/repository/CustomAuditEventRepositoryIT.java @@ -1,10 +1,18 @@ package com.ippon.pouet.repository; -import com.ippon.pouet.PouetApp; +import static com.ippon.pouet.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; +import static org.assertj.core.api.Assertions.assertThat; +import com.ippon.pouet.PouetApp; import com.ippon.pouet.config.Constants; import com.ippon.pouet.config.audit.AuditEventConverter; import com.ippon.pouet.domain.PersistentAuditEvent; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -15,144 +23,132 @@ import org.springframework.mock.web.MockHttpSession; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.transaction.annotation.Transactional; -import javax.servlet.http.HttpSession; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static com.ippon.pouet.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; - /** * Integration tests for {@link CustomAuditEventRepository}. */ @SpringBootTest(classes = PouetApp.class) @Transactional public class CustomAuditEventRepositoryIT { - - @Autowired - private PersistenceAuditEventRepository persistenceAuditEventRepository; - - @Autowired - private AuditEventConverter auditEventConverter; - - private CustomAuditEventRepository customAuditEventRepository; - - @BeforeEach - public void setup() { - customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); - persistenceAuditEventRepository.deleteAll(); - Instant oneHourAgo = Instant.now().minusSeconds(3600); - - PersistentAuditEvent testUserEvent = new PersistentAuditEvent(); - testUserEvent.setPrincipal("test-user"); - testUserEvent.setAuditEventType("test-type"); - testUserEvent.setAuditEventDate(oneHourAgo); - Map<String, String> data = new HashMap<>(); - data.put("test-key", "test-value"); - testUserEvent.setData(data); - - PersistentAuditEvent testOldUserEvent = new PersistentAuditEvent(); - testOldUserEvent.setPrincipal("test-user"); - testOldUserEvent.setAuditEventType("test-type"); - testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); - - PersistentAuditEvent testOtherUserEvent = new PersistentAuditEvent(); - testOtherUserEvent.setPrincipal("other-test-user"); - testOtherUserEvent.setAuditEventType("test-type"); - testOtherUserEvent.setAuditEventDate(oneHourAgo); - } - - @Test - public void addAuditEvent() { - Map<String, Object> data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); - assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); - assertThat(persistentAuditEvent.getData()).containsKey("test-key"); - assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); - assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) - .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); - } - - @Test - public void addAuditEventTruncateLargeData() { - Map<String, Object> data = new HashMap<>(); - StringBuilder largeData = new StringBuilder(); - for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { - largeData.append("a"); - } - data.put("test-key", largeData); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); - assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); - assertThat(persistentAuditEvent.getData()).containsKey("test-key"); - String actualData = persistentAuditEvent.getData().get("test-key"); - assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); - assertThat(actualData).isSubstringOf(largeData); - assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) - .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); - } - - @Test - public void testAddEventWithWebAuthenticationDetails() { - HttpSession session = new MockHttpSession(null, "test-session-id"); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setSession(session); - request.setRemoteAddr("1.2.3.4"); - WebAuthenticationDetails details = new WebAuthenticationDetails(request); - Map<String, Object> data = new HashMap<>(); - data.put("test-key", details); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); - assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); - } - - @Test - public void testAddEventWithNullData() { - Map<String, Object> data = new HashMap<>(); - data.put("test-key", null); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); + @Autowired + private PersistenceAuditEventRepository persistenceAuditEventRepository; + + @Autowired + private AuditEventConverter auditEventConverter; + + private CustomAuditEventRepository customAuditEventRepository; + + @BeforeEach + public void setup() { + customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); + persistenceAuditEventRepository.deleteAll(); + Instant oneHourAgo = Instant.now().minusSeconds(3600); + + PersistentAuditEvent testUserEvent = new PersistentAuditEvent(); + testUserEvent.setPrincipal("test-user"); + testUserEvent.setAuditEventType("test-type"); + testUserEvent.setAuditEventDate(oneHourAgo); + Map<String, String> data = new HashMap<>(); + data.put("test-key", "test-value"); + testUserEvent.setData(data); + + PersistentAuditEvent testOldUserEvent = new PersistentAuditEvent(); + testOldUserEvent.setPrincipal("test-user"); + testOldUserEvent.setAuditEventType("test-type"); + testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); + + PersistentAuditEvent testOtherUserEvent = new PersistentAuditEvent(); + testOtherUserEvent.setPrincipal("other-test-user"); + testOtherUserEvent.setAuditEventType("test-type"); + testOtherUserEvent.setAuditEventDate(oneHourAgo); + } + + @Test + public void addAuditEvent() { + Map<String, Object> data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); + assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); + } + + @Test + public void addAuditEventTruncateLargeData() { + Map<String, Object> data = new HashMap<>(); + StringBuilder largeData = new StringBuilder(); + for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { + largeData.append("a"); } - - @Test - public void addAuditEventWithAnonymousUser() { - Map<String, Object> data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(0); - } - - @Test - public void addAuditEventWithAuthorizationFailureType() { - Map<String, Object> data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); - customAuditEventRepository.add(event); - List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(0); - } - + data.put("test-key", largeData); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + String actualData = persistentAuditEvent.getData().get("test-key"); + assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); + assertThat(actualData).isSubstringOf(largeData); + assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); + } + + @Test + public void testAddEventWithWebAuthenticationDetails() { + HttpSession session = new MockHttpSession(null, "test-session-id"); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setSession(session); + request.setRemoteAddr("1.2.3.4"); + WebAuthenticationDetails details = new WebAuthenticationDetails(request); + Map<String, Object> data = new HashMap<>(); + data.put("test-key", details); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); + assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); + } + + @Test + public void testAddEventWithNullData() { + Map<String, Object> data = new HashMap<>(); + data.put("test-key", null); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); + } + + @Test + public void addAuditEventWithAnonymousUser() { + Map<String, Object> data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } + + @Test + public void addAuditEventWithAuthorizationFailureType() { + Map<String, Object> data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); + customAuditEventRepository.add(event); + List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } } diff --git a/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapper.java b/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapper.java index 7dd6eb832dfb66d7ddb4d49aaa8b7ac23c718ec4..20e95187d0c19ea121744e669b0a468e0d602c77 100644 --- a/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapper.java +++ b/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapper.java @@ -1,125 +1,124 @@ package com.ippon.pouet.repository.timezone; -import javax.persistence.*; import java.io.Serializable; import java.time.*; import java.util.Objects; +import javax.persistence.*; @Entity @Table(name = "jhi_date_time_wrapper") public class DateTimeWrapper implements Serializable { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + private Long id; - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") - @SequenceGenerator(name = "sequenceGenerator") - private Long id; + @Column(name = "instant") + private Instant instant; - @Column(name = "instant") - private Instant instant; + @Column(name = "local_date_time") + private LocalDateTime localDateTime; - @Column(name = "local_date_time") - private LocalDateTime localDateTime; + @Column(name = "offset_date_time") + private OffsetDateTime offsetDateTime; - @Column(name = "offset_date_time") - private OffsetDateTime offsetDateTime; + @Column(name = "zoned_date_time") + private ZonedDateTime zonedDateTime; - @Column(name = "zoned_date_time") - private ZonedDateTime zonedDateTime; + @Column(name = "local_time") + private LocalTime localTime; - @Column(name = "local_time") - private LocalTime localTime; + @Column(name = "offset_time") + private OffsetTime offsetTime; - @Column(name = "offset_time") - private OffsetTime offsetTime; + @Column(name = "local_date") + private LocalDate localDate; - @Column(name = "local_date") - private LocalDate localDate; + public Long getId() { + return id; + } - public Long getId() { - return id; - } + public void setId(Long id) { + this.id = id; + } - public void setId(Long id) { - this.id = id; - } + public Instant getInstant() { + return instant; + } - public Instant getInstant() { - return instant; - } + public void setInstant(Instant instant) { + this.instant = instant; + } - public void setInstant(Instant instant) { - this.instant = instant; - } + public LocalDateTime getLocalDateTime() { + return localDateTime; + } - public LocalDateTime getLocalDateTime() { - return localDateTime; - } + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } - public void setLocalDateTime(LocalDateTime localDateTime) { - this.localDateTime = localDateTime; - } + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } - public OffsetDateTime getOffsetDateTime() { - return offsetDateTime; - } + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } - public void setOffsetDateTime(OffsetDateTime offsetDateTime) { - this.offsetDateTime = offsetDateTime; - } + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } - public ZonedDateTime getZonedDateTime() { - return zonedDateTime; - } + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } - public void setZonedDateTime(ZonedDateTime zonedDateTime) { - this.zonedDateTime = zonedDateTime; - } + public LocalTime getLocalTime() { + return localTime; + } - public LocalTime getLocalTime() { - return localTime; - } + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } - public void setLocalTime(LocalTime localTime) { - this.localTime = localTime; - } + public OffsetTime getOffsetTime() { + return offsetTime; + } - public OffsetTime getOffsetTime() { - return offsetTime; - } + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } - public void setOffsetTime(OffsetTime offsetTime) { - this.offsetTime = offsetTime; - } + public LocalDate getLocalDate() { + return localDate; + } - public LocalDate getLocalDate() { - return localDate; - } + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } - public void setLocalDate(LocalDate localDate) { - this.localDate = localDate; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o; - return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId()); + if (o == null || getClass() != o.getClass()) { + return false; } - @Override - public int hashCode() { - return Objects.hashCode(getId()); - } + DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o; + return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } - // prettier-ignore + // prettier-ignore @Override public String toString() { return "TimeZoneTest{" + diff --git a/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapperRepository.java b/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapperRepository.java index 34da12d305ae9765674dd3361adc3f1321caa84c..eb74bafe4085ce2fbbdba185c7c9b8a33928e1bf 100644 --- a/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapperRepository.java +++ b/src/test/java/com/ippon/pouet/repository/timezone/DateTimeWrapperRepository.java @@ -7,6 +7,4 @@ import org.springframework.stereotype.Repository; * Spring Data JPA repository for the {@link DateTimeWrapper} entity. */ @Repository -public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> { - -} +public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {} diff --git a/src/test/java/com/ippon/pouet/security/DomainUserDetailsServiceIT.java b/src/test/java/com/ippon/pouet/security/DomainUserDetailsServiceIT.java index 26aad41eb08166c14ba10324cf017c6940ead1a9..1bed3dafd6bbbb4ea20b070231b5f224d75c34b0 100644 --- a/src/test/java/com/ippon/pouet/security/DomainUserDetailsServiceIT.java +++ b/src/test/java/com/ippon/pouet/security/DomainUserDetailsServiceIT.java @@ -1,9 +1,12 @@ package com.ippon.pouet.security; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.domain.User; import com.ippon.pouet.repository.UserRepository; - +import java.util.Locale; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,103 +16,96 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.transaction.annotation.Transactional; -import java.util.Locale; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - /** * Integrations tests for {@link DomainUserDetailsService}. */ @SpringBootTest(classes = PouetApp.class) @Transactional public class DomainUserDetailsServiceIT { - - private static final String USER_ONE_LOGIN = "test-user-one"; - private static final String USER_ONE_EMAIL = "test-user-one@localhost"; - private static final String USER_TWO_LOGIN = "test-user-two"; - private static final String USER_TWO_EMAIL = "test-user-two@localhost"; - private static final String USER_THREE_LOGIN = "test-user-three"; - private static final String USER_THREE_EMAIL = "test-user-three@localhost"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserDetailsService domainUserDetailsService; - - @BeforeEach - public void init() { - User userOne = new User(); - userOne.setLogin(USER_ONE_LOGIN); - userOne.setPassword(RandomStringUtils.random(60)); - userOne.setActivated(true); - userOne.setEmail(USER_ONE_EMAIL); - userOne.setFirstName("userOne"); - userOne.setLastName("doe"); - userOne.setLangKey("en"); - userRepository.save(userOne); - - User userTwo = new User(); - userTwo.setLogin(USER_TWO_LOGIN); - userTwo.setPassword(RandomStringUtils.random(60)); - userTwo.setActivated(true); - userTwo.setEmail(USER_TWO_EMAIL); - userTwo.setFirstName("userTwo"); - userTwo.setLastName("doe"); - userTwo.setLangKey("en"); - userRepository.save(userTwo); - - User userThree = new User(); - userThree.setLogin(USER_THREE_LOGIN); - userThree.setPassword(RandomStringUtils.random(60)); - userThree.setActivated(false); - userThree.setEmail(USER_THREE_EMAIL); - userThree.setFirstName("userThree"); - userThree.setLastName("doe"); - userThree.setLangKey("en"); - userRepository.save(userThree); - } - - @Test - public void assertThatUserCanBeFoundByLogin() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test - public void assertThatUserCanBeFoundByLoginIgnoreCase() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test - public void assertThatUserCanBeFoundByEmail() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); - } - - @Test - public void assertThatUserCanBeFoundByEmailIgnoreCase() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); - } - - @Test - public void assertThatEmailIsPrioritizedOverLogin() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test - public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { - assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy( - () -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)); - } - + private static final String USER_ONE_LOGIN = "test-user-one"; + private static final String USER_ONE_EMAIL = "test-user-one@localhost"; + private static final String USER_TWO_LOGIN = "test-user-two"; + private static final String USER_TWO_EMAIL = "test-user-two@localhost"; + private static final String USER_THREE_LOGIN = "test-user-three"; + private static final String USER_THREE_EMAIL = "test-user-three@localhost"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserDetailsService domainUserDetailsService; + + @BeforeEach + public void init() { + User userOne = new User(); + userOne.setLogin(USER_ONE_LOGIN); + userOne.setPassword(RandomStringUtils.random(60)); + userOne.setActivated(true); + userOne.setEmail(USER_ONE_EMAIL); + userOne.setFirstName("userOne"); + userOne.setLastName("doe"); + userOne.setLangKey("en"); + userRepository.save(userOne); + + User userTwo = new User(); + userTwo.setLogin(USER_TWO_LOGIN); + userTwo.setPassword(RandomStringUtils.random(60)); + userTwo.setActivated(true); + userTwo.setEmail(USER_TWO_EMAIL); + userTwo.setFirstName("userTwo"); + userTwo.setLastName("doe"); + userTwo.setLangKey("en"); + userRepository.save(userTwo); + + User userThree = new User(); + userThree.setLogin(USER_THREE_LOGIN); + userThree.setPassword(RandomStringUtils.random(60)); + userThree.setActivated(false); + userThree.setEmail(USER_THREE_EMAIL); + userThree.setFirstName("userThree"); + userThree.setLastName("doe"); + userThree.setLangKey("en"); + userRepository.save(userThree); + } + + @Test + public void assertThatUserCanBeFoundByLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + public void assertThatUserCanBeFoundByLoginIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + public void assertThatUserCanBeFoundByEmail() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test + public void assertThatUserCanBeFoundByEmailIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test + public void assertThatEmailIsPrioritizedOverLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { + assertThatExceptionOfType(UserNotActivatedException.class) + .isThrownBy(() -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)); + } } diff --git a/src/test/java/com/ippon/pouet/security/SecurityUtilsUnitTest.java b/src/test/java/com/ippon/pouet/security/SecurityUtilsUnitTest.java index f12efe7592696249c60595ed270f78daed586cce..561467c264303fa46f31230e2883aea77392bfb7 100644 --- a/src/test/java/com/ippon/pouet/security/SecurityUtilsUnitTest.java +++ b/src/test/java/com/ippon/pouet/security/SecurityUtilsUnitTest.java @@ -1,5 +1,10 @@ package com.ippon.pouet.security; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -7,65 +12,58 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - /** * Test class for the {@link SecurityUtils} utility class. */ public class SecurityUtilsUnitTest { - @Test - public void testGetCurrentUserLogin() { - SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); - securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); - SecurityContextHolder.setContext(securityContext); - Optional<String> login = SecurityUtils.getCurrentUserLogin(); - assertThat(login).contains("admin"); - } - - @Test - public void testgetCurrentUserJWT() { - SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); - securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")); - SecurityContextHolder.setContext(securityContext); - Optional<String> jwt = SecurityUtils.getCurrentUserJWT(); - assertThat(jwt).contains("token"); - } + @Test + public void testGetCurrentUserLogin() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); + SecurityContextHolder.setContext(securityContext); + Optional<String> login = SecurityUtils.getCurrentUserLogin(); + assertThat(login).contains("admin"); + } - @Test - public void testIsAuthenticated() { - SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); - securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); - SecurityContextHolder.setContext(securityContext); - boolean isAuthenticated = SecurityUtils.isAuthenticated(); - assertThat(isAuthenticated).isTrue(); - } + @Test + public void testgetCurrentUserJWT() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")); + SecurityContextHolder.setContext(securityContext); + Optional<String> jwt = SecurityUtils.getCurrentUserJWT(); + assertThat(jwt).contains("token"); + } - @Test - public void testAnonymousIsNotAuthenticated() { - SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); - Collection<GrantedAuthority> authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); - securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); - SecurityContextHolder.setContext(securityContext); - boolean isAuthenticated = SecurityUtils.isAuthenticated(); - assertThat(isAuthenticated).isFalse(); - } + @Test + public void testIsAuthenticated() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); + SecurityContextHolder.setContext(securityContext); + boolean isAuthenticated = SecurityUtils.isAuthenticated(); + assertThat(isAuthenticated).isTrue(); + } - @Test - public void testIsCurrentUserInRole() { - SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); - Collection<GrantedAuthority> authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); - SecurityContextHolder.setContext(securityContext); + @Test + public void testAnonymousIsNotAuthenticated() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + Collection<GrantedAuthority> authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); + SecurityContextHolder.setContext(securityContext); + boolean isAuthenticated = SecurityUtils.isAuthenticated(); + assertThat(isAuthenticated).isFalse(); + } - assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); - assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); - } + @Test + public void testIsCurrentUserInRole() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + Collection<GrantedAuthority> authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); + SecurityContextHolder.setContext(securityContext); + assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); + assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); + } } diff --git a/src/test/java/com/ippon/pouet/security/jwt/JWTFilterTest.java b/src/test/java/com/ippon/pouet/security/jwt/JWTFilterTest.java index f558d1b8bebc61b116583e6a75e49c6d216e1680..766c2a543a47fb67e6c122d49e6902b645a623de 100644 --- a/src/test/java/com/ippon/pouet/security/jwt/JWTFilterTest.java +++ b/src/test/java/com/ippon/pouet/security/jwt/JWTFilterTest.java @@ -1,10 +1,12 @@ package com.ippon.pouet.security.jwt; +import static org.assertj.core.api.Assertions.assertThat; + import com.ippon.pouet.security.AuthoritiesConstants; import io.github.jhipster.config.JHipsterProperties; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; - +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; @@ -16,100 +18,98 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.util.ReflectionTestUtils; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; - public class JWTFilterTest { + private TokenProvider tokenProvider; - private TokenProvider tokenProvider; - - private JWTFilter jwtFilter; - - @BeforeEach - public void setup() { - JHipsterProperties jHipsterProperties = new JHipsterProperties(); - tokenProvider = new TokenProvider(jHipsterProperties); - ReflectionTestUtils.setField(tokenProvider, "key", - Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); + private JWTFilter jwtFilter; - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); - jwtFilter = new JWTFilter(tokenProvider); - SecurityContextHolder.getContext().setAuthentication(null); - } + @BeforeEach + public void setup() { + JHipsterProperties jHipsterProperties = new JHipsterProperties(); + tokenProvider = new TokenProvider(jHipsterProperties); + ReflectionTestUtils.setField( + tokenProvider, + "key", + Keys.hmacShaKeyFor( + Decoders.BASE64.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8") + ) + ); - @Test - public void testJWTFilter() throws Exception { - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); - String jwt = tokenProvider.createToken(authentication, false); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); - assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); - } + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); + jwtFilter = new JWTFilter(tokenProvider); + SecurityContextHolder.getContext().setAuthentication(null); + } - @Test - public void testJWTFilterInvalidToken() throws Exception { - String jwt = "wrong_jwt"; - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } + @Test + public void testJWTFilter() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); + } - @Test - public void testJWTFilterMissingAuthorization() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } + @Test + public void testJWTFilterInvalidToken() throws Exception { + String jwt = "wrong_jwt"; + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } - @Test - public void testJWTFilterMissingToken() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } + @Test + public void testJWTFilterMissingAuthorization() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } - @Test - public void testJWTFilterWrongScheme() throws Exception { - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); - String jwt = tokenProvider.createToken(authentication, false); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } + @Test + public void testJWTFilterMissingToken() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + @Test + public void testJWTFilterWrongScheme() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } } diff --git a/src/test/java/com/ippon/pouet/security/jwt/TokenProviderTest.java b/src/test/java/com/ippon/pouet/security/jwt/TokenProviderTest.java index 07a9cb1a21c4b786a416035ef49d1aa154544148..7c0b39c4c41c12646507884991f425ad3be335d2 100644 --- a/src/test/java/com/ippon/pouet/security/jwt/TokenProviderTest.java +++ b/src/test/java/com/ippon/pouet/security/jwt/TokenProviderTest.java @@ -1,10 +1,15 @@ package com.ippon.pouet.security.jwt; -import com.ippon.pouet.security.AuthoritiesConstants; +import static org.assertj.core.api.Assertions.assertThat; +import com.ippon.pouet.security.AuthoritiesConstants; +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; import java.security.Key; import java.util.*; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -13,97 +18,89 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.util.ReflectionTestUtils; -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - -import static org.assertj.core.api.Assertions.assertThat; - public class TokenProviderTest { - - private static final long ONE_MINUTE = 60000; - - private Key key; - private TokenProvider tokenProvider; - - @BeforeEach - public void setup() { - tokenProvider = new TokenProvider( new JHipsterProperties()); - key = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); - - ReflectionTestUtils.setField(tokenProvider, "key", key); - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); - } - - @Test - public void testReturnFalseWhenJWThasInvalidSignature() { - boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature()); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisMalformed() { - Authentication authentication = createAuthentication(); - String token = tokenProvider.createToken(authentication, false); - String invalidToken = token.substring(1); - boolean isTokenValid = tokenProvider.validateToken(invalidToken); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisExpired() { - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE); - - Authentication authentication = createAuthentication(); - String token = tokenProvider.createToken(authentication, false); - - boolean isTokenValid = tokenProvider.validateToken(token); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisUnsupported() { - String unsupportedToken = createUnsupportedToken(); - - boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisInvalid() { - boolean isTokenValid = tokenProvider.validateToken(""); - - assertThat(isTokenValid).isEqualTo(false); - } - - private Authentication createAuthentication() { - Collection<GrantedAuthority> authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); - return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities); - } - - private String createUnsupportedToken() { - return Jwts.builder() - .setPayload("payload") - .signWith(key, SignatureAlgorithm.HS512) - .compact(); - } - - private String createTokenWithDifferentSignature() { - Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); - - return Jwts.builder() - .setSubject("anonymous") - .signWith(otherKey, SignatureAlgorithm.HS512) - .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) - .compact(); - } + private static final long ONE_MINUTE = 60000; + + private Key key; + private TokenProvider tokenProvider; + + @BeforeEach + public void setup() { + tokenProvider = new TokenProvider(new JHipsterProperties()); + key = + Keys.hmacShaKeyFor( + Decoders.BASE64.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8") + ); + + ReflectionTestUtils.setField(tokenProvider, "key", key); + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); + } + + @Test + public void testReturnFalseWhenJWThasInvalidSignature() { + boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature()); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisMalformed() { + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + String invalidToken = token.substring(1); + boolean isTokenValid = tokenProvider.validateToken(invalidToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisExpired() { + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE); + + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + + boolean isTokenValid = tokenProvider.validateToken(token); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisUnsupported() { + String unsupportedToken = createUnsupportedToken(); + + boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisInvalid() { + boolean isTokenValid = tokenProvider.validateToken(""); + + assertThat(isTokenValid).isEqualTo(false); + } + + private Authentication createAuthentication() { + Collection<GrantedAuthority> authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities); + } + + private String createUnsupportedToken() { + return Jwts.builder().setPayload("payload").signWith(key, SignatureAlgorithm.HS512).compact(); + } + + private String createTokenWithDifferentSignature() { + Key otherKey = Keys.hmacShaKeyFor( + Decoders.BASE64.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8") + ); + + return Jwts + .builder() + .setSubject("anonymous") + .signWith(otherKey, SignatureAlgorithm.HS512) + .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) + .compact(); + } } diff --git a/src/test/java/com/ippon/pouet/service/AuditEventServiceIT.java b/src/test/java/com/ippon/pouet/service/AuditEventServiceIT.java index a9fe3bb3f2fea1cae39d2c4f3d8a07d359789a68..bd5e0b9c9da1d1365ca31c202c9790cde3ab849a 100644 --- a/src/test/java/com/ippon/pouet/service/AuditEventServiceIT.java +++ b/src/test/java/com/ippon/pouet/service/AuditEventServiceIT.java @@ -1,18 +1,18 @@ package com.ippon.pouet.service; +import static org.assertj.core.api.Assertions.assertThat; + +import com.ippon.pouet.PouetApp; import com.ippon.pouet.domain.PersistentAuditEvent; import com.ippon.pouet.repository.PersistenceAuditEventRepository; -import com.ippon.pouet.PouetApp; import io.github.jhipster.config.JHipsterProperties; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; - -import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link AuditEventService}. @@ -20,54 +20,56 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = PouetApp.class) @Transactional public class AuditEventServiceIT { - @Autowired - private AuditEventService auditEventService; + @Autowired + private AuditEventService auditEventService; - @Autowired - private PersistenceAuditEventRepository persistenceAuditEventRepository; + @Autowired + private PersistenceAuditEventRepository persistenceAuditEventRepository; - @Autowired - private JHipsterProperties jHipsterProperties; + @Autowired + private JHipsterProperties jHipsterProperties; - private PersistentAuditEvent auditEventOld; + private PersistentAuditEvent auditEventOld; - private PersistentAuditEvent auditEventWithinRetention; + private PersistentAuditEvent auditEventWithinRetention; - private PersistentAuditEvent auditEventNew; + private PersistentAuditEvent auditEventNew; - @BeforeEach - public void init() { - auditEventOld = new PersistentAuditEvent(); - auditEventOld.setAuditEventDate(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() + 1, ChronoUnit.DAYS)); - auditEventOld.setPrincipal("test-user-old"); - auditEventOld.setAuditEventType("test-type"); + @BeforeEach + public void init() { + auditEventOld = new PersistentAuditEvent(); + auditEventOld.setAuditEventDate(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() + 1, ChronoUnit.DAYS)); + auditEventOld.setPrincipal("test-user-old"); + auditEventOld.setAuditEventType("test-type"); - auditEventWithinRetention = new PersistentAuditEvent(); - auditEventWithinRetention.setAuditEventDate(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() - 1, ChronoUnit.DAYS)); - auditEventWithinRetention.setPrincipal("test-user-retention"); - auditEventWithinRetention.setAuditEventType("test-type"); + auditEventWithinRetention = new PersistentAuditEvent(); + auditEventWithinRetention.setAuditEventDate( + Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() - 1, ChronoUnit.DAYS) + ); + auditEventWithinRetention.setPrincipal("test-user-retention"); + auditEventWithinRetention.setAuditEventType("test-type"); - auditEventNew = new PersistentAuditEvent(); - auditEventNew.setAuditEventDate(Instant.now()); - auditEventNew.setPrincipal("test-user-new"); - auditEventNew.setAuditEventType("test-type"); - } + auditEventNew = new PersistentAuditEvent(); + auditEventNew.setAuditEventDate(Instant.now()); + auditEventNew.setPrincipal("test-user-new"); + auditEventNew.setAuditEventType("test-type"); + } - @Test - @Transactional - public void verifyOldAuditEventsAreDeleted() { - persistenceAuditEventRepository.deleteAll(); - persistenceAuditEventRepository.save(auditEventOld); - persistenceAuditEventRepository.save(auditEventWithinRetention); - persistenceAuditEventRepository.save(auditEventNew); + @Test + @Transactional + public void verifyOldAuditEventsAreDeleted() { + persistenceAuditEventRepository.deleteAll(); + persistenceAuditEventRepository.save(auditEventOld); + persistenceAuditEventRepository.save(auditEventWithinRetention); + persistenceAuditEventRepository.save(auditEventNew); - persistenceAuditEventRepository.flush(); - auditEventService.removeOldAuditEvents(); - persistenceAuditEventRepository.flush(); + persistenceAuditEventRepository.flush(); + auditEventService.removeOldAuditEvents(); + persistenceAuditEventRepository.flush(); - assertThat(persistenceAuditEventRepository.findAll().size()).isEqualTo(2); - assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-old")).isEmpty(); - assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-retention")).isNotEmpty(); - assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-new")).isNotEmpty(); - } + assertThat(persistenceAuditEventRepository.findAll().size()).isEqualTo(2); + assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-old")).isEmpty(); + assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-retention")).isNotEmpty(); + assertThat(persistenceAuditEventRepository.findByPrincipal("test-user-new")).isNotEmpty(); + } } diff --git a/src/test/java/com/ippon/pouet/service/MailServiceIT.java b/src/test/java/com/ippon/pouet/service/MailServiceIT.java index 0b7af76d0e2439419c19c1a8ce8a26d923c3e5a7..1201b7d97de96f871aed651f12ced288b1101854 100644 --- a/src/test/java/com/ippon/pouet/service/MailServiceIT.java +++ b/src/test/java/com/ippon/pouet/service/MailServiceIT.java @@ -1,10 +1,27 @@ package com.ippon.pouet.service; -import com.ippon.pouet.config.Constants; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; import com.ippon.pouet.PouetApp; +import com.ippon.pouet.config.Constants; import com.ippon.pouet.domain.User; import io.github.jhipster.config.JHipsterProperties; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.mail.Multipart; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -18,230 +35,211 @@ import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.thymeleaf.spring5.SpringTemplateEngine; -import javax.mail.Multipart; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - /** * Integration tests for {@link MailService}. */ @SpringBootTest(classes = PouetApp.class) public class MailServiceIT { - - private static final String[] languages = { - "fr", - "en" - // jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array - }; - private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})"); - private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})"); - - @Autowired - private JHipsterProperties jHipsterProperties; - - @Autowired - private MessageSource messageSource; - - @Autowired - private SpringTemplateEngine templateEngine; - - @Spy - private JavaMailSenderImpl javaMailSender; - - @Captor - private ArgumentCaptor<MimeMessage> messageCaptor; - - private MailService mailService; - - @BeforeEach - public void setup() { - MockitoAnnotations.initMocks(this); - doNothing().when(javaMailSender).send(any(MimeMessage.class)); - mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); - } - - @Test - public void testSendEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent()).isInstanceOf(String.class); - assertThat(message.getContent().toString()).isEqualTo("testContent"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); - } - - @Test - public void testSendHtmlEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent()).isInstanceOf(String.class); - assertThat(message.getContent().toString()).isEqualTo("testContent"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendMultipartEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - MimeMultipart mp = (MimeMultipart) message.getContent(); - MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - part.writeTo(aos); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent()).isInstanceOf(Multipart.class); - assertThat(aos.toString()).isEqualTo("\r\ntestContent"); - assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); - } - - @Test - public void testSendMultipartHtmlEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - MimeMultipart mp = (MimeMultipart) message.getContent(); - MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - part.writeTo(aos); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent()).isInstanceOf(Multipart.class); - assertThat(aos.toString()).isEqualTo("\r\ntestContent"); - assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendEmailFromTemplate() throws Exception { - User user = new User(); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - user.setLangKey("en"); - mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("test title"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendActivationEmail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendActivationEmail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testCreationEmail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendCreationEmail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendPasswordResetMail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendPasswordResetMail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + private static final String[] languages = { + "fr", + "en", + // jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array + }; + private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})"); + private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})"); + + @Autowired + private JHipsterProperties jHipsterProperties; + + @Autowired + private MessageSource messageSource; + + @Autowired + private SpringTemplateEngine templateEngine; + + @Spy + private JavaMailSenderImpl javaMailSender; + + @Captor + private ArgumentCaptor<MimeMessage> messageCaptor; + + private MailService mailService; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + doNothing().when(javaMailSender).send(any(MimeMessage.class)); + mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); + } + + @Test + public void testSendEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendMultipartEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendMultipartHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailFromTemplate() throws Exception { + User user = new User(); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + user.setLangKey("en"); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("test title"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendActivationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendActivationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testCreationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendCreationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendPasswordResetMail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendPasswordResetMail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailWithException() { + doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); + try { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + } catch (Exception e) { + fail("Exception shouldn't have been thrown"); } - - @Test - public void testSendEmailWithException() { - doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); - try { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); - } catch (Exception e) { - fail("Exception shouldn't have been thrown"); - } + } + + @Test + public void testSendLocalizedEmailForAllSupportedLanguages() throws Exception { + User user = new User(); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + for (String langKey : languages) { + user.setLangKey(langKey); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + + String propertyFilePath = "i18n/messages_" + getJavaLocale(langKey) + ".properties"; + URL resource = this.getClass().getClassLoader().getResource(propertyFilePath); + File file = new File(new URI(resource.getFile()).getPath()); + Properties properties = new Properties(); + properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); + + String emailTitle = (String) properties.get("email.test.title"); + assertThat(message.getSubject()).isEqualTo(emailTitle); + assertThat(message.getContent().toString()) + .isEqualToNormalizingNewlines("<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n"); } - - @Test - public void testSendLocalizedEmailForAllSupportedLanguages() throws Exception { - User user = new User(); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - for (String langKey : languages) { - user.setLangKey(langKey); - mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); - verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - - String propertyFilePath = "i18n/messages_" + getJavaLocale(langKey) + ".properties"; - URL resource = this.getClass().getClassLoader().getResource(propertyFilePath); - File file = new File(new URI(resource.getFile()).getPath()); - Properties properties = new Properties(); - properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); - - String emailTitle = (String) properties.get("email.test.title"); - assertThat(message.getSubject()).isEqualTo(emailTitle); - assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n"); - } + } + + /** + * Convert a lang key to the Java locale. + */ + private String getJavaLocale(String langKey) { + String javaLangKey = langKey; + Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey); + if (matcher2.matches()) { + javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase(); } - - /** - * Convert a lang key to the Java locale. - */ - private String getJavaLocale(String langKey) { - String javaLangKey = langKey; - Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey); - if (matcher2.matches()) { - javaLangKey = matcher2.group(1) + "_"+ matcher2.group(2).toUpperCase(); - } - Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey); - if (matcher3.matches()) { - javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase(); - } - return javaLangKey; + Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey); + if (matcher3.matches()) { + javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase(); } + return javaLangKey; + } } diff --git a/src/test/java/com/ippon/pouet/service/UserServiceIT.java b/src/test/java/com/ippon/pouet/service/UserServiceIT.java index 7ce713bf75f5f3cace307831737bb4434a390bb3..2e3b2836e8c929e2c6178f173885c143d1266bfd 100644 --- a/src/test/java/com/ippon/pouet/service/UserServiceIT.java +++ b/src/test/java/com/ippon/pouet/service/UserServiceIT.java @@ -1,13 +1,19 @@ package com.ippon.pouet.service; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.config.Constants; import com.ippon.pouet.domain.User; import com.ippon.pouet.repository.UserRepository; import com.ippon.pouet.service.dto.UserDTO; - import io.github.jhipster.security.RandomUtil; - +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Optional; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,185 +26,172 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - /** * Integration tests for {@link UserService}. */ @SpringBootTest(classes = PouetApp.class) @Transactional public class UserServiceIT { - - private static final String DEFAULT_LOGIN = "johndoe"; - - private static final String DEFAULT_EMAIL = "johndoe@localhost"; - - private static final String DEFAULT_FIRSTNAME = "john"; - - private static final String DEFAULT_LASTNAME = "doe"; - - private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; - - private static final String DEFAULT_LANGKEY = "dummy"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserService userService; - - @Autowired - private AuditingHandler auditingHandler; - - @Mock - private DateTimeProvider dateTimeProvider; - - private User user; - - @BeforeEach - public void init() { - user = new User(); - user.setLogin(DEFAULT_LOGIN); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail(DEFAULT_EMAIL); - user.setFirstName(DEFAULT_FIRSTNAME); - user.setLastName(DEFAULT_LASTNAME); - user.setImageUrl(DEFAULT_IMAGEURL); - user.setLangKey(DEFAULT_LANGKEY); - - when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); - auditingHandler.setDateTimeProvider(dateTimeProvider); + private static final String DEFAULT_LOGIN = "johndoe"; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + + private static final String DEFAULT_LASTNAME = "doe"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + + private static final String DEFAULT_LANGKEY = "dummy"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private AuditingHandler auditingHandler; + + @Mock + private DateTimeProvider dateTimeProvider; + + private User user; + + @BeforeEach + public void init() { + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail(DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + + when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); + auditingHandler.setDateTimeProvider(dateTimeProvider); + } + + @Test + @Transactional + public void assertThatUserMustExistToResetPassword() { + userRepository.saveAndFlush(user); + Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost"); + assertThat(maybeUser).isNotPresent(); + + maybeUser = userService.requestPasswordReset(user.getEmail()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); + assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); + } + + @Test + @Transactional + public void assertThatOnlyActivatedUserCanRequestPasswordReset() { + user.setActivated(false); + userRepository.saveAndFlush(user); + + Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustNotBeOlderThan24Hours() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustBeValid() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey("1234"); + userRepository.saveAndFlush(user); + + Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatUserCanResetPassword() { + String oldPassword = user.getPassword(); + Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getResetDate()).isNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNull(); + assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); + + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + user.setActivationKey(RandomStringUtils.random(20)); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); + List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isNotEmpty(); + userService.removeNotActivatedUsers(); + users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isEmpty(); + } + + @Test + @Transactional + public void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); + List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isEmpty(); + userService.removeNotActivatedUsers(); + Optional<User> maybeDbUser = userRepository.findById(dbUser.getId()); + assertThat(maybeDbUser).contains(dbUser); + } + + @Test + @Transactional + public void assertThatAnonymousUserIsNotGet() { + user.setLogin(Constants.ANONYMOUS_USER); + if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { + userRepository.saveAndFlush(user); } - - @Test - @Transactional - public void assertThatUserMustExistToResetPassword() { - userRepository.saveAndFlush(user); - Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost"); - assertThat(maybeUser).isNotPresent(); - - maybeUser = userService.requestPasswordReset(user.getEmail()); - assertThat(maybeUser).isPresent(); - assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); - assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); - assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); - } - - @Test - @Transactional - public void assertThatOnlyActivatedUserCanRequestPasswordReset() { - user.setActivated(false); - userRepository.saveAndFlush(user); - - Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatResetKeyMustNotBeOlderThan24Hours() { - Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - userRepository.saveAndFlush(user); - - Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatResetKeyMustBeValid() { - Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey("1234"); - userRepository.saveAndFlush(user); - - Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatUserCanResetPassword() { - String oldPassword = user.getPassword(); - Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - userRepository.saveAndFlush(user); - - Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isPresent(); - assertThat(maybeUser.orElse(null).getResetDate()).isNull(); - assertThat(maybeUser.orElse(null).getResetKey()).isNull(); - assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); - - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() { - Instant now = Instant.now(); - when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); - user.setActivated(false); - user.setActivationKey(RandomStringUtils.random(20)); - User dbUser = userRepository.saveAndFlush(user); - dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); - userRepository.saveAndFlush(user); - Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); - List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); - assertThat(users).isNotEmpty(); - userService.removeNotActivatedUsers(); - users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); - assertThat(users).isEmpty(); - } - - @Test - @Transactional - public void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() { - Instant now = Instant.now(); - when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); - user.setActivated(false); - User dbUser = userRepository.saveAndFlush(user); - dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); - userRepository.saveAndFlush(user); - Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); - List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); - assertThat(users).isEmpty(); - userService.removeNotActivatedUsers(); - Optional<User> maybeDbUser = userRepository.findById(dbUser.getId()); - assertThat(maybeDbUser).contains(dbUser); - } - - @Test - @Transactional - public void assertThatAnonymousUserIsNotGet() { - user.setLogin(Constants.ANONYMOUS_USER); - if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { - userRepository.saveAndFlush(user); - } - final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); - final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable); - assertThat(allManagedUsers.getContent().stream() - .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) - .isTrue(); - } - + final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); + final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable); + assertThat(allManagedUsers.getContent().stream().noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))).isTrue(); + } } diff --git a/src/test/java/com/ippon/pouet/service/mapper/UserMapperTest.java b/src/test/java/com/ippon/pouet/service/mapper/UserMapperTest.java index c0838a19c0937377ecc0337380033459b5d96261..a298e02bd7cf6e5d455590f2fbdb38bda849d401 100644 --- a/src/test/java/com/ippon/pouet/service/mapper/UserMapperTest.java +++ b/src/test/java/com/ippon/pouet/service/mapper/UserMapperTest.java @@ -1,136 +1,134 @@ package com.ippon.pouet.service.mapper; +import static org.assertj.core.api.Assertions.assertThat; + import com.ippon.pouet.domain.User; import com.ippon.pouet.service.dto.UserDTO; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests for {@link UserMapper}. */ public class UserMapperTest { - - private static final String DEFAULT_LOGIN = "johndoe"; - private static final Long DEFAULT_ID = 1L; - - private UserMapper userMapper; - private User user; - private UserDTO userDto; - - @BeforeEach - public void init() { - userMapper = new UserMapper(); - user = new User(); - user.setLogin(DEFAULT_LOGIN); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail("johndoe@localhost"); - user.setFirstName("john"); - user.setLastName("doe"); - user.setImageUrl("image_url"); - user.setLangKey("en"); - - userDto = new UserDTO(user); - } - - @Test - public void usersToUserDTOsShouldMapOnlyNonNullUsers() { - List<User> users = new ArrayList<>(); - users.add(user); - users.add(null); - - List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users); - - assertThat(userDTOS).isNotEmpty(); - assertThat(userDTOS).size().isEqualTo(1); - } - - @Test - public void userDTOsToUsersShouldMapOnlyNonNullUsers() { - List<UserDTO> usersDto = new ArrayList<>(); - usersDto.add(userDto); - usersDto.add(null); - - List<User> users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - } - - @Test - public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() { - Set<String> authoritiesAsString = new HashSet<>(); - authoritiesAsString.add("ADMIN"); - userDto.setAuthorities(authoritiesAsString); - - List<UserDTO> usersDto = new ArrayList<>(); - usersDto.add(userDto); - - List<User> users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - assertThat(users.get(0).getAuthorities()).isNotNull(); - assertThat(users.get(0).getAuthorities()).isNotEmpty(); - assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); - } - - @Test - public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { - userDto.setAuthorities(null); - - List<UserDTO> usersDto = new ArrayList<>(); - usersDto.add(userDto); - - List<User> users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - assertThat(users.get(0).getAuthorities()).isNotNull(); - assertThat(users.get(0).getAuthorities()).isEmpty(); - } - - @Test - public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { - Set<String> authoritiesAsString = new HashSet<>(); - authoritiesAsString.add("ADMIN"); - userDto.setAuthorities(authoritiesAsString); - - User user = userMapper.userDTOToUser(userDto); - - assertThat(user).isNotNull(); - assertThat(user.getAuthorities()).isNotNull(); - assertThat(user.getAuthorities()).isNotEmpty(); - assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); - } - - @Test - public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { - userDto.setAuthorities(null); - - User user = userMapper.userDTOToUser(userDto); - - assertThat(user).isNotNull(); - assertThat(user.getAuthorities()).isNotNull(); - assertThat(user.getAuthorities()).isEmpty(); - } - - @Test - public void userDTOToUserMapWithNullUserShouldReturnNull() { - assertThat(userMapper.userDTOToUser(null)).isNull(); - } - - @Test - public void testUserFromId() { - assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); - assertThat(userMapper.userFromId(null)).isNull(); - } + private static final String DEFAULT_LOGIN = "johndoe"; + private static final Long DEFAULT_ID = 1L; + + private UserMapper userMapper; + private User user; + private UserDTO userDto; + + @BeforeEach + public void init() { + userMapper = new UserMapper(); + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail("johndoe@localhost"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setImageUrl("image_url"); + user.setLangKey("en"); + + userDto = new UserDTO(user); + } + + @Test + public void usersToUserDTOsShouldMapOnlyNonNullUsers() { + List<User> users = new ArrayList<>(); + users.add(user); + users.add(null); + + List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users); + + assertThat(userDTOS).isNotEmpty(); + assertThat(userDTOS).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersShouldMapOnlyNonNullUsers() { + List<UserDTO> usersDto = new ArrayList<>(); + usersDto.add(userDto); + usersDto.add(null); + + List<User> users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() { + Set<String> authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + List<UserDTO> usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List<User> users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isNotEmpty(); + assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + List<UserDTO> usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List<User> users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { + Set<String> authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isNotEmpty(); + assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithNullUserShouldReturnNull() { + assertThat(userMapper.userDTOToUser(null)).isNull(); + } + + @Test + public void testUserFromId() { + assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); + assertThat(userMapper.userFromId(null)).isNull(); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/AccountResourceIT.java b/src/test/java/com/ippon/pouet/web/rest/AccountResourceIT.java index 5404e7a2fda799f4a1ecf64ea767ee132646ad0f..c3967667f7d69508b1f1ce28fb88a3cec0a321ec 100644 --- a/src/test/java/com/ippon/pouet/web/rest/AccountResourceIT.java +++ b/src/test/java/com/ippon/pouet/web/rest/AccountResourceIT.java @@ -1,5 +1,10 @@ package com.ippon.pouet.web.rest; +import static com.ippon.pouet.web.rest.AccountResourceIT.TEST_USER_LOGIN; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.config.Constants; import com.ippon.pouet.domain.User; @@ -11,6 +16,8 @@ import com.ippon.pouet.service.dto.PasswordChangeDTO; import com.ippon.pouet.service.dto.UserDTO; import com.ippon.pouet.web.rest.vm.KeyAndPasswordVM; import com.ippon.pouet.web.rest.vm.ManagedUserVM; +import java.time.Instant; +import java.util.*; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -22,14 +29,6 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static com.ippon.pouet.web.rest.AccountResourceIT.TEST_USER_LOGIN; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link AccountResource} REST controller. */ @@ -37,739 +36,718 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WithMockUser(value = TEST_USER_LOGIN) @SpringBootTest(classes = PouetApp.class) public class AccountResourceIT { - static final String TEST_USER_LOGIN = "test"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private AuthorityRepository authorityRepository; - - @Autowired - private UserService userService; - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - private MockMvc restAccountMockMvc; - - @Test - @WithUnauthenticatedMockUser - public void testNonAuthenticatedUser() throws Exception { - restAccountMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); - } - - @Test - public void testAuthenticatedUser() throws Exception { - restAccountMockMvc.perform(get("/api/authenticate") - .with(request -> { - request.setRemoteUser(TEST_USER_LOGIN); - return request; - }) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(TEST_USER_LOGIN)); - } - - @Test - public void testGetExistingAccount() throws Exception { - Set<String> authorities = new HashSet<>(); - authorities.add(AuthoritiesConstants.ADMIN); - - UserDTO user = new UserDTO(); - user.setLogin(TEST_USER_LOGIN); - user.setFirstName("john"); - user.setLastName("doe"); - user.setEmail("john.doe@jhipster.com"); - user.setImageUrl("http://placehold.it/50x50"); - user.setLangKey("en"); - user.setAuthorities(authorities); - userService.createUser(user); - - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.login").value(TEST_USER_LOGIN)) - .andExpect(jsonPath("$.firstName").value("john")) - .andExpect(jsonPath("$.lastName").value("doe")) - .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) - .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) - .andExpect(jsonPath("$.langKey").value("en")) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); - } - - @Test - public void testGetUnknownAccount() throws Exception { - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(status().isInternalServerError()); - } - - @Test - @Transactional - public void testRegisterValid() throws Exception { - ManagedUserVM validUser = new ManagedUserVM(); - validUser.setLogin("test-register-valid"); - validUser.setPassword("password"); - validUser.setFirstName("Alice"); - validUser.setLastName("Test"); - validUser.setEmail("test-register-valid@example.com"); - validUser.setImageUrl("http://placehold.it/50x50"); - validUser.setLangKey(Constants.DEFAULT_LANGUAGE); - validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); - - assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); - } - - @Test - @Transactional - public void testRegisterInvalidLogin() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("funky-log(n");// <-- invalid - invalidUser.setPassword("password"); - invalidUser.setFirstName("Funky"); - invalidUser.setLastName("One"); - invalidUser.setEmail("funky@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterInvalidEmail() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword("password"); - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("invalid");// <-- invalid - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional<User> user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterInvalidPassword() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword("123");// password with only 3 digits - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("bob@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional<User> user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterNullPassword() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword(null);// invalid null password - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("bob@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional<User> user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterDuplicateLogin() throws Exception { - // First registration - ManagedUserVM firstUser = new ManagedUserVM(); - firstUser.setLogin("alice"); - firstUser.setPassword("password"); - firstUser.setFirstName("Alice"); - firstUser.setLastName("Something"); - firstUser.setEmail("alice@example.com"); - firstUser.setImageUrl("http://placehold.it/50x50"); - firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); - firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Duplicate login, different email - ManagedUserVM secondUser = new ManagedUserVM(); - secondUser.setLogin(firstUser.getLogin()); - secondUser.setPassword(firstUser.getPassword()); - secondUser.setFirstName(firstUser.getFirstName()); - secondUser.setLastName(firstUser.getLastName()); - secondUser.setEmail("alice2@example.com"); - secondUser.setImageUrl(firstUser.getImageUrl()); - secondUser.setLangKey(firstUser.getLangKey()); - secondUser.setCreatedBy(firstUser.getCreatedBy()); - secondUser.setCreatedDate(firstUser.getCreatedDate()); - secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); - secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); - secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // First user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); - - // Second (non activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); - - Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); - assertThat(testUser.isPresent()).isTrue(); - testUser.get().setActivated(true); - userRepository.save(testUser.get()); - - // Second (already activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); - } - - @Test - @Transactional - public void testRegisterDuplicateEmail() throws Exception { - // First user - ManagedUserVM firstUser = new ManagedUserVM(); - firstUser.setLogin("test-register-duplicate-email"); - firstUser.setPassword("password"); - firstUser.setFirstName("Alice"); - firstUser.setLastName("Test"); - firstUser.setEmail("test-register-duplicate-email@example.com"); - firstUser.setImageUrl("http://placehold.it/50x50"); - firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); - firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Register first user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); - - Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); - assertThat(testUser1.isPresent()).isTrue(); - - // Duplicate email, different login - ManagedUserVM secondUser = new ManagedUserVM(); - secondUser.setLogin("test-register-duplicate-email-2"); - secondUser.setPassword(firstUser.getPassword()); - secondUser.setFirstName(firstUser.getFirstName()); - secondUser.setLastName(firstUser.getLastName()); - secondUser.setEmail(firstUser.getEmail()); - secondUser.setImageUrl(firstUser.getImageUrl()); - secondUser.setLangKey(firstUser.getLangKey()); - secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // Register second (non activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); - - Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); - assertThat(testUser2.isPresent()).isFalse(); - - Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); - assertThat(testUser3.isPresent()).isTrue(); - - // Duplicate email - with uppercase email address - ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); - userWithUpperCaseEmail.setId(firstUser.getId()); - userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); - userWithUpperCaseEmail.setPassword(firstUser.getPassword()); - userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); - userWithUpperCaseEmail.setLastName(firstUser.getLastName()); - userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); - userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); - userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); - userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // Register third (not activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) - .andExpect(status().isCreated()); - - Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); - assertThat(testUser4.isPresent()).isTrue(); - assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); - - testUser4.get().setActivated(true); - userService.updateUser((new UserDTO(testUser4.get()))); - - // Register 4th (already activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); - } - - @Test - @Transactional - public void testRegisterAdminIsIgnored() throws Exception { - ManagedUserVM validUser = new ManagedUserVM(); - validUser.setLogin("badguy"); - validUser.setPassword("password"); - validUser.setFirstName("Bad"); - validUser.setLastName("Guy"); - validUser.setEmail("badguy@example.com"); - validUser.setActivated(true); - validUser.setImageUrl("http://placehold.it/50x50"); - validUser.setLangKey(Constants.DEFAULT_LANGUAGE); - validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); - - Optional<User> userDup = userRepository.findOneWithAuthoritiesByLogin("badguy"); - assertThat(userDup.isPresent()).isTrue(); - assertThat(userDup.get().getAuthorities()).hasSize(1) - .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); - } - - @Test - @Transactional - public void testActivateAccount() throws Exception { - final String activationKey = "some activation key"; - User user = new User(); - user.setLogin("activate-account"); - user.setEmail("activate-account@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(false); - user.setActivationKey(activationKey); - - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)) - .andExpect(status().isOk()); - - user = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(user.getActivated()).isTrue(); - } - - @Test - @Transactional - public void testActivateAccountWithWrongKey() throws Exception { - restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")) - .andExpect(status().isInternalServerError()); - } - - @Test - @Transactional - @WithMockUser("save-account") - public void testSaveAccount() throws Exception { - User user = new User(); - user.setLogin("save-account"); - user.setEmail("save-account@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-account@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneWithAuthoritiesByLogin(user.getLogin()).orElse(null); - assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); - assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); - assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); - assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); - assertThat(updatedUser.getActivated()).isEqualTo(true); - assertThat(updatedUser.getAuthorities()).isEmpty(); - } - - @Test - @Transactional - @WithMockUser("save-invalid-email") - public void testSaveInvalidEmail() throws Exception { - User user = new User(); - user.setLogin("save-invalid-email"); - user.setEmail("save-invalid-email@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("invalid email"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); - - assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); - } - - @Test - @Transactional - @WithMockUser("save-existing-email") - public void testSaveExistingEmail() throws Exception { - User user = new User(); - user.setLogin("save-existing-email"); - user.setEmail("save-existing-email@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("save-existing-email2"); - anotherUser.setEmail("save-existing-email2@example.com"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - - userRepository.saveAndFlush(anotherUser); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-existing-email2@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); - assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); - } - - @Test - @Transactional - @WithMockUser("save-existing-email-and-login") - public void testSaveExistingEmailAndLogin() throws Exception { - User user = new User(); - user.setLogin("save-existing-email-and-login"); - user.setEmail("save-existing-email-and-login@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-existing-email-and-login@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); - assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); - } - - @Test - @Transactional - @WithMockUser("change-password-wrong-existing-password") - public void testChangePasswordWrongExistingPassword() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-wrong-existing-password"); - user.setEmail("change-password-wrong-existing-password@example.com"); - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))) -) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); - assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); - assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - @WithMockUser("change-password") - public void testChangePassword() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password"); - user.setEmail("change-password@example.com"); - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) -) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); - assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - @WithMockUser("change-password-too-small") - public void testChangePasswordTooSmall() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-too-small"); - user.setEmail("change-password-too-small@example.com"); - userRepository.saveAndFlush(user); - - String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); - - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) -) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - @WithMockUser("change-password-too-long") - public void testChangePasswordTooLong() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-too-long"); - user.setEmail("change-password-too-long@example.com"); - userRepository.saveAndFlush(user); - - String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); - - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) -) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - @WithMockUser("change-password-empty") - public void testChangePasswordEmpty() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-empty"); - user.setEmail("change-password-empty@example.com"); - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) -) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - public void testRequestPasswordReset() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setLogin("password-reset"); - user.setEmail("password-reset@example.com"); - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@example.com") -) - .andExpect(status().isOk()); - } - - @Test - @Transactional - public void testRequestPasswordResetUpperCaseEmail() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setLogin("password-reset-upper-case"); - user.setEmail("password-reset-upper-case@example.com"); - userRepository.saveAndFlush(user); - - restAccountMockMvc.perform(post("/api/account/reset-password/init") - .content("password-reset-upper-case@EXAMPLE.COM") -) - .andExpect(status().isOk()); - } - - @Test - public void testRequestPasswordResetWrongEmail() throws Exception { - restAccountMockMvc.perform( - post("/api/account/reset-password/init") - .content("password-reset-wrong-email@example.com")) - .andExpect(status().isOk()); - } - - @Test - @Transactional - public void testFinishPasswordReset() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setLogin("finish-password-reset"); - user.setEmail("finish-password-reset@example.com"); - user.setResetDate(Instant.now().plusSeconds(60)); - user.setResetKey("reset key"); - userRepository.saveAndFlush(user); - - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey(user.getResetKey()); - keyAndPassword.setNewPassword("new password"); - - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - public void testFinishPasswordResetTooSmall() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setLogin("finish-password-reset-too-small"); - user.setEmail("finish-password-reset-too-small@example.com"); - user.setResetDate(Instant.now().plusSeconds(60)); - user.setResetKey("reset key too small"); - userRepository.saveAndFlush(user); - - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey(user.getResetKey()); - keyAndPassword.setNewPassword("foo"); - - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); - } - - @Test - @Transactional - public void testFinishPasswordResetWrongKey() throws Exception { - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey("wrong reset key"); - keyAndPassword.setNewPassword("new password"); - - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isInternalServerError()); - } + static final String TEST_USER_LOGIN = "test"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private AuthorityRepository authorityRepository; + + @Autowired + private UserService userService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private MockMvc restAccountMockMvc; + + @Test + @WithUnauthenticatedMockUser + public void testNonAuthenticatedUser() throws Exception { + restAccountMockMvc + .perform(get("/api/authenticate").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + } + + @Test + public void testAuthenticatedUser() throws Exception { + restAccountMockMvc + .perform( + get("/api/authenticate") + .with( + request -> { + request.setRemoteUser(TEST_USER_LOGIN); + return request; + } + ) + .accept(MediaType.APPLICATION_JSON) + ) + .andExpect(status().isOk()) + .andExpect(content().string(TEST_USER_LOGIN)); + } + + @Test + public void testGetExistingAccount() throws Exception { + Set<String> authorities = new HashSet<>(); + authorities.add(AuthoritiesConstants.ADMIN); + + UserDTO user = new UserDTO(); + user.setLogin(TEST_USER_LOGIN); + user.setFirstName("john"); + user.setLastName("doe"); + user.setEmail("john.doe@jhipster.com"); + user.setImageUrl("http://placehold.it/50x50"); + user.setLangKey("en"); + user.setAuthorities(authorities); + userService.createUser(user); + + restAccountMockMvc + .perform(get("/api/account").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.login").value(TEST_USER_LOGIN)) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + } + + @Test + public void testGetUnknownAccount() throws Exception { + restAccountMockMvc.perform(get("/api/account").accept(MediaType.APPLICATION_PROBLEM_JSON)).andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + public void testRegisterValid() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("test-register-valid"); + validUser.setPassword("password"); + validUser.setFirstName("Alice"); + validUser.setLastName("Test"); + validUser.setEmail("test-register-valid@example.com"); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); + } + + @Test + @Transactional + public void testRegisterInvalidLogin() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("funky-log(n"); // <-- invalid + invalidUser.setPassword("password"); + invalidUser.setFirstName("Funky"); + invalidUser.setLastName("One"); + invalidUser.setEmail("funky@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidEmail() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("password"); + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("invalid"); // <-- invalid + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional<User> user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("123"); // password with only 3 digits + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional<User> user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterNullPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword(null); // invalid null password + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional<User> user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterDuplicateLogin() throws Exception { + // First registration + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("alice"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Something"); + firstUser.setEmail("alice@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Duplicate login, different email + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin(firstUser.getLogin()); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail("alice2@example.com"); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setCreatedBy(firstUser.getCreatedBy()); + secondUser.setCreatedDate(firstUser.getCreatedDate()); + secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); + secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // First user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + // Second (non activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); + assertThat(testUser.isPresent()).isTrue(); + testUser.get().setActivated(true); + userRepository.save(testUser.get()); + + // Second (already activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterDuplicateEmail() throws Exception { + // First user + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("test-register-duplicate-email"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Test"); + firstUser.setEmail("test-register-duplicate-email@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Register first user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser1.isPresent()).isTrue(); + + // Duplicate email, different login + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin("test-register-duplicate-email-2"); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail(firstUser.getEmail()); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register second (non activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser2.isPresent()).isFalse(); + + Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); + assertThat(testUser3.isPresent()).isTrue(); + + // Duplicate email - with uppercase email address + ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); + userWithUpperCaseEmail.setId(firstUser.getId()); + userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); + userWithUpperCaseEmail.setPassword(firstUser.getPassword()); + userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); + userWithUpperCaseEmail.setLastName(firstUser.getLastName()); + userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); + userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); + userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); + userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register third (not activated) user + restAccountMockMvc + .perform( + post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)) + ) + .andExpect(status().isCreated()); + + Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); + assertThat(testUser4.isPresent()).isTrue(); + assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); + + testUser4.get().setActivated(true); + userService.updateUser((new UserDTO(testUser4.get()))); + + // Register 4th (already activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterAdminIsIgnored() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("badguy"); + validUser.setPassword("password"); + validUser.setFirstName("Bad"); + validUser.setLastName("Guy"); + validUser.setEmail("badguy@example.com"); + validUser.setActivated(true); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + Optional<User> userDup = userRepository.findOneWithAuthoritiesByLogin("badguy"); + assertThat(userDup.isPresent()).isTrue(); + assertThat(userDup.get().getAuthorities()).hasSize(1).containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); + } + + @Test + @Transactional + public void testActivateAccount() throws Exception { + final String activationKey = "some activation key"; + User user = new User(); + user.setLogin("activate-account"); + user.setEmail("activate-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(false); + user.setActivationKey(activationKey); + + userRepository.saveAndFlush(user); + + restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)).andExpect(status().isOk()); + + user = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(user.getActivated()).isTrue(); + } + + @Test + @Transactional + public void testActivateAccountWithWrongKey() throws Exception { + restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")).andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + @WithMockUser("save-account") + public void testSaveAccount() throws Exception { + User user = new User(); + user.setLogin("save-account"); + user.setEmail("save-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-account@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneWithAuthoritiesByLogin(user.getLogin()).orElse(null); + assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); + assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); + assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); + assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); + assertThat(updatedUser.getActivated()).isEqualTo(true); + assertThat(updatedUser.getAuthorities()).isEmpty(); + } + + @Test + @Transactional + @WithMockUser("save-invalid-email") + public void testSaveInvalidEmail() throws Exception { + User user = new User(); + user.setLogin("save-invalid-email"); + user.setEmail("save-invalid-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("invalid email"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); + } + + @Test + @Transactional + @WithMockUser("save-existing-email") + public void testSaveExistingEmail() throws Exception { + User user = new User(); + user.setLogin("save-existing-email"); + user.setEmail("save-existing-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("save-existing-email2"); + anotherUser.setEmail("save-existing-email2@example.com"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + + userRepository.saveAndFlush(anotherUser); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email2@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); + } + + @Test + @Transactional + @WithMockUser("save-existing-email-and-login") + public void testSaveExistingEmailAndLogin() throws Exception { + User user = new User(); + user.setLogin("save-existing-email-and-login"); + user.setEmail("save-existing-email-and-login@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email-and-login@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); + } + + @Test + @Transactional + @WithMockUser("change-password-wrong-existing-password") + public void testChangePasswordWrongExistingPassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-wrong-existing-password"); + user.setEmail("change-password-wrong-existing-password@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1" + currentPassword, "new password"))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); + assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password") + public void testChangePassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password"); + user.setEmail("change-password@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) + ) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password-too-small") + public void testChangePasswordTooSmall() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-small"); + user.setEmail("change-password-too-small@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-too-long") + public void testChangePasswordTooLong() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-long"); + user.setEmail("change-password-too-long@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-empty") + public void testChangePasswordEmpty() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-empty"); + user.setEmail("change-password-empty@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + public void testRequestPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc.perform(post("/api/account/reset-password/init").content("password-reset@example.com")).andExpect(status().isOk()); + } + + @Test + @Transactional + public void testRequestPasswordResetUpperCaseEmail() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset-upper-case"); + user.setEmail("password-reset-upper-case@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset-upper-case@EXAMPLE.COM")) + .andExpect(status().isOk()); + } + + @Test + public void testRequestPasswordResetWrongEmail() throws Exception { + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset-wrong-email@example.com")) + .andExpect(status().isOk()); + } + + @Test + @Transactional + public void testFinishPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset"); + user.setEmail("finish-password-reset@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("new password"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + public void testFinishPasswordResetTooSmall() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset-too-small"); + user.setEmail("finish-password-reset-too-small@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key too small"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("foo"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); + } + + @Test + @Transactional + public void testFinishPasswordResetWrongKey() throws Exception { + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey("wrong reset key"); + keyAndPassword.setNewPassword("new password"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) + .andExpect(status().isInternalServerError()); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/AuditResourceIT.java b/src/test/java/com/ippon/pouet/web/rest/AuditResourceIT.java index b3847cea77b3b4e4007545b3e977f840bd11ab1a..4a9361c07b65db284c6e4f1a077ee2aff1ee4f5a 100644 --- a/src/test/java/com/ippon/pouet/web/rest/AuditResourceIT.java +++ b/src/test/java/com/ippon/pouet/web/rest/AuditResourceIT.java @@ -1,10 +1,15 @@ package com.ippon.pouet.web.rest; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.domain.PersistentAuditEvent; import com.ippon.pouet.repository.PersistenceAuditEventRepository; import com.ippon.pouet.security.AuthoritiesConstants; - +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -15,13 +20,6 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link AuditResource} REST controller. */ @@ -30,103 +28,105 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @SpringBootTest(classes = PouetApp.class) @Transactional public class AuditResourceIT { - - private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; - private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; - private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); - private static final long SECONDS_PER_DAY = 60 * 60 * 24; - - @Autowired - private PersistenceAuditEventRepository auditEventRepository; - - private PersistentAuditEvent auditEvent; - - @Autowired - private MockMvc restAuditMockMvc; - - @BeforeEach - public void initTest() { - auditEventRepository.deleteAll(); - auditEvent = new PersistentAuditEvent(); - auditEvent.setAuditEventType(SAMPLE_TYPE); - auditEvent.setPrincipal(SAMPLE_PRINCIPAL); - auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); - } - - @Test - public void getAllAudits() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Get all the audits - restAuditMockMvc.perform(get("/management/audits")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); - } - - @Test - public void getAudit() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); - } - - @Test - public void getAuditsByDate() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Generate dates for selecting audits by date, making sure the period will contain the audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - - // Get the audit - restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); - } - - @Test - public void getNonExistingAuditsByDate() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Generate dates for selecting audits by date, making sure the period will not contain the sample audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); - String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - - // Query audits but expect no results - restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(header().string("X-Total-Count", "0")); - } - - @Test - public void getNonExistingAudit() throws Exception { - // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); - } - - @Test - public void testPersistentAuditEventEquals() throws Exception { - TestUtil.equalsVerifier(PersistentAuditEvent.class); - PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); - auditEvent1.setId(1L); - PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); - auditEvent2.setId(auditEvent1.getId()); - assertThat(auditEvent1).isEqualTo(auditEvent2); - auditEvent2.setId(2L); - assertThat(auditEvent1).isNotEqualTo(auditEvent2); - auditEvent1.setId(null); - assertThat(auditEvent1).isNotEqualTo(auditEvent2); - } + private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; + private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; + private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); + private static final long SECONDS_PER_DAY = 60 * 60 * 24; + + @Autowired + private PersistenceAuditEventRepository auditEventRepository; + + private PersistentAuditEvent auditEvent; + + @Autowired + private MockMvc restAuditMockMvc; + + @BeforeEach + public void initTest() { + auditEventRepository.deleteAll(); + auditEvent = new PersistentAuditEvent(); + auditEvent.setAuditEventType(SAMPLE_TYPE); + auditEvent.setPrincipal(SAMPLE_PRINCIPAL); + auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); + } + + @Test + public void getAllAudits() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get all the audits + restAuditMockMvc + .perform(get("/management/audits")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getAudit() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get the audit + restAuditMockMvc + .perform(get("/management/audits/{id}", auditEvent.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); + } + + @Test + public void getAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will contain the audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Get the audit + restAuditMockMvc + .perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getNonExistingAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will not contain the sample audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2 * SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Query audits but expect no results + restAuditMockMvc + .perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(header().string("X-Total-Count", "0")); + } + + @Test + public void getNonExistingAudit() throws Exception { + // Get the audit + restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + public void testPersistentAuditEventEquals() throws Exception { + TestUtil.equalsVerifier(PersistentAuditEvent.class); + PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); + auditEvent1.setId(1L); + PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); + auditEvent2.setId(auditEvent1.getId()); + assertThat(auditEvent1).isEqualTo(auditEvent2); + auditEvent2.setId(2L); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + auditEvent1.setId(null); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/ClientForwardControllerTest.java b/src/test/java/com/ippon/pouet/web/rest/ClientForwardControllerTest.java index ccf35d9dab7ad3df56ecb5604c8eafe138446074..e8aeb64e26220006e92beb292d91ca950797fd9c 100644 --- a/src/test/java/com/ippon/pouet/web/rest/ClientForwardControllerTest.java +++ b/src/test/java/com/ippon/pouet/web/rest/ClientForwardControllerTest.java @@ -1,5 +1,10 @@ package com.ippon.pouet.web.rest; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; @@ -9,56 +14,44 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Unit tests for the {@link ClientForwardController} REST controller. */ public class ClientForwardControllerTest { - - private MockMvc restMockMvc; - - @BeforeEach - public void setup() { - ClientForwardController clientForwardController = new ClientForwardController(); - this.restMockMvc = MockMvcBuilders - .standaloneSetup(clientForwardController, new TestController()) - .build(); - } - - @Test - public void getBackendEndpoint() throws Exception { - restMockMvc.perform(get("/test")) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE)) - .andExpect(content().string("test")); - } - - @Test - public void getClientEndpoint() throws Exception { - ResultActions perform = restMockMvc.perform(get("/non-existant-mapping")); - perform - .andExpect(status().isOk()) - .andExpect(forwardedUrl("/")); - } - - @Test - public void getNestedClientEndpoint() throws Exception { - restMockMvc.perform(get("/admin/user-management")) - .andExpect(status().isOk()) - .andExpect(forwardedUrl("/")); - } - - - @RestController - public static class TestController { - - @RequestMapping(value = "/test") - public String test() { - return "test"; - } + private MockMvc restMockMvc; + + @BeforeEach + public void setup() { + ClientForwardController clientForwardController = new ClientForwardController(); + this.restMockMvc = MockMvcBuilders.standaloneSetup(clientForwardController, new TestController()).build(); + } + + @Test + public void getBackendEndpoint() throws Exception { + restMockMvc + .perform(get("/test")) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE)) + .andExpect(content().string("test")); + } + + @Test + public void getClientEndpoint() throws Exception { + ResultActions perform = restMockMvc.perform(get("/non-existant-mapping")); + perform.andExpect(status().isOk()).andExpect(forwardedUrl("/")); + } + + @Test + public void getNestedClientEndpoint() throws Exception { + restMockMvc.perform(get("/admin/user-management")).andExpect(status().isOk()).andExpect(forwardedUrl("/")); + } + + @RestController + public static class TestController { + + @RequestMapping(value = "/test") + public String test() { + return "test"; } + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/TestUtil.java b/src/test/java/com/ippon/pouet/web/rest/TestUtil.java index f1bdd35597e83d48bd528dad8c9adf0d611fb013..de24bccc13820fa1b95d4bcf8aa7483a209e6840 100644 --- a/src/test/java/com/ippon/pouet/web/rest/TestUtil.java +++ b/src/test/java/com/ippon/pouet/web/rest/TestUtil.java @@ -1,157 +1,151 @@ package com.ippon.pouet.web.rest; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; -import org.springframework.format.support.DefaultFormattingConversionService; -import org.springframework.format.support.FormattingConversionService; - import java.io.IOException; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; import java.util.List; - import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; - -import static org.assertj.core.api.Assertions.assertThat; +import org.hamcrest.Description; +import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; /** * Utility class for testing REST controllers. */ public final class TestUtil { - - private static final ObjectMapper mapper = createObjectMapper(); - - private static ObjectMapper createObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - mapper.registerModule(new JavaTimeModule()); - return mapper; + private static final ObjectMapper mapper = createObjectMapper(); + + private static ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + mapper.registerModule(new JavaTimeModule()); + return mapper; + } + + /** + * Convert an object to JSON byte array. + * + * @param object the object to convert. + * @return the JSON byte array. + * @throws IOException + */ + public static byte[] convertObjectToJsonBytes(Object object) throws IOException { + return mapper.writeValueAsBytes(object); + } + + /** + * Create a byte array with a specific size filled with specified data. + * + * @param size the size of the byte array. + * @param data the data to put in the byte array. + * @return the JSON byte array. + */ + public static byte[] createByteArray(int size, String data) { + byte[] byteArray = new byte[size]; + for (int i = 0; i < size; i++) { + byteArray[i] = Byte.parseByte(data, 2); } + return byteArray; + } - /** - * Convert an object to JSON byte array. - * - * @param object the object to convert. - * @return the JSON byte array. - * @throws IOException - */ - public static byte[] convertObjectToJsonBytes(Object object) throws IOException { - return mapper.writeValueAsBytes(object); - } + /** + * A matcher that tests that the examined string represents the same instant as the reference datetime. + */ + public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> { + private final ZonedDateTime date; - /** - * Create a byte array with a specific size filled with specified data. - * - * @param size the size of the byte array. - * @param data the data to put in the byte array. - * @return the JSON byte array. - */ - public static byte[] createByteArray(int size, String data) { - byte[] byteArray = new byte[size]; - for (int i = 0; i < size; i++) { - byteArray[i] = Byte.parseByte(data, 2); - } - return byteArray; + public ZonedDateTimeMatcher(ZonedDateTime date) { + this.date = date; } - /** - * A matcher that tests that the examined string represents the same instant as the reference datetime. - */ - public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> { - - private final ZonedDateTime date; - - public ZonedDateTimeMatcher(ZonedDateTime date) { - this.date = date; + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) { + try { + if (!date.isEqual(ZonedDateTime.parse(item))) { + mismatchDescription.appendText("was ").appendValue(item); + return false; } - - @Override - protected boolean matchesSafely(String item, Description mismatchDescription) { - try { - if (!date.isEqual(ZonedDateTime.parse(item))) { - mismatchDescription.appendText("was ").appendValue(item); - return false; - } - return true; - } catch (DateTimeParseException e) { - mismatchDescription.appendText("was ").appendValue(item) - .appendText(", which could not be parsed as a ZonedDateTime"); - return false; - } - - } - - @Override - public void describeTo(Description description) { - description.appendText("a String representing the same Instant as ").appendValue(date); - } - } - - /** - * Creates a matcher that matches when the examined string represents the same instant as the reference datetime. - * - * @param date the reference datetime against which the examined string is checked. - */ - public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) { - return new ZonedDateTimeMatcher(date); - } - - /** - * Verifies the equals/hashcode contract on the domain object. - */ - public static <T> void equalsVerifier(Class<T> clazz) throws Exception { - T domainObject1 = clazz.getConstructor().newInstance(); - assertThat(domainObject1.toString()).isNotNull(); - assertThat(domainObject1).isEqualTo(domainObject1); - assertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode()); - // Test with an instance of another class - Object testOtherObject = new Object(); - assertThat(domainObject1).isNotEqualTo(testOtherObject); - assertThat(domainObject1).isNotEqualTo(null); - // Test with an instance of the same class - T domainObject2 = clazz.getConstructor().newInstance(); - assertThat(domainObject1).isNotEqualTo(domainObject2); - // HashCodes are equals because the objects are not persisted yet - assertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode()); - } - - /** - * Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one. - * @return the {@link FormattingConversionService}. - */ - public static FormattingConversionService createFormattingConversionService() { - DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService (); - DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); - registrar.setUseIsoFormat(true); - registrar.registerFormatters(dfcs); - return dfcs; + return true; + } catch (DateTimeParseException e) { + mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime"); + return false; + } } - /** - * Makes a an executes a query to the EntityManager finding all stored objects. - * @param <T> The type of objects to be searched - * @param em The instance of the EntityManager - * @param clss The class type to be searched - * @return A list of all found objects - */ - public static <T> List<T> findAll(EntityManager em, Class<T> clss) { - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<T> cq = cb.createQuery(clss); - Root<T> rootEntry = cq.from(clss); - CriteriaQuery<T> all = cq.select(rootEntry); - TypedQuery<T> allQuery = em.createQuery(all); - return allQuery.getResultList(); + @Override + public void describeTo(Description description) { + description.appendText("a String representing the same Instant as ").appendValue(date); } - - private TestUtil() {} + } + + /** + * Creates a matcher that matches when the examined string represents the same instant as the reference datetime. + * + * @param date the reference datetime against which the examined string is checked. + */ + public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) { + return new ZonedDateTimeMatcher(date); + } + + /** + * Verifies the equals/hashcode contract on the domain object. + */ + public static <T> void equalsVerifier(Class<T> clazz) throws Exception { + T domainObject1 = clazz.getConstructor().newInstance(); + assertThat(domainObject1.toString()).isNotNull(); + assertThat(domainObject1).isEqualTo(domainObject1); + assertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode()); + // Test with an instance of another class + Object testOtherObject = new Object(); + assertThat(domainObject1).isNotEqualTo(testOtherObject); + assertThat(domainObject1).isNotEqualTo(null); + // Test with an instance of the same class + T domainObject2 = clazz.getConstructor().newInstance(); + assertThat(domainObject1).isNotEqualTo(domainObject2); + // HashCodes are equals because the objects are not persisted yet + assertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode()); + } + + /** + * Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one. + * @return the {@link FormattingConversionService}. + */ + public static FormattingConversionService createFormattingConversionService() { + DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService(); + DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); + registrar.setUseIsoFormat(true); + registrar.registerFormatters(dfcs); + return dfcs; + } + + /** + * Makes a an executes a query to the EntityManager finding all stored objects. + * @param <T> The type of objects to be searched + * @param em The instance of the EntityManager + * @param clss The class type to be searched + * @return A list of all found objects + */ + public static <T> List<T> findAll(EntityManager em, Class<T> clss) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery<T> cq = cb.createQuery(clss); + Root<T> rootEntry = cq.from(clss); + CriteriaQuery<T> all = cq.select(rootEntry); + TypedQuery<T> allQuery = em.createQuery(all); + return allQuery.getResultList(); + } + + private TestUtil() {} } diff --git a/src/test/java/com/ippon/pouet/web/rest/UserJWTControllerIT.java b/src/test/java/com/ippon/pouet/web/rest/UserJWTControllerIT.java index 26939b3dd93b8207f19c6cd5e7ff0b1919a6dba7..873c707fc4dfe444df6d53bc28b3d87d77052250 100644 --- a/src/test/java/com/ippon/pouet/web/rest/UserJWTControllerIT.java +++ b/src/test/java/com/ippon/pouet/web/rest/UserJWTControllerIT.java @@ -1,5 +1,14 @@ package com.ippon.pouet.web.rest; +import static org.hamcrest.Matchers.emptyString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.domain.User; import com.ippon.pouet.repository.UserRepository; @@ -13,90 +22,77 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.emptyString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; - /** * Integration tests for the {@link UserJWTController} REST controller. */ @AutoConfigureMockMvc @SpringBootTest(classes = PouetApp.class) public class UserJWTControllerIT { + @Autowired + private UserRepository userRepository; - @Autowired - private UserRepository userRepository; - - @Autowired - private PasswordEncoder passwordEncoder; + @Autowired + private PasswordEncoder passwordEncoder; - @Autowired - private MockMvc mockMvc; + @Autowired + private MockMvc mockMvc; - @Test - @Transactional - public void testAuthorize() throws Exception { - User user = new User(); - user.setLogin("user-jwt-controller"); - user.setEmail("user-jwt-controller@example.com"); - user.setActivated(true); - user.setPassword(passwordEncoder.encode("test")); + @Test + @Transactional + public void testAuthorize() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller"); + user.setEmail("user-jwt-controller@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); - userRepository.saveAndFlush(user); + userRepository.saveAndFlush(user); - LoginVM login = new LoginVM(); - login.setUsername("user-jwt-controller"); - login.setPassword("test"); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(is(emptyString())))); - } + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller"); + login.setPassword("test"); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); + } - @Test - @Transactional - public void testAuthorizeWithRememberMe() throws Exception { - User user = new User(); - user.setLogin("user-jwt-controller-remember-me"); - user.setEmail("user-jwt-controller-remember-me@example.com"); - user.setActivated(true); - user.setPassword(passwordEncoder.encode("test")); + @Test + @Transactional + public void testAuthorizeWithRememberMe() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller-remember-me"); + user.setEmail("user-jwt-controller-remember-me@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); - userRepository.saveAndFlush(user); + userRepository.saveAndFlush(user); - LoginVM login = new LoginVM(); - login.setUsername("user-jwt-controller-remember-me"); - login.setPassword("test"); - login.setRememberMe(true); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(is(emptyString())))); - } + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller-remember-me"); + login.setPassword("test"); + login.setRememberMe(true); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); + } - @Test - public void testAuthorizeFails() throws Exception { - LoginVM login = new LoginVM(); - login.setUsername("wrong-user"); - login.setPassword("wrong password"); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.id_token").doesNotExist()) - .andExpect(header().doesNotExist("Authorization")); - } + @Test + public void testAuthorizeFails() throws Exception { + LoginVM login = new LoginVM(); + login.setUsername("wrong-user"); + login.setPassword("wrong password"); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.id_token").doesNotExist()) + .andExpect(header().doesNotExist("Authorization")); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/UserResourceIT.java b/src/test/java/com/ippon/pouet/web/rest/UserResourceIT.java index 8f29f13e8416a7e1d59fcab97cf3cd9874d42577..ee76dc490c63cb7e80ee105250cfca57b1c1e082 100644 --- a/src/test/java/com/ippon/pouet/web/rest/UserResourceIT.java +++ b/src/test/java/com/ippon/pouet/web/rest/UserResourceIT.java @@ -1,5 +1,11 @@ package com.ippon.pouet.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import com.ippon.pouet.PouetApp; import com.ippon.pouet.domain.Authority; import com.ippon.pouet.domain.User; @@ -8,6 +14,10 @@ import com.ippon.pouet.security.AuthoritiesConstants; import com.ippon.pouet.service.dto.UserDTO; import com.ippon.pouet.service.mapper.UserMapper; import com.ippon.pouet.web.rest.vm.ManagedUserVM; +import java.time.Instant; +import java.util.*; +import java.util.function.Consumer; +import javax.persistence.EntityManager; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,17 +29,6 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import java.time.Instant; -import java.util.*; -import java.util.function.Consumer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link UserResource} REST controller. */ @@ -37,532 +36,527 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WithMockUser(authorities = AuthoritiesConstants.ADMIN) @SpringBootTest(classes = PouetApp.class) public class UserResourceIT { - - private static final String DEFAULT_LOGIN = "johndoe"; - private static final String UPDATED_LOGIN = "jhipster"; - - private static final Long DEFAULT_ID = 1L; - - private static final String DEFAULT_PASSWORD = "passjohndoe"; - private static final String UPDATED_PASSWORD = "passjhipster"; - - private static final String DEFAULT_EMAIL = "johndoe@localhost"; - private static final String UPDATED_EMAIL = "jhipster@localhost"; - - private static final String DEFAULT_FIRSTNAME = "john"; - private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; - - private static final String DEFAULT_LASTNAME = "doe"; - private static final String UPDATED_LASTNAME = "jhipsterLastName"; - - private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; - private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; - - private static final String DEFAULT_LANGKEY = "en"; - private static final String UPDATED_LANGKEY = "fr"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserMapper userMapper; - - @Autowired - private EntityManager em; - - @Autowired - private MockMvc restUserMockMvc; - - private User user; - - /** - * Create a User. - * - * This is a static method, as tests for other entities might also need it, - * if they test an entity which has a required relationship to the User entity. - */ - public static User createEntity(EntityManager em) { - User user = new User(); - user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); - user.setFirstName(DEFAULT_FIRSTNAME); - user.setLastName(DEFAULT_LASTNAME); - user.setImageUrl(DEFAULT_IMAGEURL); - user.setLangKey(DEFAULT_LANGKEY); - return user; - } - - @BeforeEach - public void initTest() { - user = createEntity(em); - user.setLogin(DEFAULT_LOGIN); - user.setEmail(DEFAULT_EMAIL); - } - - @Test - @Transactional - public void createUser() throws Exception { - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - // Create the User - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin(DEFAULT_LOGIN); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isCreated()); - - // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeCreate + 1); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - }); - } - - @Test - @Transactional - public void createUserWithExistingId() throws Exception { - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(1L); - managedUserVM.setLogin(DEFAULT_LOGIN); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // An entity with an existing ID cannot be created, so this API call must fail - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); - } - - @Test - @Transactional - public void createUserWithExistingLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail("anothermail@localhost"); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); - } - - @Test - @Transactional - public void createUserWithExistingEmail() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin("anotherlogin"); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); - } - - @Test - @Transactional - public void getAllUsers() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - // Get all the users - restUserMockMvc.perform(get("/api/users?sort=id,desc") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) - .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) - .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) - .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) - .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) - .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); - } - - @Test - @Transactional - public void getUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - // Get the user - restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.login").value(user.getLogin())) - .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) - .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) - .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) - .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) - .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); - - } - - @Test - @Transactional - public void getNonExistingUser() throws Exception { - restUserMockMvc.perform(get("/api/users/unknown")) - .andExpect(status().isNotFound()); - } - - @Test - @Transactional - public void updateUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeUpdate = userRepository.findAll().size(); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(updatedUser.getLogin()); - managedUserVM.setPassword(UPDATED_PASSWORD); - managedUserVM.setFirstName(UPDATED_FIRSTNAME); - managedUserVM.setLastName(UPDATED_LASTNAME); - managedUserVM.setEmail(UPDATED_EMAIL); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(UPDATED_IMAGEURL); - managedUserVM.setLangKey(UPDATED_LANGKEY); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); - - // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeUpdate); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - }); - } - - @Test - @Transactional - public void updateUserLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeUpdate = userRepository.findAll().size(); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(UPDATED_LOGIN); - managedUserVM.setPassword(UPDATED_PASSWORD); - managedUserVM.setFirstName(UPDATED_FIRSTNAME); - managedUserVM.setLastName(UPDATED_LASTNAME); - managedUserVM.setEmail(UPDATED_EMAIL); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(UPDATED_IMAGEURL); - managedUserVM.setLangKey(UPDATED_LANGKEY); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); - - // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeUpdate); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - }); - } - - @Test - @Transactional - public void updateUserExistingEmail() throws Exception { - // Initialize the database with 2 users - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("jhipster"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - anotherUser.setEmail("jhipster@localhost"); - anotherUser.setFirstName("java"); - anotherUser.setLastName("hipster"); - anotherUser.setImageUrl(""); - anotherUser.setLangKey("en"); - userRepository.saveAndFlush(anotherUser); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(updatedUser.getLogin()); - managedUserVM.setPassword(updatedUser.getPassword()); - managedUserVM.setFirstName(updatedUser.getFirstName()); - managedUserVM.setLastName(updatedUser.getLastName()); - managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(updatedUser.getImageUrl()); - managedUserVM.setLangKey(updatedUser.getLangKey()); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - } - - @Test - @Transactional - public void updateUserExistingLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("jhipster"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - anotherUser.setEmail("jhipster@localhost"); - anotherUser.setFirstName("java"); - anotherUser.setLastName("hipster"); - anotherUser.setImageUrl(""); - anotherUser.setLangKey("en"); - userRepository.saveAndFlush(anotherUser); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser - managedUserVM.setPassword(updatedUser.getPassword()); - managedUserVM.setFirstName(updatedUser.getFirstName()); - managedUserVM.setLastName(updatedUser.getLastName()); - managedUserVM.setEmail(updatedUser.getEmail()); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(updatedUser.getImageUrl()); - managedUserVM.setLangKey(updatedUser.getLangKey()); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - } - - @Test - @Transactional - public void deleteUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeDelete = userRepository.findAll().size(); - - // Delete the user - restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()); - - // Validate the database is empty - assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1)); - } - - @Test - @Transactional - public void getAllAuthorities() throws Exception { - restUserMockMvc.perform(get("/api/users/authorities") - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); - } - - @Test - public void testUserEquals() throws Exception { - TestUtil.equalsVerifier(User.class); - User user1 = new User(); - user1.setId(1L); - User user2 = new User(); - user2.setId(user1.getId()); - assertThat(user1).isEqualTo(user2); - user2.setId(2L); - assertThat(user1).isNotEqualTo(user2); - user1.setId(null); - assertThat(user1).isNotEqualTo(user2); - } - - @Test - public void testUserDTOtoUser() { - UserDTO userDTO = new UserDTO(); - userDTO.setId(DEFAULT_ID); - userDTO.setLogin(DEFAULT_LOGIN); - userDTO.setFirstName(DEFAULT_FIRSTNAME); - userDTO.setLastName(DEFAULT_LASTNAME); - userDTO.setEmail(DEFAULT_EMAIL); - userDTO.setActivated(true); - userDTO.setImageUrl(DEFAULT_IMAGEURL); - userDTO.setLangKey(DEFAULT_LANGKEY); - userDTO.setCreatedBy(DEFAULT_LOGIN); - userDTO.setLastModifiedBy(DEFAULT_LOGIN); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - User user = userMapper.userDTOToUser(userDTO); - assertThat(user.getId()).isEqualTo(DEFAULT_ID); - assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(user.getActivated()).isEqualTo(true); - assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - assertThat(user.getCreatedBy()).isNull(); - assertThat(user.getCreatedDate()).isNotNull(); - assertThat(user.getLastModifiedBy()).isNull(); - assertThat(user.getLastModifiedDate()).isNotNull(); - assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); - } - - @Test - public void testUserToUserDTO() { - user.setId(DEFAULT_ID); - user.setCreatedBy(DEFAULT_LOGIN); - user.setCreatedDate(Instant.now()); - user.setLastModifiedBy(DEFAULT_LOGIN); - user.setLastModifiedDate(Instant.now()); - Set<Authority> authorities = new HashSet<>(); - Authority authority = new Authority(); - authority.setName(AuthoritiesConstants.USER); - authorities.add(authority); - user.setAuthorities(authorities); - - UserDTO userDTO = userMapper.userToUserDTO(user); - - assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); - assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(userDTO.isActivated()).isEqualTo(true); - assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); - assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); - assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); - assertThat(userDTO.toString()).isNotNull(); - } - - @Test - public void testAuthorityEquals() { - Authority authorityA = new Authority(); - assertThat(authorityA).isEqualTo(authorityA); - assertThat(authorityA).isNotEqualTo(null); - assertThat(authorityA).isNotEqualTo(new Object()); - assertThat(authorityA.hashCode()).isEqualTo(0); - assertThat(authorityA.toString()).isNotNull(); - - Authority authorityB = new Authority(); - assertThat(authorityA).isEqualTo(authorityB); - - authorityB.setName(AuthoritiesConstants.ADMIN); - assertThat(authorityA).isNotEqualTo(authorityB); - - authorityA.setName(AuthoritiesConstants.USER); - assertThat(authorityA).isNotEqualTo(authorityB); - - authorityB.setName(AuthoritiesConstants.USER); - assertThat(authorityA).isEqualTo(authorityB); - assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); - } - - private void assertPersistedUsers(Consumer<List<User>> userAssertion) { - userAssertion.accept(userRepository.findAll()); - } + private static final String DEFAULT_LOGIN = "johndoe"; + private static final String UPDATED_LOGIN = "jhipster"; + + private static final Long DEFAULT_ID = 1L; + + private static final String DEFAULT_PASSWORD = "passjohndoe"; + private static final String UPDATED_PASSWORD = "passjhipster"; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + private static final String UPDATED_EMAIL = "jhipster@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; + + private static final String DEFAULT_LASTNAME = "doe"; + private static final String UPDATED_LASTNAME = "jhipsterLastName"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; + + private static final String DEFAULT_LANGKEY = "en"; + private static final String UPDATED_LANGKEY = "fr"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserMapper userMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restUserMockMvc; + + private User user; + + /** + * Create a User. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which has a required relationship to the User entity. + */ + public static User createEntity(EntityManager em) { + User user = new User(); + user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + return user; + } + + @BeforeEach + public void initTest() { + user = createEntity(em); + user.setLogin(DEFAULT_LOGIN); + user.setEmail(DEFAULT_EMAIL); + } + + @Test + @Transactional + public void createUser() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + // Create the User + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isCreated()); + + // Validate the User in the database + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeCreate + 1); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + } + ); + } + + @Test + @Transactional + public void createUserWithExistingId() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(1L); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + public void createUserWithExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN); // this login should already be used + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail("anothermail@localhost"); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + public void createUserWithExistingEmail() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin("anotherlogin"); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); // this email should already be used + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + public void getAllUsers() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get all the users + restUserMockMvc + .perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); + } + + @Test + @Transactional + public void getUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get the user + restUserMockMvc + .perform(get("/api/users/{login}", user.getLogin())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); + } + + @Test + @Transactional + public void getNonExistingUser() throws Exception { + restUserMockMvc.perform(get("/api/users/unknown")).andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + ); + } + + @Test + @Transactional + public void updateUserLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(UPDATED_LOGIN); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + ); + } + + @Test + @Transactional + public void updateUserExistingEmail() throws Exception { + // Initialize the database with 2 users + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail("jhipster@localhost"); // this email should already be used by anotherUser + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void updateUserExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin("jhipster"); // this login should already be used by anotherUser + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail(updatedUser.getEmail()); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void deleteUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeDelete = userRepository.findAll().size(); + + // Delete the user + restUserMockMvc + .perform(delete("/api/users/{login}", user.getLogin()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1)); + } + + @Test + @Transactional + public void getAllAuthorities() throws Exception { + restUserMockMvc + .perform(get("/api/users/authorities").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); + } + + @Test + public void testUserEquals() throws Exception { + TestUtil.equalsVerifier(User.class); + User user1 = new User(); + user1.setId(1L); + User user2 = new User(); + user2.setId(user1.getId()); + assertThat(user1).isEqualTo(user2); + user2.setId(2L); + assertThat(user1).isNotEqualTo(user2); + user1.setId(null); + assertThat(user1).isNotEqualTo(user2); + } + + @Test + public void testUserDTOtoUser() { + UserDTO userDTO = new UserDTO(); + userDTO.setId(DEFAULT_ID); + userDTO.setLogin(DEFAULT_LOGIN); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setCreatedBy(DEFAULT_LOGIN); + userDTO.setLastModifiedBy(DEFAULT_LOGIN); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + User user = userMapper.userDTOToUser(userDTO); + assertThat(user.getId()).isEqualTo(DEFAULT_ID); + assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(user.getActivated()).isEqualTo(true); + assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(user.getCreatedBy()).isNull(); + assertThat(user.getCreatedDate()).isNotNull(); + assertThat(user.getLastModifiedBy()).isNull(); + assertThat(user.getLastModifiedDate()).isNotNull(); + assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); + } + + @Test + public void testUserToUserDTO() { + user.setId(DEFAULT_ID); + user.setCreatedBy(DEFAULT_LOGIN); + user.setCreatedDate(Instant.now()); + user.setLastModifiedBy(DEFAULT_LOGIN); + user.setLastModifiedDate(Instant.now()); + Set<Authority> authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.USER); + authorities.add(authority); + user.setAuthorities(authorities); + + UserDTO userDTO = userMapper.userToUserDTO(user); + + assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); + assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(userDTO.isActivated()).isEqualTo(true); + assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); + assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); + assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); + assertThat(userDTO.toString()).isNotNull(); + } + + @Test + public void testAuthorityEquals() { + Authority authorityA = new Authority(); + assertThat(authorityA).isEqualTo(authorityA); + assertThat(authorityA).isNotEqualTo(null); + assertThat(authorityA).isNotEqualTo(new Object()); + assertThat(authorityA.hashCode()).isEqualTo(0); + assertThat(authorityA.toString()).isNotNull(); + + Authority authorityB = new Authority(); + assertThat(authorityA).isEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.ADMIN); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityA.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isEqualTo(authorityB); + assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); + } + + private void assertPersistedUsers(Consumer<List<User>> userAssertion) { + userAssertion.accept(userRepository.findAll()); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/WithUnauthenticatedMockUser.java b/src/test/java/com/ippon/pouet/web/rest/WithUnauthenticatedMockUser.java index ba73914c7bace8fee5f2dec03432c4f2d188c248..341ea32bbd4aba0d98c3afbb1d50df398d32abf4 100644 --- a/src/test/java/com/ippon/pouet/web/rest/WithUnauthenticatedMockUser.java +++ b/src/test/java/com/ippon/pouet/web/rest/WithUnauthenticatedMockUser.java @@ -1,24 +1,23 @@ package com.ippon.pouet.web.rest; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.test.context.support.WithSecurityContext; -import org.springframework.security.test.context.support.WithSecurityContextFactory; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithSecurityContext; +import org.springframework.security.test.context.support.WithSecurityContextFactory; -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class) public @interface WithUnauthenticatedMockUser { + class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> { - class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> { - @Override - public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { - return SecurityContextHolder.createEmptyContext(); - } + @Override + public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { + return SecurityContextHolder.createEmptyContext(); } + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorIT.java b/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorIT.java index 4e07611bccfda2f7b4a445ffbe7d037102f450ba..5ddd9f26857bb842c80789fe25b621687598b618 100644 --- a/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorIT.java +++ b/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorIT.java @@ -1,20 +1,20 @@ package com.ippon.pouet.web.rest.errors; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.ippon.pouet.PouetApp; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.test.context.support.WithMockUser; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Integration tests {@link ExceptionTranslator} controller advice. */ @@ -22,89 +22,96 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc @SpringBootTest(classes = PouetApp.class) public class ExceptionTranslatorIT { + @Autowired + private MockMvc mockMvc; - @Autowired - private MockMvc mockMvc; - - @Test - public void testConcurrencyFailure() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/concurrency-failure")) - .andExpect(status().isConflict()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); - } - - @Test - public void testMethodArgumentNotValid() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) - .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); - } + @Test + public void testConcurrencyFailure() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/concurrency-failure")) + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + } - @Test - public void testMissingServletRequestPartException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-part")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } + @Test + public void testMethodArgumentNotValid() throws Exception { + mockMvc + .perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); + } - @Test - public void testMissingServletRequestParameterException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } + @Test + public void testMissingServletRequestPartException() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-part")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } - @Test - public void testAccessDenied() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/access-denied")) - .andExpect(status().isForbidden()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.403")) - .andExpect(jsonPath("$.detail").value("test access denied!")); - } + @Test + public void testMissingServletRequestParameterException() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } - @Test - public void testUnauthorized() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/unauthorized")) - .andExpect(status().isUnauthorized()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.401")) - .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) - .andExpect(jsonPath("$.detail").value("test authentication failed!")); - } + @Test + public void testAccessDenied() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/access-denied")) + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); + } - @Test - public void testMethodNotSupported() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/access-denied")) - .andExpect(status().isMethodNotAllowed()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.405")) - .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); - } + @Test + public void testUnauthorized() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/unauthorized")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); + } - @Test - public void testExceptionWithResponseStatus() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/response-status")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")) - .andExpect(jsonPath("$.title").value("test response status")); - } + @Test + public void testMethodNotSupported() throws Exception { + mockMvc + .perform(post("/api/exception-translator-test/access-denied")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + } - @Test - public void testInternalServerError() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/internal-server-error")) - .andExpect(status().isInternalServerError()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.500")) - .andExpect(jsonPath("$.title").value("Internal Server Error")); - } + @Test + public void testExceptionWithResponseStatus() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/response-status")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); + } + @Test + public void testInternalServerError() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/internal-server-error")) + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); + } } diff --git a/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorTestController.java b/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorTestController.java index 520cebb632c870bc1a761588048ef23233efc0d3..ef025802bebaf5f777026d5c4163fa7bbbdee88d 100644 --- a/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorTestController.java +++ b/src/test/java/com/ippon/pouet/web/rest/errors/ExceptionTranslatorTestController.java @@ -1,72 +1,65 @@ package com.ippon.pouet.web.rest.errors; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - @RestController @RequestMapping("/api/exception-translator-test") public class ExceptionTranslatorTestController { - @GetMapping("/concurrency-failure") - public void concurrencyFailure() { - throw new ConcurrencyFailureException("test concurrency failure"); - } + @GetMapping("/concurrency-failure") + public void concurrencyFailure() { + throw new ConcurrencyFailureException("test concurrency failure"); + } - @PostMapping("/method-argument") - public void methodArgument(@Valid @RequestBody TestDTO testDTO) { - } + @PostMapping("/method-argument") + public void methodArgument(@Valid @RequestBody TestDTO testDTO) {} - @GetMapping("/missing-servlet-request-part") - public void missingServletRequestPartException(@RequestPart String part) { - } + @GetMapping("/missing-servlet-request-part") + public void missingServletRequestPartException(@RequestPart String part) {} - @GetMapping("/missing-servlet-request-parameter") - public void missingServletRequestParameterException(@RequestParam String param) { - } - - @GetMapping("/access-denied") - public void accessdenied() { - throw new AccessDeniedException("test access denied!"); - } + @GetMapping("/missing-servlet-request-parameter") + public void missingServletRequestParameterException(@RequestParam String param) {} - @GetMapping("/unauthorized") - public void unauthorized() { - throw new BadCredentialsException("test authentication failed!"); - } + @GetMapping("/access-denied") + public void accessdenied() { + throw new AccessDeniedException("test access denied!"); + } - @GetMapping("/response-status") - public void exceptionWithResponseStatus() { - throw new TestResponseStatusException(); - } - - @GetMapping("/internal-server-error") - public void internalServerError() { - throw new RuntimeException(); - } + @GetMapping("/unauthorized") + public void unauthorized() { + throw new BadCredentialsException("test authentication failed!"); + } - public static class TestDTO { + @GetMapping("/response-status") + public void exceptionWithResponseStatus() { + throw new TestResponseStatusException(); + } - @NotNull - private String test; + @GetMapping("/internal-server-error") + public void internalServerError() { + throw new RuntimeException(); + } - public String getTest() { - return test; - } + public static class TestDTO { + @NotNull + private String test; - public void setTest(String test) { - this.test = test; - } + public String getTest() { + return test; } - @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") - @SuppressWarnings("serial") - public static class TestResponseStatusException extends RuntimeException { + public void setTest(String test) { + this.test = test; } + } + @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") + @SuppressWarnings("serial") + public static class TestResponseStatusException extends RuntimeException {} }