diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8cdfa43 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.gradle +.idea +**/build +**/data +**/gradle +**/logs +.gitignore +.gitlab-ci.yml +docker-compose.yml +Dockerfile +gradlew** diff --git a/.drone.yml b/.drone.yml index b9e00cc..131882b 100644 --- a/.drone.yml +++ b/.drone.yml @@ -1,44 +1,86 @@ +--- +global-variables: + release: &release ${DRONE_BRANCH##**/} + environment: &environment + JAVA_VERSION: 11 + GRADLE_VERSION: 7.1 + CRE_VERSION: dev-${DRONE_BUILD_NUMBER} + CRE_ARTIFACT_NAME: ColorRecipesExplorer + CRE_REGISTRY_IMAGE: registry.fyloz.dev:5443/colorrecipesexplorer/backend + CRE_PORT: 9101 + CRE_RELEASE: *release + gradle-image: &gradle-image gradle:7.1-jdk11 + alpine-image: &alpine-image alpine:latest + docker-registry-repo: &docker-registry-repo registry.fyloz.dev:5443/colorrecipesexplorer/backend + kind: pipeline name: default type: docker -environment: - CRE_VERSION: ${DRONE_BUILD_NUMBER} - CRE_ARTIFACT_NAME: ColorRecipesExplorer - CRE_REGISTRY_IMAGE: registry.fyloz.dev:5443/colorrecipesexplorer/backend - CRE_PORT: 9101 - steps: - - name: test - image: gradle:7.1-jdk11 + - name: gradle-test + image: *gradle-image commands: - gradle test + when: + branch: develop - - name: build - image: gradle:7.1-jdk11 + - name: set-docker-tags-latest + image: *alpine-image + environment: + <<: *environment commands: - - gradle bootJar -Pversion=$CRE_VERSION - - mv build/libs/ColorRecipesExplorer-$CRE_VERSION.jar $CRE_ARTIFACT_NAME.jar - - echo -n "latest,$CRE_VERSION" > .tags + - echo -n "latest" > .tags when: - branch: - - master - events: [ push, tag ] + branch: develop + event: + exclude: + - pull_request - - name: containerize - image: plugins/docker - settings: - build_args: - - JAVA_VERSION=11 - repo: registry.fyloz.dev:5443/colorrecipesexplorer/backend + - name: set-docker-tags-release + image: *alpine-image + environment: + <<: *environment + commands: + - echo -n "latest-release,$CRE_RELEASE" > .tags when: - branch: - - master - events: [ push, tag ] + branch: release/** + + - name: containerize-dev + image: plugins/docker + environment: + <<: *environment + settings: + build_args_from_env: + - GRADLE_VERSION + - JAVA_VERSION + - CRE_VERSION + repo: *docker-registry-repo + when: + branch: develop + event: + exclude: + - pull_request + + - name: containerize-release + image: plugins/docker + environment: + <<: *environment + settings: + build_args_from_env: + - GRADLE_VERSION + - JAVA_VERSION + build_args: + - CRE_VERSION=${DRONE_BRANCH##**/} + repo: *docker-registry-repo + when: + branch: release/** - name: deploy image: alpine:latest environment: + <<: *environment + CRE_REGISTRY_IMAGE: *docker-registry-repo DEPLOY_SERVER: from_secret: deploy_server DEPLOY_SERVER_USERNAME: @@ -47,7 +89,7 @@ steps: from_secret: deploy_server_ssh_port DEPLOY_SERVER_SSH_KEY: from_secret: deploy_server_ssh_key - DEPLOY_CONTAINER_NAME: cre_backend-${DRONE_BRANCH} + DEPLOY_CONTAINER_NAME: cre_backend DEPLOY_SPRING_PROFILES: mysql,rest DEPLOY_DATA_VOLUME: /var/cre/data DEPLOY_CONFIG_VOLUME: /var/cre/config @@ -62,11 +104,15 @@ steps: - ssh-keyscan -p $DEPLOY_SERVER_SSH_PORT -H $DEPLOY_SERVER >> ~/.ssh/known_hosts - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker stop $DEPLOY_CONTAINER_NAME || true && docker rm $DEPLOY_CONTAINER_NAME || true" - - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:latest" - - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/cre/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/cre/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE" + - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:$CRE_RELEASE" + - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE:$CRE_RELEASE" when: - branch: - - master - events: [ push, tag ] + branch: release/** + +trigger: + branch: + - develop + - release/** + - master diff --git a/Dockerfile b/Dockerfile index 3f4a504..adf4abc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,21 @@ +ARG GRADLE_VERSION=7.1 ARG JAVA_VERSION=11 -FROM openjdk:$JAVA_VERSION +FROM gradle:$GRADLE_VERSION-jdk$JAVA_VERSION AS build +WORKDIR /usr/src +COPY . . -WORKDIR /usr/bin/cre/ +ARG CRE_VERSION=dev +RUN gradle bootJar -Pversion=$CRE_VERSION -ARG CRE_ARTIFACT_NAME=ColorRecipesExplorer -COPY $CRE_ARTIFACT_NAME.jar ColorRecipesExplorer.jar +FROM alpine:latest +WORKDIR /usr/bin + +ARG JAVA_VERSION +RUN apk add --no-cache openjdk$JAVA_VERSION + +ARG CRE_VERSION +COPY --from=build /usr/src/build/libs/ColorRecipesExplorer-$CRE_VERSION.jar ColorRecipesExplorer.jar ARG CRE_PORT=9090 EXPOSE $CRE_PORT @@ -16,7 +26,7 @@ ENV spring_datasource_url=jdbc:h2:mem:cre ENV spring_datasource_username=root ENV spring_datasource_password=pass -VOLUME /usr/bin/cre/data -VOLUME /usr/bin/cre/config +VOLUME /usr/bin/data +VOLUME /usr/bin/config ENTRYPOINT ["java", "-jar", "ColorRecipesExplorer.jar"] diff --git a/build.gradle.kts b/build.gradle.kts index 9912eaf..91aa6dd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,13 +2,13 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile group = "dev.fyloz.colorrecipesexplorer" -val kotlinVersion = "1.5.21" -val springBootVersion = "2.3.4.RELEASE" +val kotlinVersion = "1.6.0" +val springBootVersion = "2.5.6" plugins { // Outer scope variables can't be accessed in the plugins section, so we have to redefine them here - val kotlinVersion = "1.5.21" - val springBootVersion = "2.3.4.RELEASE" + val kotlinVersion = "1.6.0" + val springBootVersion = "2.5.6" id("java") id("org.jetbrains.kotlin.jvm") version kotlinVersion @@ -22,7 +22,7 @@ repositories { mavenCentral() maven { - url = uri("https://git.fyloz.dev/api/v4/projects/40/packages/maven") + url = uri("https://archiva.fyloz.dev/repository/internal") } } @@ -30,12 +30,16 @@ dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom:${kotlinVersion}")) implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}") implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.3") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.0") implementation("javax.xml.bind:jaxb-api:2.3.0") - implementation("io.jsonwebtoken:jjwt:0.9.1") + implementation("io.jsonwebtoken:jjwt-api:0.11.2") + implementation("io.jsonwebtoken:jjwt-impl:0.11.2") + implementation("io.jsonwebtoken:jjwt-jackson:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") - implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2") + implementation("org.apache.logging.log4j:log4j-api:2.16.0") + implementation("org.apache.logging.log4j:log4j-to-slf4j:2.16.0") + implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2.1") implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}") implementation("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}") @@ -45,11 +49,10 @@ dependencies { implementation("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}") implementation("org.springframework.boot:spring-boot-devtools:${springBootVersion}") - testImplementation("org.springframework:spring-test:5.1.6.RELEASE") + testImplementation("org.springframework:spring-test:5.3.13") testImplementation("org.mockito:mockito-inline:3.11.2") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") - testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.2") - testImplementation("io.mockk:mockk:1.10.6") + testImplementation("io.mockk:mockk:1.12.0") testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}") testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}") @@ -58,8 +61,6 @@ dependencies { runtimeOnly("mysql:mysql-connector-java:8.0.22") runtimeOnly("org.postgresql:postgresql:42.2.16") runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11") - - implementation("org.springframework.cloud:spring-cloud-starter:2.2.8.RELEASE") } springBoot { diff --git a/gradle.Dockerfile b/gradle.Dockerfile deleted file mode 100644 index 2538416..0000000 --- a/gradle.Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -ARG JDK_VERSION=11 -ARG GRADLE_VERSION=7.1 - -FROM gradle:$GRADLE_VERSION-jdk$JDK_VERSION -WORKDIR /usr/src/cre/ - -COPY build.gradle.kts build.gradle.kts -COPY settings.gradle.kts settings.gradle.kts -COPY src src - diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..7454180 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 69a9715..ffed3a2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..1b6c787 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt index a355f4b..5f020fb 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt @@ -3,23 +3,24 @@ package dev.fyloz.colorrecipesexplorer import dev.fyloz.colorrecipesexplorer.databasemanager.CreDatabase import dev.fyloz.colorrecipesexplorer.databasemanager.databaseContext import dev.fyloz.colorrecipesexplorer.databasemanager.databaseUpdaterProperties +import dev.fyloz.colorrecipesexplorer.model.Configuration import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import org.slf4j.Logger import org.springframework.boot.jdbc.DataSourceBuilder import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.DependsOn import org.springframework.context.annotation.Profile import org.springframework.core.env.ConfigurableEnvironment import javax.sql.DataSource +import org.springframework.context.annotation.Configuration as SpringConfiguration const val SUPPORTED_DATABASE_VERSION = 5 const val ENV_VAR_ENABLE_DATABASE_UPDATE_NAME = "CRE_ENABLE_DB_UPDATE" val DATABASE_NAME_REGEX = Regex("(\\w+)$") @Profile("!emergency") -@Configuration +@SpringConfiguration @DependsOn("configurationsInitializer", "configurationService") class DataSourceConfiguration { @Bean(name = ["dataSource"]) @@ -29,7 +30,8 @@ class DataSourceConfiguration { configurationService: ConfigurationService ): DataSource { fun getConfiguration(type: ConfigurationType) = - configurationService.get(type).content + if (type.secure) configurationService.getSecure(type) + else configurationService.getContent(type) val databaseUrl = "jdbc:" + getConfiguration(ConfigurationType.DATABASE_URL) val databaseUsername = getConfiguration(ConfigurationType.DATABASE_USER) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt new file mode 100644 index 0000000..b56a00d --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt @@ -0,0 +1,5 @@ +package dev.fyloz.colorrecipesexplorer + +typealias SpringUser = org.springframework.security.core.userdetails.User +typealias SpringUserDetails = org.springframework.security.core.userdetails.UserDetails +typealias SpringUserDetailsService = org.springframework.security.core.userdetails.UserDetailsService diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index bca86e3..d5b5023 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -3,32 +3,33 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toAuthorities +import dev.fyloz.colorrecipesexplorer.service.users.JwtService +import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService +import dev.fyloz.colorrecipesexplorer.utils.addCookie import io.jsonwebtoken.ExpiredJwtException -import io.jsonwebtoken.Jwts -import io.jsonwebtoken.SignatureAlgorithm import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder -import org.springframework.security.core.userdetails.User -import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.authentication.www.BasicAuthenticationFilter -import org.springframework.util.Assert import org.springframework.web.util.WebUtils -import java.util.* import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse const val authorizationCookieName = "Authorization" const val defaultGroupCookieName = "Default-Group" -val blacklistedJwtTokens = mutableListOf() +val blacklistedJwtTokens = mutableListOf() // Not working, move to a cache or something class JwtAuthenticationFilter( private val authManager: AuthenticationManager, - private val securityConfigurationProperties: CreSecurityProperties, + private val jwtService: JwtService, + private val securityProperties: CreSecurityProperties, private val updateUserLoginTime: (Long) -> Unit ) : UsernamePasswordAuthenticationFilter() { private var debugMode = false @@ -47,38 +48,28 @@ class JwtAuthenticationFilter( request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain, - authResult: Authentication + auth: Authentication ) { - val jwtSecret = securityConfigurationProperties.jwtSecret - val jwtDuration = securityConfigurationProperties.jwtDuration - Assert.notNull(jwtSecret, "No JWT secret has been defined.") - Assert.notNull(jwtDuration, "No JWT duration has been defined.") - val userId = (authResult.principal as User).username - updateUserLoginTime(userId.toLong()) - val expirationMs = System.currentTimeMillis() + jwtDuration - val expirationDate = Date(expirationMs) - val token = Jwts.builder() - .setSubject(userId) - .setExpiration(expirationDate) - .signWith(SignatureAlgorithm.HS512, jwtSecret.toByteArray()) - .compact() - response.addHeader("Access-Control-Expose-Headers", "X-Authentication-Expiration") - var bearerCookie = - "$authorizationCookieName=Bearer$token; Max-Age=${jwtDuration / 1000}; HttpOnly; SameSite=strict" - if (!debugMode) bearerCookie += "; Secure;" - response.addHeader( - "Set-Cookie", - bearerCookie - ) + val userDetails = auth.principal as UserDetails + val token = jwtService.buildJwt(userDetails) + + response.addHeader("Access-Control-Expose-Headers", authorizationCookieName) response.addHeader(authorizationCookieName, "Bearer $token") - response.addHeader("X-Authentication-Expiration", "$expirationMs") + response.addCookie(authorizationCookieName, "Bearer$token") { + httpOnly = true + sameSite = true + secure = !debugMode + maxAge = securityProperties.jwtDuration / 1000 + } + + updateUserLoginTime(userDetails.user.id) } } class JwtAuthorizationFilter( - private val securityConfigurationProperties: CreSecurityProperties, + private val jwtService: JwtService, authenticationManager: AuthenticationManager, - private val loadUserById: (Long) -> UserDetails + private val userDetailsService: UserDetailsService ) : BasicAuthenticationFilter(authenticationManager) { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) { fun tryLoginFromBearer(): Boolean { @@ -112,24 +103,24 @@ class JwtAuthorizationFilter( } private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { - val jwtSecret = securityConfigurationProperties.jwtSecret - Assert.notNull(jwtSecret, "No JWT secret has been defined.") return try { - val userId = Jwts.parser() - .setSigningKey(jwtSecret.toByteArray()) - .parseClaimsJws(token.replace("Bearer", "")) - .body - .subject - if (userId != null) getAuthenticationToken(userId) else null + val user = jwtService.parseJwt(token.replace("Bearer", "")) + getAuthenticationToken(user) } catch (_: ExpiredJwtException) { null } } - private fun getAuthenticationToken(userId: String): UsernamePasswordAuthenticationToken? = try { - val userDetails = loadUserById(userId.toLong()) + private fun getAuthenticationToken(user: UserOutputDto) = + UsernamePasswordAuthenticationToken(user.id, null, user.permissions.toAuthorities()) + + private fun getAuthenticationToken(userId: Long): UsernamePasswordAuthenticationToken? = try { + val userDetails = userDetailsService.loadUserById(userId) UsernamePasswordAuthenticationToken(userDetails.username, null, userDetails.authorities) } catch (_: NotFoundException) { null } + + private fun getAuthenticationToken(userId: String) = + getAuthenticationToken(userId.toLong()) } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 5440e61..ec68d49 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -4,11 +4,15 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.emergencyMode import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.User -import dev.fyloz.colorrecipesexplorer.service.CreUserDetailsService -import dev.fyloz.colorrecipesexplorer.service.UserService +import dev.fyloz.colorrecipesexplorer.service.users.JwtService +import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService +import dev.fyloz.colorrecipesexplorer.service.users.UserService import org.slf4j.Logger import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.* +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Lazy +import org.springframework.context.annotation.Profile import org.springframework.core.env.Environment import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder @@ -18,67 +22,52 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.AuthenticationException -import org.springframework.security.core.authority.SimpleGrantedAuthority -import org.springframework.security.core.userdetails.UserDetails -import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder -import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.stereotype.Component -import org.springframework.util.Assert import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.UrlBasedCorsConfigurationSource import javax.annotation.PostConstruct import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse -import org.springframework.security.core.userdetails.User as SpringUser -@Configuration -@Profile("!emergency") -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) -@EnableConfigurationProperties(CreSecurityProperties::class) -class SecurityConfig( - private val securityProperties: CreSecurityProperties, - @Lazy private val userDetailsService: CreUserDetailsService, - @Lazy private val userService: UserService, +private const val angularDevServerOrigin = "http://localhost:4200" +private const val rootUserFirstName = "Root" +private const val rootUserLastName = "User" + +abstract class BaseSecurityConfig( + private val userDetailsService: UserDetailsService, + private val jwtService: JwtService, private val environment: Environment, - private val logger: Logger + protected val logger: Logger, + protected val securityProperties: CreSecurityProperties ) : WebSecurityConfigurerAdapter() { + protected val passwordEncoder = BCryptPasswordEncoder() var debugMode = false - override fun configure(authBuilder: AuthenticationManagerBuilder) { - authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) - } + @Bean + open fun passwordEncoder() = + passwordEncoder @Bean - fun passwordEncoder() = - getPasswordEncoder() - - @Bean - fun corsConfigurationSource() = - getCorsConfigurationSource() - - @PostConstruct - fun initWebSecurity() { - if (emergencyMode) { - logger.error("Emergency mode is enabled, system users will not be created") - return + open fun corsConfigurationSource() = + UrlBasedCorsConfigurationSource().apply { + registerCorsConfiguration("/**", CorsConfiguration().apply { + allowedOrigins = listOf(angularDevServerOrigin) + allowedMethods = listOf( + HttpMethod.GET.name, + HttpMethod.POST.name, + HttpMethod.PUT.name, + HttpMethod.DELETE.name, + HttpMethod.OPTIONS.name, + HttpMethod.HEAD.name + ) + allowCredentials = true + }.applyPermitDefaultValues()) } - debugMode = "debug" in environment.activeProfiles - if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!") - - // Create Root user - assertRootUserNotNull(securityProperties) - createSystemUser( - securityProperties.root!!, - userService, - passwordEncoder(), - "Root", - "User", - listOf(Permission.ADMIN) - ) + override fun configure(authBuilder: AuthenticationManagerBuilder) { + authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder) } override fun configure(http: HttpSecurity) { @@ -87,29 +76,84 @@ class SecurityConfig( .and() .csrf().disable() .addFilter( - JwtAuthenticationFilter(authenticationManager(), securityProperties) { - userService.updateLastLoginTime(it) - } + JwtAuthenticationFilter( + authenticationManager(), + jwtService, + securityProperties, + this::updateUserLoginTime + ) ) .addFilter( - JwtAuthorizationFilter(securityProperties, authenticationManager()) { - userDetailsService.loadUserById(it, false) - } + JwtAuthorizationFilter(jwtService, authenticationManager(), userDetailsService) ) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers("/api/config/**").permitAll() // Allow access to logo and icon + .antMatchers("/api/login").permitAll() // Allow access to login + .antMatchers("**").fullyAuthenticated() - if (!debugMode) { - http.authorizeRequests() - .antMatchers("/api/login").permitAll() - .antMatchers("/api/logout").fullyAuthenticated() - .antMatchers("/api/user/current").fullyAuthenticated() - .anyRequest().fullyAuthenticated() - } else { + if (debugMode) { http .cors() - .and() - .authorizeRequests() - .antMatchers("**").permitAll() + } + } + + @PostConstruct + fun initDebugMode() { + debugMode = "debug" in environment.activeProfiles + if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!") + } + + protected open fun updateUserLoginTime(userId: Long) { + } +} + +@Configuration +@Profile("!emergency") +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableConfigurationProperties(CreSecurityProperties::class) +class SecurityConfig( + @Lazy userDetailsService: UserDetailsService, + @Lazy private val userService: UserService, + jwtService: JwtService, + environment: Environment, + logger: Logger, + securityProperties: CreSecurityProperties +) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) { + @PostConstruct + fun initWebSecurity() { + if (emergencyMode) { + logger.error("Emergency mode is enabled, system users will not be created") + return + } + + createRootUser() + } + + override fun updateUserLoginTime(userId: Long) { + userService.updateLastLoginTime(userId) + } + + private fun createRootUser() { + if (securityProperties.root == null) { + throw InvalidSystemUserException("root", "cre.security.root configuration is not defined") + } + + with(securityProperties.root!!) { + if (!userService.existsById(this.id)) { + userService.save( + User( + id = this.id, + firstName = rootUserFirstName, + lastName = rootUserLastName, + password = passwordEncoder.encode(this.password), + isSystemUser = true, + permissions = mutableSetOf(Permission.ADMIN) + ) + ) + } } } } @@ -118,67 +162,15 @@ class SecurityConfig( @Profile("emergency") @EnableConfigurationProperties(CreSecurityProperties::class) class EmergencySecurityConfig( - private val securityProperties: CreSecurityProperties, - private val environment: Environment -) : WebSecurityConfigurerAdapter() { - private val rootUserRole = Permission.ADMIN.name - + userDetailsService: UserDetailsService, + jwtService: JwtService, + environment: Environment, + logger: Logger, + securityProperties: CreSecurityProperties +) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) { init { emergencyMode = true } - - @Bean - fun corsConfigurationSource() = - getCorsConfigurationSource() - - @Bean - fun passwordEncoder() = - getPasswordEncoder() - - override fun configure(auth: AuthenticationManagerBuilder) { - assertRootUserNotNull(securityProperties) - // Create in-memory root user - auth.inMemoryAuthentication() - .withUser(securityProperties.root!!.id.toString()) - .password(passwordEncoder().encode(securityProperties.root!!.password)) - .authorities(SimpleGrantedAuthority(rootUserRole)) - } - - override fun configure(http: HttpSecurity) { - val debugMode = "debug" in environment.activeProfiles - - http - .headers().frameOptions().disable() - .and() - .csrf().disable() - .addFilter( - JwtAuthenticationFilter(authenticationManager(), securityProperties) { } - ) - .addFilter( - JwtAuthorizationFilter(securityProperties, authenticationManager(), this::loadUserById) - ) - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .authorizeRequests() - .antMatchers("**").fullyAuthenticated() - .antMatchers("/api/login").permitAll() - - if (debugMode) { - http.cors() - } - } - - private fun loadUserById(id: Long): UserDetails { - assertRootUserNotNull(securityProperties) - if (id == securityProperties.root!!.id) { - return SpringUser( - id.toString(), - securityProperties.root!!.password, - listOf(SimpleGrantedAuthority(rootUserRole)) - ) - } - throw UsernameNotFoundException(id.toString()) - } } @Component @@ -190,50 +182,5 @@ class RestAuthenticationEntryPoint : AuthenticationEntryPoint { ) = response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized") } -fun createSystemUser( - credentials: CreSecurityProperties.SystemUserCredentials, - userService: UserService, - passwordEncoder: PasswordEncoder, - firstName: String, - lastName: String, - permissions: List -) { - Assert.notNull(credentials.id, "A system user has no identifier defined") - Assert.notNull(credentials.password, "A system user has no password defined") - - if (!userService.existsById(credentials.id)) { - userService.save( - User( - id = credentials.id, - firstName = firstName, - lastName = lastName, - password = passwordEncoder.encode(credentials.password), - isSystemUser = true, - permissions = permissions.toMutableSet() - ) - ) - } -} - -fun getPasswordEncoder() = - BCryptPasswordEncoder() - -fun getCorsConfigurationSource() = - UrlBasedCorsConfigurationSource().apply { - registerCorsConfiguration("/**", CorsConfiguration().apply { - allowedOrigins = listOf("http://localhost:4200") // Angular development server - allowedMethods = listOf( - HttpMethod.GET.name, - HttpMethod.POST.name, - HttpMethod.PUT.name, - HttpMethod.DELETE.name, - HttpMethod.OPTIONS.name, - HttpMethod.HEAD.name - ) - allowCredentials = true - }.applyPermitDefaultValues()) - } - -private fun assertRootUserNotNull(securityProperties: CreSecurityProperties) { - Assert.notNull(securityProperties.root, "cre.security.root should be defined") -} +private class InvalidSystemUserException(userType: String, message: String) : + RuntimeException("Invalid $userType user: $message") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt index c1c4384..990551c 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt @@ -12,20 +12,25 @@ import javax.persistence.Id import javax.persistence.Table import javax.validation.constraints.NotBlank -data class Configuration( +sealed class ConfigurationBase( @JsonIgnore val type: ConfigurationType, - val content: String, val lastUpdated: LocalDateTime ) { val key = type.key val requireRestart = type.requireRestart val editable = !type.computed +} +class Configuration(type: ConfigurationType, val content: String, lastUpdated: LocalDateTime) : + ConfigurationBase(type, lastUpdated) { fun toEntity() = ConfigurationEntity(key, content, lastUpdated) } +class SecureConfiguration(type: ConfigurationType, lastUpdated: LocalDateTime) : + ConfigurationBase(type, lastUpdated) + @Entity @Table(name = "configuration") data class ConfigurationEntity( @@ -76,6 +81,15 @@ fun configuration( configuration(type = key.toConfigurationType(), content = content) } +fun secureConfiguration( + type: ConfigurationType, + lastUpdated: LocalDateTime? = null +) = SecureConfiguration(type, lastUpdated ?: LocalDateTime.now()) + +fun secureConfiguration( + configuration: Configuration +) = secureConfiguration(configuration.type, configuration.lastUpdated) + enum class ConfigurationType( val key: String, val defaultContent: Any? = null, @@ -86,8 +100,8 @@ enum class ConfigurationType( val secure: Boolean = false ) { INSTANCE_NAME("instance.name", defaultContent = "Color Recipes Explorer", public = true), - INSTANCE_LOGO_PATH("instance.logo.path", defaultContent = "images/logo", public = true), - INSTANCE_ICON_PATH("instance.icon.path", defaultContent = "images/icon", public = true), + INSTANCE_LOGO_SET("instance.logo.set", defaultContent = false, public = true), + INSTANCE_ICON_SET("instance.icon.set", defaultContent = false, public = true), INSTANCE_URL("instance.url", "http://localhost:9090", public = true), DATABASE_URL("database.url", defaultContent = "mysql://localhost/cre", file = true, requireRestart = true), @@ -128,15 +142,15 @@ class InvalidConfigurationKeyException(val key: String) : ) class InvalidImageConfigurationException(val type: ConfigurationType) : - RestException( - "invalid-configuration-image", - "Invalid image configuration", - HttpStatus.BAD_REQUEST, - "The configuration with the key '${type.key}' does not accept images as content", - mapOf( - "key" to type.key - ) - ) + RestException( + "invalid-configuration-image", + "Invalid image configuration", + HttpStatus.BAD_REQUEST, + "The configuration with the key '${type.key}' does not accept images as content", + mapOf( + "key" to type.key + ) + ) class ConfigurationNotSetException(val type: ConfigurationType) : RestException( diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt index 3f4a64a..ac6f5d6 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt @@ -1,12 +1,12 @@ package dev.fyloz.colorrecipesexplorer.model.account +import dev.fyloz.colorrecipesexplorer.SpringUserDetails import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.EntityDto import dev.fyloz.colorrecipesexplorer.model.Model import org.hibernate.annotations.Fetch import org.hibernate.annotations.FetchMode -import org.springframework.security.core.GrantedAuthority import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import java.time.LocalDateTime @@ -59,9 +59,6 @@ data class User( .apply { if (group != null) this.addAll(group!!.flatPermissions) } - - val authorities: Set - get() = flatPermissions.map { it.toAuthority() }.toMutableSet() } open class UserSaveDto( @@ -110,13 +107,23 @@ data class UserOutputDto( data class UserLoginRequest(val id: Long, val password: String) +data class UserDetails(val user: User) : SpringUserDetails { + override fun getPassword() = user.password + override fun getUsername() = user.id.toString() + override fun getAuthorities() = user.flatPermissions.toAuthorities() + + override fun isAccountNonExpired() = true + override fun isAccountNonLocked() = true + override fun isCredentialsNonExpired() = true + override fun isEnabled() = true +} + // ==== DSL ==== fun user( - passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), id: Long = 0L, firstName: String = "firstName", lastName: String = "lastName", - password: String = passwordEncoder.encode("password"), + password: String = "password", isDefaultGroupUser: Boolean = false, isSystemUser: Boolean = false, group: Group? = null, @@ -135,6 +142,30 @@ fun user( lastLoginTime ).apply(op) +fun user( + id: Long = 0L, + firstName: String = "firstName", + lastName: String = "lastName", + plainPassword: String = "password", + isDefaultGroupUser: Boolean = false, + isSystemUser: Boolean = false, + group: Group? = null, + permissions: MutableSet = mutableSetOf(), + lastLoginTime: LocalDateTime? = null, + passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), + op: User.() -> Unit = {} +) = User( + id, + firstName, + lastName, + passwordEncoder.encode(plainPassword), + isDefaultGroupUser, + isSystemUser, + group, + permissions, + lastLoginTime +).apply(op) + fun userSaveDto( passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), id: Long = 0L, @@ -155,6 +186,21 @@ fun userUpdateDto( op: UserUpdateDto.() -> Unit = {} ) = UserUpdateDto(id, firstName, lastName, groupId, permissions).apply(op) +// ==== Extensions ==== +fun Set.toAuthorities() = + this.map { it.toAuthority() }.toMutableSet() + +fun User.toOutputDto() = + UserOutputDto( + this.id, + this.firstName, + this.lastName, + this.group, + this.flatPermissions, + this.permissions, + this.lastLoginTime + ) + // ==== Exceptions ==== private const val USER_NOT_FOUND_EXCEPTION_TITLE = "User not found" private const val USER_ALREADY_EXISTS_EXCEPTION_TITLE = "User already exists" diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt index 52e61d0..6864c91 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt @@ -3,13 +3,12 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeEditUsers import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeViewUsers import dev.fyloz.colorrecipesexplorer.model.account.* -import dev.fyloz.colorrecipesexplorer.service.UserService -import dev.fyloz.colorrecipesexplorer.service.GroupService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService +import dev.fyloz.colorrecipesexplorer.service.users.UserService import org.springframework.context.annotation.Profile import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* -import java.security.Principal import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.validation.Valid @@ -31,21 +30,6 @@ class UserController(private val userService: UserService) { fun getById(@PathVariable id: Long) = ok(userService.getByIdForOutput(id)) - @GetMapping("current") - fun getCurrent(loggedInUser: Principal?) = - if (loggedInUser != null) - ok( - with(userService) { - getById( - loggedInUser.name.toLong(), - ignoreDefaultGroupUsers = false, - ignoreSystemUsers = false - ).toOutput() - } - ) - else - forbidden() - @PostMapping @PreAuthorizeEditUsers fun save(@Valid @RequestBody user: UserSaveDto) = @@ -132,6 +116,12 @@ class GroupsController( getRequestDefaultGroup(request).toOutput() }) + @GetMapping("currentuser") + fun getCurrentGroupUser(request: HttpServletRequest) = + ok(with(groupService.getRequestDefaultGroup(request)) { + userService.getDefaultGroupUser(this).toOutputDto() + }) + @PostMapping @PreAuthorizeEditUsers fun save(@Valid @RequestBody group: GroupSaveDto) = @@ -161,6 +151,7 @@ class GroupsController( @Profile("!emergency") class LogoutController(private val userService: UserService) { @GetMapping("logout") + @PreAuthorize("isFullyAuthenticated()") fun logout(request: HttpServletRequest) = ok { userService.logout(request) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt index 1cad0ee..db64365 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt @@ -1,12 +1,13 @@ package dev.fyloz.colorrecipesexplorer.rest -import dev.fyloz.colorrecipesexplorer.model.Configuration +import dev.fyloz.colorrecipesexplorer.model.ConfigurationBase import dev.fyloz.colorrecipesexplorer.model.ConfigurationDto import dev.fyloz.colorrecipesexplorer.model.ConfigurationImageDto import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.toAuthority import dev.fyloz.colorrecipesexplorer.restartApplication import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.* @@ -20,13 +21,11 @@ class ConfigurationController(val configurationService: ConfigurationService) { fun getAll(@RequestParam(required = false) keys: String?, authentication: Authentication?) = ok(with(configurationService) { if (keys != null) getAll(keys) else getAll() - }.filter { - !it.type.secure && authentication.hasAuthority(it) - }) + }.filter { authentication.hasAuthority(it) }) @GetMapping("{key}") fun get(@PathVariable key: String, authentication: Authentication?) = with(configurationService.get(key)) { - if (!this.type.secure && authentication.hasAuthority(this)) ok(this) else forbidden() + if (authentication.hasAuthority(this)) ok(this) else forbidden() } @PutMapping @@ -35,20 +34,38 @@ class ConfigurationController(val configurationService: ConfigurationService) { configurationService.set(configurations) } - @PutMapping("image") - @PreAuthorize("hasAuthority('ADMIN')") - fun setImage(@RequestParam @NotBlank key: String, @RequestParam @NotBlank image: MultipartFile) = noContent { - configurationService.set(ConfigurationImageDto(key, image)) - } - @PostMapping("restart") @PreAuthorize("hasAuthority('ADMIN')") fun restart() = noContent { restartApplication() } + + // Icon + + @GetMapping("icon") + fun getIcon() = + okFile(configurationService.getConfiguredIcon(), MediaType.IMAGE_PNG_VALUE) + + @PutMapping("icon") + @PreAuthorize("hasAuthority('ADMIN')") + fun setIcon(@RequestParam icon: MultipartFile) = noContent { + configurationService.setConfiguredIcon(icon) + } + + // Logo + + @GetMapping("logo") + fun getLogo() = + okFile(configurationService.getConfiguredLogo(), MediaType.IMAGE_PNG_VALUE) + + @PutMapping("logo") + @PreAuthorize("hasAuthority('ADMIN')") + fun setLogo(@RequestParam logo: MultipartFile) = noContent { + configurationService.setConfiguredLogo(logo) + } } -private fun Authentication?.hasAuthority(configuration: Configuration) = when { +private fun Authentication?.hasAuthority(configuration: ConfigurationBase) = when { configuration.type.public -> true this != null && Permission.ADMIN.toAuthority() in this.authorities -> true else -> false diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt index 5f1e689..92b078a 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt @@ -2,8 +2,7 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService -import dev.fyloz.colorrecipesexplorer.service.FileService -import org.springframework.core.io.ByteArrayResource +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -12,26 +11,18 @@ import org.springframework.web.multipart.MultipartFile import java.net.URI const val FILE_CONTROLLER_PATH = "/api/file" -private const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE @RestController @RequestMapping(FILE_CONTROLLER_PATH) class FileController( - private val fileService: FileService, + private val fileService: WriteableFileService, private val configService: ConfigurationService ) { @GetMapping(produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE]) fun upload( @RequestParam path: String, @RequestParam(required = false) mediaType: String? - ): ResponseEntity { - val file = fileService.read(path) - return ResponseEntity.ok() - .header("Content-Disposition", "filename=${getFileNameFromPath(path)}") - .contentLength(file.contentLength()) - .contentType(MediaType.parseMediaType(mediaType ?: DEFAULT_MEDIA_TYPE)) - .body(file) - } + ) = okFile(fileService.read(path), mediaType) @PutMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @PreAuthorize("hasAnyAuthority('WRITE_FILE')") @@ -46,17 +37,13 @@ class FileController( @DeleteMapping @PreAuthorize("hasAnyAuthority('WRITE_FILE')") - fun delete(@RequestParam path: String): ResponseEntity { - return noContent { + fun delete(@RequestParam path: String): ResponseEntity = + noContent { fileService.delete(path) } - } private fun created(path: String): ResponseEntity = ResponseEntity .created(URI.create("${configService.get(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=$path")) .build() - - private fun getFileNameFromPath(path: String) = - path.split("/").last() } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt index 23d59da..7147aa0 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt @@ -2,12 +2,14 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.model.Model +import org.springframework.core.io.Resource import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import java.net.URI +const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE lateinit var CRE_PROPERTIES: CreProperties /** Creates a HTTP OK [ResponseEntity] from the given [body]. */ @@ -24,6 +26,14 @@ fun ok(action: () -> Unit): ResponseEntity { return ResponseEntity.ok().build() } +/** Creates a HTTP OK [ResponseEntity] for the given [file], with the given [mediaType]. */ +fun okFile(file: Resource, mediaType: String? = null): ResponseEntity = + ResponseEntity.ok() + .header("Content-Disposition", "filename=${file.filename}") + .contentLength(file.contentLength()) + .contentType(MediaType.parseMediaType(mediaType ?: DEFAULT_MEDIA_TYPE)) + .body(file) + /** Creates a HTTP CREATED [ResponseEntity] from the given [body] with the location set to [controllerPath]/id. */ fun created(controllerPath: String, body: T): ResponseEntity = created(controllerPath, body, body.id!!) @@ -63,3 +73,6 @@ fun httpHeaders( op() } + +fun getFileNameFromPath(path: String) = + path.split("/").last() diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt index e9cbe47..027d71d 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt @@ -5,7 +5,7 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitSaveDto import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitUpdateDto import dev.fyloz.colorrecipesexplorer.service.TouchUpKitService import org.springframework.context.annotation.Profile -import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -57,7 +57,7 @@ class TouchUpKitController( } @GetMapping("pdf") - fun getJobPdf(@RequestParam project: String): ResponseEntity { + fun getJobPdf(@RequestParam project: String): ResponseEntity { with(touchUpKitService.generateJobPdfResource(project)) { return ResponseEntity.ok() .header("Content-Disposition", "filename=TouchUpKit_$project.pdf") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt index 6802776..327d6e2 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt @@ -4,6 +4,7 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository import dev.fyloz.colorrecipesexplorer.rest.FILE_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import io.jsonwebtoken.lang.Assert import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile @@ -39,7 +40,7 @@ class MaterialServiceImpl( val recipeService: RecipeService, val mixService: MixService, @Lazy val materialTypeService: MaterialTypeService, - val fileService: FileService, + val fileService: WriteableFileService, val configService: ConfigurationService ) : AbstractExternalNamedModelService( @@ -59,7 +60,7 @@ class MaterialServiceImpl( isMixType = this.isMixType, materialType = this.materialType!!, simdutUrl = if (fileService.exists(this.simdutFilePath)) - "${configService.get(ConfigurationType.INSTANCE_URL).content}$FILE_CONTROLLER_PATH?path=${ + "${configService.getContent(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=${ URLEncoder.encode( this.simdutFilePath, StandardCharsets.UTF_8 diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt index 3b44f8a..dd9eccd 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt @@ -5,6 +5,8 @@ import dev.fyloz.colorrecipesexplorer.model.account.Group import dev.fyloz.colorrecipesexplorer.model.validation.or import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService import dev.fyloz.colorrecipesexplorer.utils.setAll import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile @@ -78,7 +80,7 @@ class RecipeServiceImpl( }.toSet(), this.groupsInformation, recipeImageService.getAllImages(this) - .map { this.imageUrl(configService.get(ConfigurationType.INSTANCE_URL).content, it) } + .map { this.imageUrl(configService.getContent(ConfigurationType.INSTANCE_URL), it) } .toSet() ) @@ -87,7 +89,7 @@ class RecipeServiceImpl( repository.existsByNameAndCompany(name, company) override fun isApprobationExpired(recipe: Recipe): Boolean? = - with(Period.parse(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION).content)) { + with(Period.parse(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION))) { recipe.approbationDate?.plus(this)?.isBefore(LocalDate.now()) } @@ -222,7 +224,7 @@ const val RECIPE_IMAGE_EXTENSION = ".jpg" @Service @Profile("!emergency") class RecipeImageServiceImpl( - val fileService: FileService + val fileService: WriteableFileService ) : RecipeImageService { override fun getAllImages(recipe: Recipe): Set { val recipeDirectory = recipe.getDirectory() diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt index acd1600..a6bbc1e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt @@ -5,9 +5,12 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.* import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository import dev.fyloz.colorrecipesexplorer.rest.TOUCH_UP_KIT_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.FileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.* import org.springframework.context.annotation.Profile import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.stereotype.Service import java.time.LocalDate import java.time.Period @@ -32,7 +35,7 @@ interface TouchUpKitService : * If TOUCH_UP_KIT_CACHE_PDF is enabled and a file exists for the job, its content will be returned. * If caching is enabled but no file exists for the job, the generated ByteArrayResource will be cached on the disk. */ - fun generateJobPdfResource(job: String): ByteArrayResource + fun generateJobPdfResource(job: String): Resource /** Writes the given [document] to the [FileService] if TOUCH_UP_KIT_CACHE_PDF is enabled. */ fun String.cachePdfDocument(document: PdfDocument) @@ -41,14 +44,14 @@ interface TouchUpKitService : @Service @Profile("!emergency") class TouchUpKitServiceImpl( - private val fileService: FileService, + private val fileService: WriteableFileService, private val configService: ConfigurationService, touchUpKitRepository: TouchUpKitRepository ) : AbstractExternalModelService( touchUpKitRepository ), TouchUpKitService { private val cacheGeneratedFiles by lazy { - configService.get(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF).content == true.toString() + configService.getContent(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) == true.toString() } override fun idNotFoundException(id: Long) = touchUpKitIdNotFoundException(id) @@ -90,7 +93,7 @@ class TouchUpKitServiceImpl( } override fun isExpired(touchUpKit: TouchUpKit) = - with(Period.parse(configService.get(ConfigurationType.TOUCH_UP_KIT_EXPIRATION).content)) { + with(Period.parse(configService.getContent(ConfigurationType.TOUCH_UP_KIT_EXPIRATION))) { touchUpKit.completed && touchUpKit.completionDate!!.plus(this) < LocalDate.now() } @@ -120,7 +123,7 @@ class TouchUpKitServiceImpl( } } - override fun generateJobPdfResource(job: String): ByteArrayResource { + override fun generateJobPdfResource(job: String): Resource { if (cacheGeneratedFiles) { with(job.pdfDocumentPath()) { if (fileService.exists(this)) { @@ -144,5 +147,5 @@ class TouchUpKitServiceImpl( "$TOUCH_UP_KIT_FILES_PATH/$this.pdf" private fun TouchUpKit.pdfUrl() = - "${configService.get(ConfigurationType.INSTANCE_URL).content}$TOUCH_UP_KIT_CONTROLLER_PATH/pdf?job=$project" + "${configService.getContent(ConfigurationType.INSTANCE_URL)}$TOUCH_UP_KIT_CONTROLLER_PATH/pdf?job=$project" } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt index 03eef2f..f6db17e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt @@ -2,32 +2,47 @@ package dev.fyloz.colorrecipesexplorer.service.config import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.model.* -import dev.fyloz.colorrecipesexplorer.service.FileService +import dev.fyloz.colorrecipesexplorer.service.files.ResourceFileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.decrypt import dev.fyloz.colorrecipesexplorer.utils.encrypt import org.slf4j.Logger import org.springframework.context.annotation.Lazy +import org.springframework.core.io.Resource import org.springframework.security.crypto.keygen.KeyGenerators import org.springframework.stereotype.Service +import org.springframework.web.multipart.MultipartFile interface ConfigurationService { /** Gets all set configurations. */ - fun getAll(): List + fun getAll(): List /** * Gets all configurations with keys contained in the given [formattedKeyList]. * The [formattedKeyList] contains wanted configuration keys separated by a semi-colon. */ - fun getAll(formattedKeyList: String): List + fun getAll(formattedKeyList: String): List /** * Gets the configuration with the given [key]. * If the [key] does not exists, an [InvalidConfigurationKeyException] will be thrown. */ - fun get(key: String): Configuration + fun get(key: String): ConfigurationBase /** Gets the configuration with the given [type]. */ - fun get(type: ConfigurationType): Configuration + fun get(type: ConfigurationType): ConfigurationBase + + /** Gets the content of the configuration with the given [type]. */ + fun getContent(type: ConfigurationType): String + + /** Gets the content of the secure configuration with the given [type]. Should not be accessible to the users. */ + fun getSecure(type: ConfigurationType): String + + /** Gets the app's icon. */ + fun getConfiguredIcon(): Resource + + /** Gets the app's logo. */ + fun getConfiguredLogo(): Resource /** Sets the content of each configuration in the given [configurations] list. */ fun set(configurations: List) @@ -41,20 +56,26 @@ interface ConfigurationService { /** Sets the content given [configuration]. */ fun set(configuration: Configuration) - /** Sets the content of the configuration matching the given [configuration] with a given image. */ - fun set(configuration: ConfigurationImageDto) + /** Sets the app's icon. */ + fun setConfiguredIcon(icon: MultipartFile) + + /** Sets the app's logo. */ + fun setConfiguredLogo(logo: MultipartFile) /** Initialize the properties matching the given [predicate]. */ fun initializeProperties(predicate: (ConfigurationType) -> Boolean) } +const val CONFIGURATION_LOGO_RESOURCE_PATH = "images/logo.png" const val CONFIGURATION_LOGO_FILE_PATH = "images/logo" +const val CONFIGURATION_ICON_RESOURCE_PATH = "images/icon.png" const val CONFIGURATION_ICON_FILE_PATH = "images/icon" const val CONFIGURATION_FORMATTED_LIST_DELIMITER = ';' @Service("configurationService") class ConfigurationServiceImpl( - @Lazy private val fileService: FileService, + @Lazy private val fileService: WriteableFileService, + private val resourceFileService: ResourceFileService, private val configurationSource: ConfigurationSource, private val securityProperties: CreSecurityProperties, private val logger: Logger @@ -89,18 +110,55 @@ class ConfigurationServiceImpl( override fun get(key: String) = get(key.toConfigurationType()) - override fun get(type: ConfigurationType): Configuration { + override fun get(type: ConfigurationType): ConfigurationBase { // Encryption salt should never be returned, but cannot be set as "secure" without encrypting it if (type == ConfigurationType.GENERATED_ENCRYPTION_SALT) throw InvalidConfigurationKeyException(type.key) val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type) return if (type.secure) { - decryptConfiguration(configuration) + secureConfiguration(configuration) } else { configuration } } + override fun getContent(type: ConfigurationType): String { + val configuration = get(type) + if (configuration is SecureConfiguration) throw UnsupportedOperationException("Cannot get '${type.key}' configuration content because it is secure") + + return (configuration as Configuration).content + } + + override fun getSecure(type: ConfigurationType): String { + if (!type.secure) throw UnsupportedOperationException("Cannot get configuration of type '${type.key}' because it is not a secure configuration") + + val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type) + return decryptConfiguration(configuration).content + } + + override fun getConfiguredIcon() = + getConfiguredImage( + type = ConfigurationType.INSTANCE_ICON_SET, + filePath = CONFIGURATION_ICON_FILE_PATH, + resourcePath = CONFIGURATION_ICON_RESOURCE_PATH + ) + + override fun getConfiguredLogo() = + getConfiguredImage( + type = ConfigurationType.INSTANCE_LOGO_SET, + filePath = CONFIGURATION_LOGO_FILE_PATH, + resourcePath = CONFIGURATION_LOGO_RESOURCE_PATH + ) + + private fun getConfiguredImage(type: ConfigurationType, filePath: String, resourcePath: String) = + with(get(type) as Configuration) { + if (this.content == true.toString()) { + fileService.read(filePath) + } else { + resourceFileService.read(resourcePath) + } + } + override fun set(configurations: List) { configurationSource.set( configurations @@ -116,14 +174,15 @@ class ConfigurationServiceImpl( configurationSource.set(encryptConfigurationIfSecure(configuration)) } - override fun set(configuration: ConfigurationImageDto) { - val filePath = when (val configurationType = configuration.key.toConfigurationType()) { - ConfigurationType.INSTANCE_LOGO_PATH -> CONFIGURATION_LOGO_FILE_PATH - ConfigurationType.INSTANCE_ICON_PATH -> CONFIGURATION_ICON_FILE_PATH - else -> throw InvalidImageConfigurationException(configurationType) - } + override fun setConfiguredIcon(icon: MultipartFile) = + setConfiguredImage(icon, CONFIGURATION_ICON_FILE_PATH, ConfigurationType.INSTANCE_ICON_SET) - fileService.write(configuration.image, filePath, true) + override fun setConfiguredLogo(logo: MultipartFile) = + setConfiguredImage(logo, CONFIGURATION_LOGO_FILE_PATH, ConfigurationType.INSTANCE_LOGO_SET) + + private fun setConfiguredImage(image: MultipartFile, path: String, type: ConfigurationType) { + fileService.write(image, path, true) + set(configuration(type, content = true.toString())) } override fun initializeProperties(predicate: (ConfigurationType) -> Boolean) { @@ -180,7 +239,7 @@ class ConfigurationServiceImpl( private fun getGeneratedSalt(): String { logger.warn("Sensitives configurations encryption salt was not configured, using generated salt") - logger.warn("Consider configuring the encryption salt. More details at: https://git.fyloz.dev/color-recipes-explorer/backend/-/wikis/Configuration/S%C3%A9curit%C3%A9/#sel") + logger.warn("Consider configuring the encryption salt. More details at: https://cre.fyloz.dev/docs/Configuration/S%C3%A9curit%C3%A9/#sel") var saltConfiguration = configurationSource.get(saltConfigurationType) if (saltConfiguration == null) { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt index 0b00a97..6971f9e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt @@ -8,7 +8,7 @@ import dev.fyloz.colorrecipesexplorer.model.Configuration import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.repository.ConfigurationRepository -import dev.fyloz.colorrecipesexplorer.service.create +import dev.fyloz.colorrecipesexplorer.service.files.create import dev.fyloz.colorrecipesexplorer.utils.excludeAll import org.slf4j.Logger import org.springframework.boot.info.BuildProperties diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt similarity index 96% rename from src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt rename to src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt index 69cd4aa..4136ebe 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt @@ -1,9 +1,10 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.files import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.exception.RestException import org.slf4j.Logger import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.multipart.MultipartFile @@ -23,8 +24,13 @@ interface FileService { fun exists(path: String): Boolean /** Reads the file at the given [path]. */ - fun read(path: String): ByteArrayResource + fun read(path: String): Resource + /** Completes the path of the given [String] by adding the working directory. */ + fun String.fullPath(): FilePath +} + +interface WriteableFileService : FileService { /** Creates a file at the given [path]. */ fun create(path: String) @@ -36,16 +42,13 @@ interface FileService { /** Deletes the file at the given [path]. */ fun delete(path: String) - - /** Completes the path of the given [String] by adding the working directory. */ - fun String.fullPath(): FilePath } @Service class FileServiceImpl( private val creProperties: CreProperties, private val logger: Logger -) : FileService { +) : WriteableFileService { override fun exists(path: String) = withFileAt(path.fullPath()) { this.exists() && this.isFile } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt new file mode 100644 index 0000000..be9ba6e --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt @@ -0,0 +1,26 @@ +package dev.fyloz.colorrecipesexplorer.service.files + +import org.springframework.core.io.Resource +import org.springframework.core.io.ResourceLoader +import org.springframework.stereotype.Service + +@Service +class ResourceFileService( + private val resourceLoader: ResourceLoader +) : FileService { + override fun exists(path: String) = + path.fullPath().resource.exists() + + override fun read(path: String): Resource = + path.fullPath().resource.also { + if (!it.exists()) { + throw FileNotFoundException(path) + } + } + + override fun String.fullPath() = + FilePath("classpath:${this}") + + val FilePath.resource: Resource + get() = resourceLoader.getResource(this.path) +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt new file mode 100644 index 0000000..62ac1f0 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt @@ -0,0 +1,97 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName +import dev.fyloz.colorrecipesexplorer.model.account.* +import dev.fyloz.colorrecipesexplorer.repository.GroupRepository +import dev.fyloz.colorrecipesexplorer.service.AbstractExternalNamedModelService +import dev.fyloz.colorrecipesexplorer.service.ExternalNamedModelService +import org.springframework.context.annotation.Profile +import org.springframework.stereotype.Service +import org.springframework.web.util.WebUtils +import javax.servlet.http.HttpServletRequest +import javax.servlet.http.HttpServletResponse +import javax.transaction.Transactional + +const val defaultGroupCookieMaxAge = 10 * 365 * 24 * 60 * 60 // 10 ans + +interface GroupService : + ExternalNamedModelService { + /** Gets all the users of the group with the given [id]. */ + fun getUsersForGroup(id: Long): Collection + + /** Gets the default group from a cookie in the given HTTP [request]. */ + fun getRequestDefaultGroup(request: HttpServletRequest): Group + + /** Sets the default group cookie for the given HTTP [response]. */ + fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) +} + +@Service +@Profile("!emergency") +class GroupServiceImpl( + private val userService: UserService, + groupRepository: GroupRepository +) : AbstractExternalNamedModelService( + groupRepository +), + GroupService { + override fun idNotFoundException(id: Long) = groupIdNotFoundException(id) + override fun idAlreadyExistsException(id: Long) = groupIdAlreadyExistsException(id) + override fun nameNotFoundException(name: String) = groupNameNotFoundException(name) + override fun nameAlreadyExistsException(name: String) = groupNameAlreadyExistsException(name) + + override fun Group.toOutput() = GroupOutputDto( + this.id!!, + this.name, + this.permissions, + this.flatPermissions + ) + + override fun existsByName(name: String): Boolean = repository.existsByName(name) + override fun getUsersForGroup(id: Long): Collection = + userService.getByGroup(getById(id)) + + @Transactional + override fun save(entity: Group): Group { + return super.save(entity).apply { + userService.saveDefaultGroupUser(this) + } + } + + override fun update(entity: GroupUpdateDto): Group { + val persistedGroup by lazy { getById(entity.id) } + return update(with(entity) { + Group( + entity.id, + if (name.isNotBlank()) entity.name else persistedGroup.name, + if (permissions.isNotEmpty()) entity.permissions else persistedGroup.permissions + ) + }) + } + + @Transactional + override fun delete(entity: Group) { + userService.delete(userService.getDefaultGroupUser(entity)) + super.delete(entity) + } + + override fun getRequestDefaultGroup(request: HttpServletRequest): Group { + val defaultGroupCookie = WebUtils.getCookie(request, defaultGroupCookieName) + ?: throw NoDefaultGroupException() + val defaultGroupUser = userService.getById( + defaultGroupCookie.value.toLong(), + ignoreDefaultGroupUsers = false, + ignoreSystemUsers = true + ) + return defaultGroupUser.group!! + } + + override fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) { + val group = getById(groupId) + val defaultGroupUser = userService.getDefaultGroupUser(group) + response.addHeader( + "Set-Cookie", + "$defaultGroupCookieName=${defaultGroupUser.id}; Max-Age=$defaultGroupCookieMaxAge; Path=/api; HttpOnly; Secure; SameSite=strict" + ) + } +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt new file mode 100644 index 0000000..282d6ba --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt @@ -0,0 +1,79 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto +import dev.fyloz.colorrecipesexplorer.utils.base64encode +import dev.fyloz.colorrecipesexplorer.utils.toDate +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.jackson.io.JacksonDeserializer +import io.jsonwebtoken.jackson.io.JacksonSerializer +import org.springframework.stereotype.Service +import java.time.Instant +import java.util.* + +const val jwtClaimUser = "user" + +interface JwtService { + /** Build a JWT token for the given [userDetails]. */ + fun buildJwt(userDetails: UserDetails): String + + /** Build a JWT token for the given [user]. */ + fun buildJwt(user: User): String + + /** Parses a user from the given [jwt] token. */ + fun parseJwt(jwt: String): UserOutputDto +} + +@Service +class JwtServiceImpl( + val objectMapper: ObjectMapper, + val securityProperties: CreSecurityProperties +) : JwtService { + private val secretKey by lazy { + securityProperties.jwtSecret.base64encode() + } + + private val jwtBuilder by lazy { + Jwts.builder() + .serializeToJsonWith(JacksonSerializer>(objectMapper)) + .signWith(secretKey) + } + + private val jwtParser by lazy { + Jwts.parserBuilder() + .deserializeJsonWith(JacksonDeserializer>(objectMapper)) + .setSigningKey(secretKey) + .build() + } + + override fun buildJwt(userDetails: UserDetails) = + buildJwt(userDetails.user) + + override fun buildJwt(user: User): String = + jwtBuilder + .setSubject(user.id.toString()) + .setExpiration(getCurrentExpirationDate()) + .claim(jwtClaimUser, user.serialize()) + .compact() + + override fun parseJwt(jwt: String): UserOutputDto = + with( + jwtParser.parseClaimsJws(jwt) + .body.get(jwtClaimUser, String::class.java) + ) { + objectMapper.readValue(this) + } + + private fun getCurrentExpirationDate(): Date = + Instant.now() + .plusSeconds(securityProperties.jwtDuration) + .toDate() + + private fun User.serialize(): String = + objectMapper.writeValueAsString(this.toOutputDto()) +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt new file mode 100644 index 0000000..923abed --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt @@ -0,0 +1,77 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import dev.fyloz.colorrecipesexplorer.SpringUserDetails +import dev.fyloz.colorrecipesexplorer.SpringUserDetailsService +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.exception.NotFoundException +import dev.fyloz.colorrecipesexplorer.model.account.Permission +import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.user +import org.springframework.context.annotation.Profile +import org.springframework.security.core.userdetails.UsernameNotFoundException +import org.springframework.stereotype.Service + +interface UserDetailsService : SpringUserDetailsService { + /** Loads an [User] for the given [id]. */ + fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean = false): UserDetails +} + +@Service +@Profile("!emergency") +class UserDetailsServiceImpl( + private val userService: UserService +) : UserDetailsService { + override fun loadUserByUsername(username: String): UserDetails { + try { + return loadUserById(username.toLong(), true) + } catch (ex: NotFoundException) { + throw UsernameNotFoundException(username) + } + } + + override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { + val user = userService.getById( + id, + ignoreDefaultGroupUsers = ignoreDefaultGroupUsers, + ignoreSystemUsers = false + ) + return UserDetails(user) + } +} + +@Service +@Profile("emergency") +class EmergencyUserDetailsServiceImpl( + securityProperties: CreSecurityProperties +) : UserDetailsService { + private val users: Set + + init { + if (securityProperties.root == null) { + throw NullPointerException("The root user has not been configured") + } + + users = setOf( + // Add root user + with(securityProperties.root!!) { + user( + id = this.id, + plainPassword = this.password, + permissions = mutableSetOf(Permission.ADMIN) + ) + } + ) + } + + override fun loadUserByUsername(username: String): SpringUserDetails { + return loadUserById(username.toLong(), true) + } + + override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { + val user = users.firstOrNull { it.id == id } + ?: throw UsernameNotFoundException(id.toString()) + + return UserDetails(user) + } +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt similarity index 57% rename from src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt rename to src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt index 9373ecb..04add2b 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt @@ -1,25 +1,18 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.users import dev.fyloz.colorrecipesexplorer.config.security.blacklistedJwtTokens -import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName -import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.account.* import dev.fyloz.colorrecipesexplorer.model.validation.or -import dev.fyloz.colorrecipesexplorer.repository.GroupRepository import dev.fyloz.colorrecipesexplorer.repository.UserRepository +import dev.fyloz.colorrecipesexplorer.service.AbstractExternalModelService +import dev.fyloz.colorrecipesexplorer.service.ExternalModelService import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile -import org.springframework.security.core.userdetails.UserDetails -import org.springframework.security.core.userdetails.UserDetailsService -import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import org.springframework.web.util.WebUtils import java.time.LocalDateTime import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse -import javax.transaction.Transactional -import org.springframework.security.core.userdetails.User as SpringUser interface UserService : ExternalModelService { @@ -57,29 +50,11 @@ interface UserService : fun logout(request: HttpServletRequest) } -interface GroupService : - ExternalNamedModelService { - /** Gets all the users of the group with the given [id]. */ - fun getUsersForGroup(id: Long): Collection - - /** Gets the default group from a cookie in the given HTTP [request]. */ - fun getRequestDefaultGroup(request: HttpServletRequest): Group - - /** Sets the default group cookie for the given HTTP [response]. */ - fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) -} - -interface CreUserDetailsService : UserDetailsService { - /** Loads an [User] for the given [id]. */ - fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean = false): UserDetails -} - @Service @Profile("!emergency") class UserServiceImpl( userRepository: UserRepository, @Lazy val groupService: GroupService, - @Lazy val passwordEncoder: PasswordEncoder, ) : AbstractExternalModelService( userRepository ), @@ -87,15 +62,7 @@ class UserServiceImpl( override fun idNotFoundException(id: Long) = userIdNotFoundException(id) override fun idAlreadyExistsException(id: Long) = userIdAlreadyExistsException(id) - override fun User.toOutput() = UserOutputDto( - this.id, - this.firstName, - this.lastName, - this.group, - this.flatPermissions, - this.permissions, - this.lastLoginTime - ) + override fun User.toOutput() = this.toOutputDto() override fun existsByFirstNameAndLastName(firstName: String, lastName: String): Boolean = repository.existsByFirstNameAndLastName(firstName, lastName) @@ -122,11 +89,11 @@ class UserServiceImpl( override fun save(entity: UserSaveDto): User = save(with(entity) { - User( - id, - firstName, - lastName, - passwordEncoder.encode(password), + user( + id = id, + firstName = firstName, + lastName = lastName, + plainPassword = password, isDefaultGroupUser = false, isSystemUser = false, group = if (groupId != null) groupService.getById(groupId) else null, @@ -148,7 +115,7 @@ class UserServiceImpl( id = 1000000L + group.id!!, firstName = group.name, lastName = "User", - password = passwordEncoder.encode(group.name), + plainPassword = group.name, group = group, isDefaultGroupUser = true ) @@ -197,11 +164,11 @@ class UserServiceImpl( override fun updatePassword(id: Long, password: String): User { val persistedUser = getById(id, ignoreDefaultGroupUsers = true, ignoreSystemUsers = true) return super.update(with(persistedUser) { - User( + user( id, firstName, lastName, - passwordEncoder.encode(password), + plainPassword = password, isDefaultGroupUser, isSystemUser, group, @@ -227,101 +194,3 @@ class UserServiceImpl( } } } - -const val defaultGroupCookieMaxAge = 10 * 365 * 24 * 60 * 60 // 10 ans - -@Service -@Profile("!emergency") -class GroupServiceImpl( - private val userService: UserService, - groupRepository: GroupRepository -) : AbstractExternalNamedModelService( - groupRepository -), - GroupService { - override fun idNotFoundException(id: Long) = groupIdNotFoundException(id) - override fun idAlreadyExistsException(id: Long) = groupIdAlreadyExistsException(id) - override fun nameNotFoundException(name: String) = groupNameNotFoundException(name) - override fun nameAlreadyExistsException(name: String) = groupNameAlreadyExistsException(name) - - override fun Group.toOutput() = GroupOutputDto( - this.id!!, - this.name, - this.permissions, - this.flatPermissions - ) - - override fun existsByName(name: String): Boolean = repository.existsByName(name) - override fun getUsersForGroup(id: Long): Collection = - userService.getByGroup(getById(id)) - - @Transactional - override fun save(entity: Group): Group { - return super.save(entity).apply { - userService.saveDefaultGroupUser(this) - } - } - - override fun update(entity: GroupUpdateDto): Group { - val persistedGroup by lazy { getById(entity.id) } - return update(with(entity) { - Group( - entity.id, - if (name.isNotBlank()) entity.name else persistedGroup.name, - if (permissions.isNotEmpty()) entity.permissions else persistedGroup.permissions - ) - }) - } - - @Transactional - override fun delete(entity: Group) { - userService.delete(userService.getDefaultGroupUser(entity)) - super.delete(entity) - } - - override fun getRequestDefaultGroup(request: HttpServletRequest): Group { - val defaultGroupCookie = WebUtils.getCookie(request, defaultGroupCookieName) - ?: throw NoDefaultGroupException() - val defaultGroupUser = userService.getById( - defaultGroupCookie.value.toLong(), - ignoreDefaultGroupUsers = false, - ignoreSystemUsers = true - ) - return defaultGroupUser.group!! - } - - override fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) { - val group = getById(groupId) - val defaultGroupUser = userService.getDefaultGroupUser(group) - response.addHeader( - "Set-Cookie", - "$defaultGroupCookieName=${defaultGroupUser.id}; Max-Age=${defaultGroupCookieMaxAge}; Path=/api; HttpOnly; Secure; SameSite=strict" - ) - } -} - -@Service -@Profile("!emergency") -class CreUserDetailsServiceImpl( - private val userService: UserService -) : - CreUserDetailsService { - override fun loadUserByUsername(username: String): UserDetails { - try { - return loadUserById(username.toLong(), true) - } catch (ex: NotFoundException) { - throw UsernameNotFoundException(username) - } catch (ex: NotFoundException) { - throw UsernameNotFoundException(username) - } - } - - override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { - val user = userService.getById( - id, - ignoreDefaultGroupUsers = ignoreDefaultGroupUsers, - ignoreSystemUsers = false - ) - return SpringUser(user.id.toString(), user.password, user.authorities) - } -} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt index a8206e6..1c27b76 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt @@ -1,5 +1,7 @@ package dev.fyloz.colorrecipesexplorer.utils +import io.jsonwebtoken.io.Encoders +import io.jsonwebtoken.security.Keys import org.springframework.security.crypto.encrypt.Encryptors import org.springframework.security.crypto.encrypt.TextEncryptor @@ -15,3 +17,8 @@ fun String.decrypt(password: String, salt: String): String = private fun withTextEncryptor(password: String, salt: String, op: (TextEncryptor) -> String) = op(Encryptors.text(password, salt)) + +fun String.base64encode() = + with(Encoders.BASE64.encode(this.toByteArray())) { + Keys.hmacShaKeyFor(this.toByteArray()) + } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt new file mode 100644 index 0000000..b9af339 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt @@ -0,0 +1,55 @@ +package dev.fyloz.colorrecipesexplorer.utils + +import javax.servlet.http.HttpServletResponse + +private const val defaultCookieMaxAge = 3600L +private const val defaultCookieHttpOnly = true +private const val defaultCookieSameSite = true +private const val defaultCookieSecure = true + +data class CookieBuilderOptions( + /** HTTP Only cookies cannot be access by Javascript clients. */ + var httpOnly: Boolean = defaultCookieHttpOnly, + + /** SameSite cookies are only sent in requests to their origin location. */ + var sameSite: Boolean = defaultCookieSameSite, + + /** Secure cookies are only sent in HTTPS requests. */ + var secure: Boolean = defaultCookieSecure, + + /** Cookie's maximum age in seconds. */ + var maxAge: Long = defaultCookieMaxAge +) + +private enum class CookieBuilderOption(val optionName: String) { + HTTP_ONLY("HttpOnly"), + SAME_SITE("SameSite"), + SECURE("Secure"), + MAX_AGE("Max-Age") +} + +fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit) { + this.addHeader("Set-Cookie", buildCookie(name, value, optionsBuilder)) +} + +private fun buildCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit): String { + val options = CookieBuilderOptions().apply(optionsBuilder) + val cookie = StringBuilder("$name=$value;") + + fun addBoolOption(option: CookieBuilderOption, enabled: Boolean) { + if (enabled) { + cookie.append("${option.optionName};") + } + } + + fun addOption(option: CookieBuilderOption, value: Any) { + cookie.append("${option.optionName}=$value;") + } + + addBoolOption(CookieBuilderOption.HTTP_ONLY, options.httpOnly) + addBoolOption(CookieBuilderOption.SAME_SITE, options.sameSite) + addBoolOption(CookieBuilderOption.SECURE, options.secure) + addOption(CookieBuilderOption.MAX_AGE, options.maxAge) + + return cookie.toString() +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt index 9889865..272ad29 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt @@ -1,9 +1,18 @@ package dev.fyloz.colorrecipesexplorer.utils +import java.time.Instant import java.time.Period +import java.util.* fun period(days: Int = 0, months: Int = 0, years: Int = 0): Period = Period.of(days, months, years) +fun Instant.toDate(): Date = + Date.from(this) + +/** Checks if a [Instant] is around the given [other] Instant, with an allowed [offset] in seconds. */ +fun Instant.isAround(other: Instant, offset: Long = 1L) = + this.isAfter(other.minusSeconds(offset)) && this.isBefore(other.plusSeconds(offset)) + val Int.months: Period get() = period(months = this) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e796dda..18852ab 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,7 +3,7 @@ server.port=9090 # CRE cre.server.data-directory=data cre.server.config-directory=config -cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE +cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE78WWOgl8InrbwBgQsMy0 cre.security.jwt-duration=18000000 cre.security.aes-secret=blabla # Root user diff --git a/src/main/resources/images/icon.png b/src/main/resources/images/icon.png new file mode 100644 index 0000000..1e877b7 Binary files /dev/null and b/src/main/resources/images/icon.png differ diff --git a/src/main/resources/images/logo.png b/src/main/resources/images/logo.png new file mode 100644 index 0000000..08822c8 Binary files /dev/null and b/src/main/resources/images/logo.png differ diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt index 7394f85..fa622f0 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt @@ -10,8 +10,8 @@ import kotlin.test.assertEquals @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) class MaterialRepositoryTest @Autowired constructor( - private val materialRepository: MaterialRepository, - private val entityManager: TestEntityManager + private val materialRepository: MaterialRepository, + private val entityManager: TestEntityManager ) { // updateInventoryQuantityById() diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt index 2362e33..e87c425 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt @@ -10,8 +10,8 @@ import kotlin.test.assertEquals @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) class MixRepositoryTest @Autowired constructor( - private val mixRepository: MixRepository, - private val entityManager: TestEntityManager + private val mixRepository: MixRepository, + private val entityManager: TestEntityManager ) { // updateLocationById() diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt index a9979b7..7fd9b53 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt @@ -5,8 +5,9 @@ import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.account.* -import dev.fyloz.colorrecipesexplorer.repository.UserRepository import dev.fyloz.colorrecipesexplorer.repository.GroupRepository +import dev.fyloz.colorrecipesexplorer.repository.UserRepository +import dev.fyloz.colorrecipesexplorer.service.users.* import org.junit.jupiter.api.* import org.springframework.mock.web.MockHttpServletResponse import org.springframework.security.core.userdetails.UsernameNotFoundException @@ -18,24 +19,23 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue -import org.springframework.security.core.userdetails.User as SpringUser @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserServiceTest : AbstractExternalModelServiceTest() { private val passwordEncoder = BCryptPasswordEncoder() - override val entity: User = user(passwordEncoder, id = 0L) - override val anotherEntity: User = user(passwordEncoder, id = 1L) - private val entityDefaultGroupUser = user(passwordEncoder, id = 2L, isDefaultGroupUser = true) - private val entitySystemUser = user(passwordEncoder, id = 3L, isSystemUser = true) + override val entity: User = user(id = 0L, passwordEncoder = passwordEncoder) + override val anotherEntity: User = user(id = 1L, passwordEncoder = passwordEncoder) + private val entityDefaultGroupUser = user(id = 2L, isDefaultGroupUser = true, passwordEncoder = passwordEncoder) + private val entitySystemUser = user(id = 3L, isSystemUser = true, passwordEncoder = passwordEncoder) private val group = group(id = 0L) override val entitySaveDto: UserSaveDto = spy(userSaveDto(passwordEncoder, id = 0L)) override val entityUpdateDto: UserUpdateDto = spy(userUpdateDto(id = 0L)) override val repository: UserRepository = mock() private val groupService: GroupService = mock() - override val service: UserService = spy(UserServiceImpl(repository, groupService, passwordEncoder)) + override val service: UserService = spy(UserServiceImpl(repository, groupService)) private val entitySaveDtoUser = User( entitySaveDto.id, @@ -210,7 +210,7 @@ class GroupServiceTest : override val entityWithEntityName: Group = group(id = 2L, name = entity.name) private val groupUserId = 1000000L + entity.id!! - private val groupUser = user(BCryptPasswordEncoder(), id = groupUserId, group = entity) + private val groupUser = user(passwordEncoder = BCryptPasswordEncoder(), id = groupUserId, group = entity) @BeforeEach override fun afterEach() { @@ -303,7 +303,7 @@ class GroupServiceTest : @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserUserDetailsServiceTest { private val userService: UserService = mock() - private val service = spy(CreUserDetailsServiceImpl(userService)) + private val service = spy(UserDetailsServiceImpl(userService)) private val user = user(id = 0L) @@ -317,8 +317,8 @@ class UserUserDetailsServiceTest { @Test fun `loadUserByUsername() calls loadUserByUserId() with the given username as an id`() { whenever(userService.getById(eq(user.id), any(), any())).doReturn(user) - doReturn(SpringUser(user.id.toString(), user.password, listOf())).whenever(service) - .loadUserById(user.id) + doReturn(UserDetails(user(id = user.id, plainPassword = user.password))) + .whenever(service).loadUserById(user.id) service.loadUserByUsername(user.id.toString()) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt index 8c4df85..ea4a73f 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt @@ -5,22 +5,35 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.service.config.CONFIGURATION_FORMATTED_LIST_DELIMITER import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationServiceImpl import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationSource +import dev.fyloz.colorrecipesexplorer.service.files.ResourceFileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.encrypt import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows +import org.springframework.core.io.Resource +import org.springframework.web.multipart.MultipartFile import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class ConfigurationServiceTest { - private val fileService = mockk() + private val fileService = mockk() + private val resourceFileService = mockk() private val configurationSource = mockk() private val securityProperties = mockk { every { configSalt } returns "d32270943af7e1cc" } - private val service = spyk(ConfigurationServiceImpl(fileService, configurationSource, securityProperties, mockk())) + private val service = spyk( + ConfigurationServiceImpl( + fileService, + resourceFileService, + configurationSource, + securityProperties, + mockk() + ) + ) @AfterEach fun afterEach() { @@ -48,8 +61,8 @@ class ConfigurationServiceTest { fun `getAll() only returns set configurations`() { val unsetConfigurationTypes = listOf( ConfigurationType.INSTANCE_NAME, - ConfigurationType.INSTANCE_LOGO_PATH, - ConfigurationType.INSTANCE_ICON_PATH + ConfigurationType.INSTANCE_LOGO_SET, + ConfigurationType.INSTANCE_ICON_SET ) every { service.get(match { it in unsetConfigurationTypes }) } answers { @@ -81,8 +94,8 @@ class ConfigurationServiceTest { fun `getAll() only includes configurations matching the formatted formatted key list`() { val configurationTypes = listOf( ConfigurationType.INSTANCE_NAME, - ConfigurationType.INSTANCE_LOGO_PATH, - ConfigurationType.INSTANCE_ICON_PATH + ConfigurationType.INSTANCE_LOGO_SET, + ConfigurationType.INSTANCE_ICON_SET ) val formattedKeyList = configurationTypes .map { it.key } @@ -112,7 +125,7 @@ class ConfigurationServiceTest { @Test fun `get(key) calls get() with the ConfigurationType matching the given key`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET val key = type.key every { service.get(type) } answers { @@ -131,7 +144,7 @@ class ConfigurationServiceTest { @Test fun `get(type) gets the configuration in the ConfigurationSource`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET val configuration = configuration(type = type) every { configurationSource.get(type) } returns configuration @@ -143,7 +156,7 @@ class ConfigurationServiceTest { @Test fun `get(type) throws ConfigurationNotSetException when the given ConfigurationType has no set configuration`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET every { configurationSource.get(type) } returns null @@ -165,7 +178,47 @@ class ConfigurationServiceTest { } @Test - fun `get(type) decrypts configuration content when the given ConfigurationType is secure`() { + fun `get(type) returns a SecureConfiguration when the given ConfigurationType is secure`() { + val type = ConfigurationType.DATABASE_PASSWORD + val configuration = configuration( + type = type, + content = "securepassword".encrypt(type.key, securityProperties.configSalt!!) + ) + + every { configurationSource.get(type) } returns configuration + + val found = service.get(type) + + assertTrue { found is SecureConfiguration } + } + + @Test + fun `getContent(type) returns configuration content`() { + val type = ConfigurationType.INSTANCE_NAME + val configuration = configuration( + type = type, + content = "content" + ) + + every { service.get(type) } returns configuration + + val found = service.getContent(type) + + assertEquals(configuration.content, found) + } + + @Test + fun `getContent(type) throws UnsupportedOperationException when configuration is secure`() { + val type = ConfigurationType.DATABASE_PASSWORD + val configuration = secureConfiguration(type) + + every { service.get(type) } returns configuration + + assertThrows { service.getContent(type) } + } + + @Test + fun `getSecure(type) returns decrypted configuration content`() { val type = ConfigurationType.DATABASE_PASSWORD val content = "securepassword" val configuration = configuration( @@ -175,9 +228,67 @@ class ConfigurationServiceTest { every { configurationSource.get(type) } returns configuration - val found = service.get(type) + val found = service.getSecure(type) - assertEquals(content, found.content) + assertEquals(content, found) + } + + @Test + fun `getSecure(type) throws UnsupportedOperationException when configuration is not secure`() { + val type = ConfigurationType.INSTANCE_NAME + + assertThrows { service.getSecure(type) } + } + + private fun getConfiguredImageTest( + configurationType: ConfigurationType, + imageSet: Boolean, + test: (Resource) -> Unit + ) { + val resource = mockk() + val configuration = configuration(configurationType, imageSet.toString()) + val imageService = if (imageSet) fileService else resourceFileService + + every { service.get(configurationType) } returns configuration + every { imageService.read(any()) } returns resource + + test(resource) + } + + @Test + fun `getConfiguredIcon() gets icon from resources when INSTANCE_ICON_SET configuration is false`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_ICON_SET, false) { resource -> + val found = service.getConfiguredIcon() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredIcon() gets icon from files when INSTANCE_ICON_SET configuration is true`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_ICON_SET, true) { resource -> + val found = service.getConfiguredIcon() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredLogo() gets logo from resources when INSTANCE_LOGO_SET is false`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_LOGO_SET, false) { resource -> + val found = service.getConfiguredLogo() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredLogo() gets logo from files when INSTANCE_LOGO_SET is true`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_LOGO_SET, true) { resource -> + val found = service.getConfiguredLogo() + + assertEquals(resource, found) + } } @Test @@ -197,7 +308,7 @@ class ConfigurationServiceTest { fun `set(configuration) encrypts secure configurations`() { val type = ConfigurationType.DATABASE_PASSWORD val content = "securepassword" - val encryptedContent =content.encrypt(type.key, securityProperties.configSalt!!) + val encryptedContent = content.encrypt(type.key, securityProperties.configSalt!!) val configuration = configuration(type = type, content = content) mockkStatic(String::encrypt) @@ -213,4 +324,65 @@ class ConfigurationServiceTest { }) } } + + private fun setConfiguredImageTest(test: (MultipartFile) -> Unit) { + val file = mockk() + + every { service.set(any()) } just runs + every { fileService.write(any(), any(), any()) } just runs + + test(file) + } + + @Test + fun `setConfiguredIcon() sets icon in files`() { + setConfiguredImageTest { file -> + service.setConfiguredIcon(file) + + verify { + fileService.write(file, any(), true) + } + } + } + + @Test + fun `setConfiguredIcon() sets INSTANCE_ICON_SET configuration to true`() { + val type = ConfigurationType.INSTANCE_ICON_SET + + setConfiguredImageTest { file -> + service.setConfiguredIcon(file) + + verify { + service.set(match { + it.key == type.key && it.content == true.toString() + }) + } + } + } + + @Test + fun `setConfiguredLogo() sets logo in files`() { + setConfiguredImageTest { file -> + service.setConfiguredLogo(file) + + verify { + fileService.write(file, any(), true) + } + } + } + + @Test + fun `setConfiguredLogo() sets INSTANCE_LOGO_SET configuration to true`() { + val type = ConfigurationType.INSTANCE_LOGO_SET + + setConfiguredImageTest { file -> + service.setConfiguredLogo(file) + + verify { + service.set(match { + it.key == type.key && it.content == true.toString() + }) + } + } + } } diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt new file mode 100644 index 0000000..8a0a241 --- /dev/null +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt @@ -0,0 +1,99 @@ +package dev.fyloz.colorrecipesexplorer.service + +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.user +import dev.fyloz.colorrecipesexplorer.service.users.JwtServiceImpl +import dev.fyloz.colorrecipesexplorer.service.users.jwtClaimUser +import dev.fyloz.colorrecipesexplorer.utils.base64encode +import dev.fyloz.colorrecipesexplorer.utils.isAround +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.jackson.io.JacksonDeserializer +import io.mockk.spyk +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.time.Instant +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class JwtServiceTest { + private val objectMapper = jacksonObjectMapper() + private val securityProperties = CreSecurityProperties().apply { + jwtSecret = "XRRm7OflmFuCrOB2Xvmfsercih9DCKom" + jwtDuration = 1000000L + } + private val jwtParser by lazy { + Jwts.parserBuilder() + .deserializeJsonWith(JacksonDeserializer>(objectMapper)) + .setSigningKey(securityProperties.jwtSecret.base64encode()) + .build() + } + + private val jwtService = spyk(JwtServiceImpl(objectMapper, securityProperties)) + + private val user = user() + private val userOutputDto = user.toOutputDto() + + // buildJwt() + + private fun withParsedUserOutputDto(jwt: String, test: (UserOutputDto) -> Unit) { + val serializedUser = jwtParser.parseClaimsJws(jwt) + .body.get(jwtClaimUser, String::class.java) + + test(objectMapper.readValue(serializedUser)) + } + + @Test + fun `buildJwt(userDetails) returns jwt string with valid user`() { + val userDetails = UserDetails(user) + + val builtJwt = jwtService.buildJwt(userDetails) + + withParsedUserOutputDto(builtJwt) { parsedUser -> + assertEquals(user.toOutputDto(), parsedUser) + } + } + + @Test + fun `buildJwt() returns jwt string with valid user`() { + val builtJwt = jwtService.buildJwt(user) + + withParsedUserOutputDto(builtJwt) { parsedUser -> + assertEquals(user.toOutputDto(), parsedUser) + } + } + + @Test + fun `buildJwt() returns jwt string with valid subject`() { + val builtJwt = jwtService.buildJwt(user) + val jwtSubject = jwtParser.parseClaimsJws(builtJwt).body.subject + + assertEquals(user.id.toString(), jwtSubject) + } + + @Test + fun `buildJwt() returns jwt with valid expiration date`() { + val jwtExpectedExpirationDate = Instant.now().plusSeconds(securityProperties.jwtDuration) + + val builtJwt = jwtService.buildJwt(user) + val jwtExpiration = jwtParser.parseClaimsJws(builtJwt) + .body.expiration.toInstant() + + // Check if it's between 1 second + assertTrue { jwtExpiration.isAround(jwtExpectedExpirationDate) } + } + + // parseJwt() + + @Test + fun `parseJwt() returns expected user`() { + val jwt = jwtService.buildJwt(user) + val parsedUser = jwtService.parseJwt(jwt) + + assertEquals(userOutputDto, parsedUser) + } +} diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt index 0962323..be7c476 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt @@ -4,7 +4,7 @@ import com.nhaarman.mockitokotlin2.* import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository -import dev.fyloz.colorrecipesexplorer.service.FileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @@ -21,7 +21,7 @@ class MaterialServiceTest : private val recipeService: RecipeService = mock() private val mixService: MixService = mock() private val materialTypeService: MaterialTypeService = mock() - private val fileService: FileService = mock() + private val fileService: WriteableFileService = mock() override val service: MaterialService = spy(MaterialServiceImpl(repository, recipeService, mixService, materialTypeService, fileService, mock())) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt index a9debc1..707da9f 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt @@ -87,9 +87,9 @@ class MixServiceTest : AbstractExternalModelServiceTest Unit + scope: MixUpdateDtoTestScope = MixUpdateDtoTestScope(), + sharedMixType: Boolean = false, + op: MixUpdateDtoTestScope.() -> Unit ) { with(scope) { doReturn(true).whenever(service).existsById(mix.id!!) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt index 58a1193..ede2dce 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt @@ -6,6 +6,8 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.model.account.group import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test @@ -80,9 +82,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns false when the approbation date of the given recipe is within the configured period`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = LocalDate.now()) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) @@ -93,9 +95,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns true when the approbation date of the given recipe is outside the configured period`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = LocalDate.now().minus(period).minusMonths(1)) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) @@ -106,9 +108,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns null when the given recipe as no approbation date`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = null) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) @@ -263,7 +265,7 @@ class RecipeServiceTest : } private class RecipeImageServiceTestContext { - val fileService = mockk { + val fileService = mockk { every { write(any(), any(), any()) } just Runs every { delete(any()) } just Runs } diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt index b0f9c73..31933b0 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt @@ -1,8 +1,11 @@ package dev.fyloz.colorrecipesexplorer.service import com.nhaarman.mockitokotlin2.* -import dev.fyloz.colorrecipesexplorer.model.* +import dev.fyloz.colorrecipesexplorer.model.RecipeGroupInformation +import dev.fyloz.colorrecipesexplorer.model.RecipeStep import dev.fyloz.colorrecipesexplorer.model.account.group +import dev.fyloz.colorrecipesexplorer.model.recipeGroupInformation +import dev.fyloz.colorrecipesexplorer.model.recipeStep import dev.fyloz.colorrecipesexplorer.repository.RecipeStepRepository import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt index c913d45..51ef288 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt @@ -1,11 +1,10 @@ package dev.fyloz.colorrecipesexplorer.service -import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository -import dev.fyloz.colorrecipesexplorer.service.* import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.PdfDocument import dev.fyloz.colorrecipesexplorer.utils.toByteArrayResource import io.mockk.* @@ -16,10 +15,9 @@ import kotlin.test.assertEquals private class TouchUpKitServiceTestContext { val touchUpKitRepository = mockk() - val fileService = mockk { + val fileService = mockk { every { write(any(), any(), any()) } just Runs } - val creProperties = mockk() val configService = mockk(relaxed = true) val touchUpKitService = spyk(TouchUpKitServiceImpl(fileService, configService, touchUpKitRepository)) val pdfDocumentData = mockk() @@ -131,10 +129,7 @@ class TouchUpKitServiceTest { this.setCachePdf(false) private fun TouchUpKitServiceTestContext.setCachePdf(enabled: Boolean) { - every { configService.get(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns configuration( - type = ConfigurationType.TOUCH_UP_KIT_CACHE_PDF, - enabled.toString() - ) + every { configService.getContent(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns enabled.toString() } private fun test(test: TouchUpKitServiceTestContext.() -> Unit) { diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt similarity index 99% rename from src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt rename to src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt index 8c4ca7a..936bf47 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt @@ -1,4 +1,4 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.files import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import io.mockk.* diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt new file mode 100644 index 0000000..5c0d6ff --- /dev/null +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt @@ -0,0 +1,114 @@ +package dev.fyloz.colorrecipesexplorer.service.files + +import io.mockk.clearAllMocks +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.springframework.core.io.Resource +import org.springframework.core.io.ResourceLoader +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ResourceFileServiceTest { + private val resourceLoader = mockk() + + private val service = spyk(ResourceFileService(resourceLoader)) + + @AfterEach + fun afterEach() { + clearAllMocks() + } + + private fun existsTest(shouldExists: Boolean, test: (String) -> Unit) { + val path = "unit_test_resource" + with(service) { + every { path.fullPath() } returns mockk { + every { resource } returns mockk { + every { exists() } returns shouldExists + } + } + + test(path) + } + } + + @Test + fun `exists() returns true when a resource exists at the given path`() { + existsTest(true) { path -> + val found = service.exists(path) + + assertTrue { found } + } + } + + @Test + fun `exists() returns false when no resource exists at the given path`() { + existsTest(false) { path -> + val found = service.exists(path) + + assertFalse { found } + } + } + + private fun readTest(shouldExists: Boolean, test: (Resource, String) -> Unit) { + val mockResource = mockk { + every { exists() } returns shouldExists + } + val path = "unit_test_path" + with(service) { + every { path.fullPath() } returns mockk { + every { resource } returns mockResource + } + + test(mockResource, path) + } + } + + @Test + fun `read() returns the resource at the given path`() { + readTest(true) { resource, path -> + val found = service.read(path) + + assertEquals(resource, found) + } + } + + @Test + fun `read() throws FileNotFoundException when no resource exists at the given path`() { + readTest(false) { _, path -> + assertThrows { + service.read(path) + } + } + } + + @Test + fun `fullPath() returns the given path in the classpath`() { + val path = "unit_test_path" + val expectedPath = "classpath:$path" + + with(service) { + val found = path.fullPath() + + assertEquals(expectedPath, found.path) + } + } + + @Test + fun `resource returns a resource for the given path`() { + val filePath = FilePath("classpath:unit_test_path") + val resource = mockk() + + every { resourceLoader.getResource(filePath.path) } returns resource + + with(service) { + val found = filePath.resource + + assertEquals(resource, found) + } + } +} diff --git a/todo.txt b/todo.txt deleted file mode 100644 index e940649..0000000 --- a/todo.txt +++ /dev/null @@ -1,15 +0,0 @@ -== Icônes pour recettes non-approuvés / quantité faible == -== Texte SIMDUT inexistant (fiche signalitique) pour les matériaux == - - - -== Comptes == -No employé - Permissions - Employés - - - -== Kits de retouche == -No Job - No Dossier - Qté - Description - Case à cocher - Note - Bouton compléter si tout est coché/imprimé ? - -Enregistrer localdatetime/personne pendant une certaine durée