Merge pull request 'develop' (#22) from develop into master
continuous-integration/drone/push Build is passing Details

Reviewed-on: #22
This commit is contained in:
William Nolin 2021-12-14 23:59:35 -05:00
commit 8a513a71e3
49 changed files with 1476 additions and 699 deletions

11
.dockerignore Normal file
View File

@ -0,0 +1,11 @@
.gradle
.idea
**/build
**/data
**/gradle
**/logs
.gitignore
.gitlab-ci.yml
docker-compose.yml
Dockerfile
gradlew**

View File

@ -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 kind: pipeline
name: default name: default
type: docker 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: steps:
- name: test - name: gradle-test
image: gradle:7.1-jdk11 image: *gradle-image
commands: commands:
- gradle test - gradle test
when:
branch: develop
- name: build - name: set-docker-tags-latest
image: gradle:7.1-jdk11 image: *alpine-image
environment:
<<: *environment
commands: commands:
- gradle bootJar -Pversion=$CRE_VERSION - echo -n "latest" > .tags
- mv build/libs/ColorRecipesExplorer-$CRE_VERSION.jar $CRE_ARTIFACT_NAME.jar
- echo -n "latest,$CRE_VERSION" > .tags
when: when:
branch: branch: develop
- master event:
events: [ push, tag ] exclude:
- pull_request
- name: containerize - name: set-docker-tags-release
image: plugins/docker image: *alpine-image
settings: environment:
build_args: <<: *environment
- JAVA_VERSION=11 commands:
repo: registry.fyloz.dev:5443/colorrecipesexplorer/backend - echo -n "latest-release,$CRE_RELEASE" > .tags
when: when:
branch: branch: release/**
- master
events: [ push, tag ] - 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 - name: deploy
image: alpine:latest image: alpine:latest
environment: environment:
<<: *environment
CRE_REGISTRY_IMAGE: *docker-registry-repo
DEPLOY_SERVER: DEPLOY_SERVER:
from_secret: deploy_server from_secret: deploy_server
DEPLOY_SERVER_USERNAME: DEPLOY_SERVER_USERNAME:
@ -47,7 +89,7 @@ steps:
from_secret: deploy_server_ssh_port from_secret: deploy_server_ssh_port
DEPLOY_SERVER_SSH_KEY: DEPLOY_SERVER_SSH_KEY:
from_secret: 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_SPRING_PROFILES: mysql,rest
DEPLOY_DATA_VOLUME: /var/cre/data DEPLOY_DATA_VOLUME: /var/cre/data
DEPLOY_CONFIG_VOLUME: /var/cre/config DEPLOY_CONFIG_VOLUME: /var/cre/config
@ -62,11 +104,15 @@ steps:
- ssh-keyscan -p $DEPLOY_SERVER_SSH_PORT -H $DEPLOY_SERVER >> ~/.ssh/known_hosts - 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' - '[[ -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 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 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/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 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: when:
branch: branch: release/**
- master
events: [ push, tag ] trigger:
branch:
- develop
- release/**
- master

View File

@ -1,11 +1,21 @@
ARG GRADLE_VERSION=7.1
ARG JAVA_VERSION=11 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 FROM alpine:latest
COPY $CRE_ARTIFACT_NAME.jar ColorRecipesExplorer.jar 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 ARG CRE_PORT=9090
EXPOSE $CRE_PORT EXPOSE $CRE_PORT
@ -16,7 +26,7 @@ ENV spring_datasource_url=jdbc:h2:mem:cre
ENV spring_datasource_username=root ENV spring_datasource_username=root
ENV spring_datasource_password=pass ENV spring_datasource_password=pass
VOLUME /usr/bin/cre/data VOLUME /usr/bin/data
VOLUME /usr/bin/cre/config VOLUME /usr/bin/config
ENTRYPOINT ["java", "-jar", "ColorRecipesExplorer.jar"] ENTRYPOINT ["java", "-jar", "ColorRecipesExplorer.jar"]

View File

@ -2,13 +2,13 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
group = "dev.fyloz.colorrecipesexplorer" group = "dev.fyloz.colorrecipesexplorer"
val kotlinVersion = "1.5.21" val kotlinVersion = "1.6.0"
val springBootVersion = "2.3.4.RELEASE" val springBootVersion = "2.5.6"
plugins { plugins {
// Outer scope variables can't be accessed in the plugins section, so we have to redefine them here // Outer scope variables can't be accessed in the plugins section, so we have to redefine them here
val kotlinVersion = "1.5.21" val kotlinVersion = "1.6.0"
val springBootVersion = "2.3.4.RELEASE" val springBootVersion = "2.5.6"
id("java") id("java")
id("org.jetbrains.kotlin.jvm") version kotlinVersion id("org.jetbrains.kotlin.jvm") version kotlinVersion
@ -22,7 +22,7 @@ repositories {
mavenCentral() mavenCentral()
maven { 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(platform("org.jetbrains.kotlin:kotlin-bom:${kotlinVersion}"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
implementation("org.jetbrains.kotlin:kotlin-reflect:${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("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.poi:poi-ooxml:4.1.0")
implementation("org.apache.pdfbox:pdfbox:2.0.4") 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-data-jpa:${springBootVersion}")
implementation("org.springframework.boot:spring-boot-starter-jdbc:${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-configuration-processor:${springBootVersion}")
implementation("org.springframework.boot:spring-boot-devtools:${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("org.mockito:mockito-inline:3.11.2")
testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.2") testImplementation("io.mockk:mockk:1.12.0")
testImplementation("io.mockk:mockk:1.10.6")
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}") testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}")
testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}") testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}")
@ -58,8 +61,6 @@ dependencies {
runtimeOnly("mysql:mysql-connector-java:8.0.22") runtimeOnly("mysql:mysql-connector-java:8.0.22")
runtimeOnly("org.postgresql:postgresql:42.2.16") runtimeOnly("org.postgresql:postgresql:42.2.16")
runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11") runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11")
implementation("org.springframework.cloud:spring-cloud-starter:2.2.8.RELEASE")
} }
springBoot { springBoot {

View File

@ -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

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists 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 zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

269
gradlew vendored
View File

@ -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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with 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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" 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. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 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." location of your Java installation."
fi fi
else 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. 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 Please set the JAVA_HOME variable in your environment to match the
@ -106,80 +140,95 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
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" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --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 # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 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" "$@" exec "$JAVACMD" "$@"

View File

@ -3,23 +3,24 @@ package dev.fyloz.colorrecipesexplorer
import dev.fyloz.colorrecipesexplorer.databasemanager.CreDatabase import dev.fyloz.colorrecipesexplorer.databasemanager.CreDatabase
import dev.fyloz.colorrecipesexplorer.databasemanager.databaseContext import dev.fyloz.colorrecipesexplorer.databasemanager.databaseContext
import dev.fyloz.colorrecipesexplorer.databasemanager.databaseUpdaterProperties import dev.fyloz.colorrecipesexplorer.databasemanager.databaseUpdaterProperties
import dev.fyloz.colorrecipesexplorer.model.Configuration
import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.ConfigurationType
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService
import org.slf4j.Logger import org.slf4j.Logger
import org.springframework.boot.jdbc.DataSourceBuilder import org.springframework.boot.jdbc.DataSourceBuilder
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn import org.springframework.context.annotation.DependsOn
import org.springframework.context.annotation.Profile import org.springframework.context.annotation.Profile
import org.springframework.core.env.ConfigurableEnvironment import org.springframework.core.env.ConfigurableEnvironment
import javax.sql.DataSource import javax.sql.DataSource
import org.springframework.context.annotation.Configuration as SpringConfiguration
const val SUPPORTED_DATABASE_VERSION = 5 const val SUPPORTED_DATABASE_VERSION = 5
const val ENV_VAR_ENABLE_DATABASE_UPDATE_NAME = "CRE_ENABLE_DB_UPDATE" const val ENV_VAR_ENABLE_DATABASE_UPDATE_NAME = "CRE_ENABLE_DB_UPDATE"
val DATABASE_NAME_REGEX = Regex("(\\w+)$") val DATABASE_NAME_REGEX = Regex("(\\w+)$")
@Profile("!emergency") @Profile("!emergency")
@Configuration @SpringConfiguration
@DependsOn("configurationsInitializer", "configurationService") @DependsOn("configurationsInitializer", "configurationService")
class DataSourceConfiguration { class DataSourceConfiguration {
@Bean(name = ["dataSource"]) @Bean(name = ["dataSource"])
@ -29,7 +30,8 @@ class DataSourceConfiguration {
configurationService: ConfigurationService configurationService: ConfigurationService
): DataSource { ): DataSource {
fun getConfiguration(type: ConfigurationType) = 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 databaseUrl = "jdbc:" + getConfiguration(ConfigurationType.DATABASE_URL)
val databaseUsername = getConfiguration(ConfigurationType.DATABASE_USER) val databaseUsername = getConfiguration(ConfigurationType.DATABASE_USER)

View File

@ -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

View File

@ -3,32 +3,33 @@ package dev.fyloz.colorrecipesexplorer.config.security
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties
import dev.fyloz.colorrecipesexplorer.exception.NotFoundException 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.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.ExpiredJwtException
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder 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.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import org.springframework.util.Assert
import org.springframework.web.util.WebUtils import org.springframework.web.util.WebUtils
import java.util.*
import javax.servlet.FilterChain import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse
const val authorizationCookieName = "Authorization" const val authorizationCookieName = "Authorization"
const val defaultGroupCookieName = "Default-Group" const val defaultGroupCookieName = "Default-Group"
val blacklistedJwtTokens = mutableListOf<String>() val blacklistedJwtTokens = mutableListOf<String>() // Not working, move to a cache or something
class JwtAuthenticationFilter( class JwtAuthenticationFilter(
private val authManager: AuthenticationManager, private val authManager: AuthenticationManager,
private val securityConfigurationProperties: CreSecurityProperties, private val jwtService: JwtService,
private val securityProperties: CreSecurityProperties,
private val updateUserLoginTime: (Long) -> Unit private val updateUserLoginTime: (Long) -> Unit
) : UsernamePasswordAuthenticationFilter() { ) : UsernamePasswordAuthenticationFilter() {
private var debugMode = false private var debugMode = false
@ -47,38 +48,28 @@ class JwtAuthenticationFilter(
request: HttpServletRequest, request: HttpServletRequest,
response: HttpServletResponse, response: HttpServletResponse,
chain: FilterChain, chain: FilterChain,
authResult: Authentication auth: Authentication
) { ) {
val jwtSecret = securityConfigurationProperties.jwtSecret val userDetails = auth.principal as UserDetails
val jwtDuration = securityConfigurationProperties.jwtDuration val token = jwtService.buildJwt(userDetails)
Assert.notNull(jwtSecret, "No JWT secret has been defined.")
Assert.notNull(jwtDuration, "No JWT duration has been defined.") response.addHeader("Access-Control-Expose-Headers", authorizationCookieName)
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
)
response.addHeader(authorizationCookieName, "Bearer $token") 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( class JwtAuthorizationFilter(
private val securityConfigurationProperties: CreSecurityProperties, private val jwtService: JwtService,
authenticationManager: AuthenticationManager, authenticationManager: AuthenticationManager,
private val loadUserById: (Long) -> UserDetails private val userDetailsService: UserDetailsService
) : BasicAuthenticationFilter(authenticationManager) { ) : BasicAuthenticationFilter(authenticationManager) {
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
fun tryLoginFromBearer(): Boolean { fun tryLoginFromBearer(): Boolean {
@ -112,24 +103,24 @@ class JwtAuthorizationFilter(
} }
private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? {
val jwtSecret = securityConfigurationProperties.jwtSecret
Assert.notNull(jwtSecret, "No JWT secret has been defined.")
return try { return try {
val userId = Jwts.parser() val user = jwtService.parseJwt(token.replace("Bearer", ""))
.setSigningKey(jwtSecret.toByteArray()) getAuthenticationToken(user)
.parseClaimsJws(token.replace("Bearer", ""))
.body
.subject
if (userId != null) getAuthenticationToken(userId) else null
} catch (_: ExpiredJwtException) { } catch (_: ExpiredJwtException) {
null null
} }
} }
private fun getAuthenticationToken(userId: String): UsernamePasswordAuthenticationToken? = try { private fun getAuthenticationToken(user: UserOutputDto) =
val userDetails = loadUserById(userId.toLong()) 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) UsernamePasswordAuthenticationToken(userDetails.username, null, userDetails.authorities)
} catch (_: NotFoundException) { } catch (_: NotFoundException) {
null null
} }
private fun getAuthenticationToken(userId: String) =
getAuthenticationToken(userId.toLong())
} }

View File

@ -4,11 +4,15 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties
import dev.fyloz.colorrecipesexplorer.emergencyMode import dev.fyloz.colorrecipesexplorer.emergencyMode
import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.Permission
import dev.fyloz.colorrecipesexplorer.model.account.User import dev.fyloz.colorrecipesexplorer.model.account.User
import dev.fyloz.colorrecipesexplorer.service.CreUserDetailsService import dev.fyloz.colorrecipesexplorer.service.users.JwtService
import dev.fyloz.colorrecipesexplorer.service.UserService import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService
import dev.fyloz.colorrecipesexplorer.service.users.UserService
import org.slf4j.Logger import org.slf4j.Logger
import org.springframework.boot.context.properties.EnableConfigurationProperties 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.core.env.Environment
import org.springframework.http.HttpMethod import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder 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.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.core.AuthenticationException 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.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.stereotype.Component import org.springframework.stereotype.Component
import org.springframework.util.Assert
import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import javax.annotation.PostConstruct import javax.annotation.PostConstruct
import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse
import org.springframework.security.core.userdetails.User as SpringUser
@Configuration private const val angularDevServerOrigin = "http://localhost:4200"
@Profile("!emergency") private const val rootUserFirstName = "Root"
@EnableWebSecurity private const val rootUserLastName = "User"
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(CreSecurityProperties::class) abstract class BaseSecurityConfig(
class SecurityConfig( private val userDetailsService: UserDetailsService,
private val securityProperties: CreSecurityProperties, private val jwtService: JwtService,
@Lazy private val userDetailsService: CreUserDetailsService,
@Lazy private val userService: UserService,
private val environment: Environment, private val environment: Environment,
private val logger: Logger protected val logger: Logger,
protected val securityProperties: CreSecurityProperties
) : WebSecurityConfigurerAdapter() { ) : WebSecurityConfigurerAdapter() {
protected val passwordEncoder = BCryptPasswordEncoder()
var debugMode = false var debugMode = false
override fun configure(authBuilder: AuthenticationManagerBuilder) { @Bean
authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) open fun passwordEncoder() =
} passwordEncoder
@Bean @Bean
fun passwordEncoder() = open fun corsConfigurationSource() =
getPasswordEncoder() UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/**", CorsConfiguration().apply {
@Bean allowedOrigins = listOf(angularDevServerOrigin)
fun corsConfigurationSource() = allowedMethods = listOf(
getCorsConfigurationSource() HttpMethod.GET.name,
HttpMethod.POST.name,
@PostConstruct HttpMethod.PUT.name,
fun initWebSecurity() { HttpMethod.DELETE.name,
if (emergencyMode) { HttpMethod.OPTIONS.name,
logger.error("Emergency mode is enabled, system users will not be created") HttpMethod.HEAD.name
return )
allowCredentials = true
}.applyPermitDefaultValues())
} }
debugMode = "debug" in environment.activeProfiles override fun configure(authBuilder: AuthenticationManagerBuilder) {
if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!") authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder)
// Create Root user
assertRootUserNotNull(securityProperties)
createSystemUser(
securityProperties.root!!,
userService,
passwordEncoder(),
"Root",
"User",
listOf(Permission.ADMIN)
)
} }
override fun configure(http: HttpSecurity) { override fun configure(http: HttpSecurity) {
@ -87,29 +76,84 @@ class SecurityConfig(
.and() .and()
.csrf().disable() .csrf().disable()
.addFilter( .addFilter(
JwtAuthenticationFilter(authenticationManager(), securityProperties) { JwtAuthenticationFilter(
userService.updateLastLoginTime(it) authenticationManager(),
} jwtService,
securityProperties,
this::updateUserLoginTime
)
) )
.addFilter( .addFilter(
JwtAuthorizationFilter(securityProperties, authenticationManager()) { JwtAuthorizationFilter(jwtService, authenticationManager(), userDetailsService)
userDetailsService.loadUserById(it, false)
}
) )
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .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) { if (debugMode) {
http.authorizeRequests()
.antMatchers("/api/login").permitAll()
.antMatchers("/api/logout").fullyAuthenticated()
.antMatchers("/api/user/current").fullyAuthenticated()
.anyRequest().fullyAuthenticated()
} else {
http http
.cors() .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") @Profile("emergency")
@EnableConfigurationProperties(CreSecurityProperties::class) @EnableConfigurationProperties(CreSecurityProperties::class)
class EmergencySecurityConfig( class EmergencySecurityConfig(
private val securityProperties: CreSecurityProperties, userDetailsService: UserDetailsService,
private val environment: Environment jwtService: JwtService,
) : WebSecurityConfigurerAdapter() { environment: Environment,
private val rootUserRole = Permission.ADMIN.name logger: Logger,
securityProperties: CreSecurityProperties
) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) {
init { init {
emergencyMode = true 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 @Component
@ -190,50 +182,5 @@ class RestAuthenticationEntryPoint : AuthenticationEntryPoint {
) = response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized") ) = response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")
} }
fun createSystemUser( private class InvalidSystemUserException(userType: String, message: String) :
credentials: CreSecurityProperties.SystemUserCredentials, RuntimeException("Invalid $userType user: $message")
userService: UserService,
passwordEncoder: PasswordEncoder,
firstName: String,
lastName: String,
permissions: List<Permission>
) {
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")
}

View File

@ -12,20 +12,25 @@ import javax.persistence.Id
import javax.persistence.Table import javax.persistence.Table
import javax.validation.constraints.NotBlank import javax.validation.constraints.NotBlank
data class Configuration( sealed class ConfigurationBase(
@JsonIgnore @JsonIgnore
val type: ConfigurationType, val type: ConfigurationType,
val content: String,
val lastUpdated: LocalDateTime val lastUpdated: LocalDateTime
) { ) {
val key = type.key val key = type.key
val requireRestart = type.requireRestart val requireRestart = type.requireRestart
val editable = !type.computed val editable = !type.computed
}
class Configuration(type: ConfigurationType, val content: String, lastUpdated: LocalDateTime) :
ConfigurationBase(type, lastUpdated) {
fun toEntity() = fun toEntity() =
ConfigurationEntity(key, content, lastUpdated) ConfigurationEntity(key, content, lastUpdated)
} }
class SecureConfiguration(type: ConfigurationType, lastUpdated: LocalDateTime) :
ConfigurationBase(type, lastUpdated)
@Entity @Entity
@Table(name = "configuration") @Table(name = "configuration")
data class ConfigurationEntity( data class ConfigurationEntity(
@ -76,6 +81,15 @@ fun configuration(
configuration(type = key.toConfigurationType(), content = content) 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( enum class ConfigurationType(
val key: String, val key: String,
val defaultContent: Any? = null, val defaultContent: Any? = null,
@ -86,8 +100,8 @@ enum class ConfigurationType(
val secure: Boolean = false val secure: Boolean = false
) { ) {
INSTANCE_NAME("instance.name", defaultContent = "Color Recipes Explorer", public = true), INSTANCE_NAME("instance.name", defaultContent = "Color Recipes Explorer", public = true),
INSTANCE_LOGO_PATH("instance.logo.path", defaultContent = "images/logo", public = true), INSTANCE_LOGO_SET("instance.logo.set", defaultContent = false, public = true),
INSTANCE_ICON_PATH("instance.icon.path", defaultContent = "images/icon", public = true), INSTANCE_ICON_SET("instance.icon.set", defaultContent = false, public = true),
INSTANCE_URL("instance.url", "http://localhost:9090", public = true), INSTANCE_URL("instance.url", "http://localhost:9090", public = true),
DATABASE_URL("database.url", defaultContent = "mysql://localhost/cre", file = true, requireRestart = 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) : class InvalidImageConfigurationException(val type: ConfigurationType) :
RestException( RestException(
"invalid-configuration-image", "invalid-configuration-image",
"Invalid image configuration", "Invalid image configuration",
HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST,
"The configuration with the key '${type.key}' does not accept images as content", "The configuration with the key '${type.key}' does not accept images as content",
mapOf( mapOf(
"key" to type.key "key" to type.key
) )
) )
class ConfigurationNotSetException(val type: ConfigurationType) : class ConfigurationNotSetException(val type: ConfigurationType) :
RestException( RestException(

View File

@ -1,12 +1,12 @@
package dev.fyloz.colorrecipesexplorer.model.account package dev.fyloz.colorrecipesexplorer.model.account
import dev.fyloz.colorrecipesexplorer.SpringUserDetails
import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException
import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException
import dev.fyloz.colorrecipesexplorer.model.EntityDto import dev.fyloz.colorrecipesexplorer.model.EntityDto
import dev.fyloz.colorrecipesexplorer.model.Model import dev.fyloz.colorrecipesexplorer.model.Model
import org.hibernate.annotations.Fetch import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode import org.hibernate.annotations.FetchMode
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder
import java.time.LocalDateTime import java.time.LocalDateTime
@ -59,9 +59,6 @@ data class User(
.apply { .apply {
if (group != null) this.addAll(group!!.flatPermissions) if (group != null) this.addAll(group!!.flatPermissions)
} }
val authorities: Set<GrantedAuthority>
get() = flatPermissions.map { it.toAuthority() }.toMutableSet()
} }
open class UserSaveDto( open class UserSaveDto(
@ -110,13 +107,23 @@ data class UserOutputDto(
data class UserLoginRequest(val id: Long, val password: String) 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 ==== // ==== DSL ====
fun user( fun user(
passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(),
id: Long = 0L, id: Long = 0L,
firstName: String = "firstName", firstName: String = "firstName",
lastName: String = "lastName", lastName: String = "lastName",
password: String = passwordEncoder.encode("password"), password: String = "password",
isDefaultGroupUser: Boolean = false, isDefaultGroupUser: Boolean = false,
isSystemUser: Boolean = false, isSystemUser: Boolean = false,
group: Group? = null, group: Group? = null,
@ -135,6 +142,30 @@ fun user(
lastLoginTime lastLoginTime
).apply(op) ).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<Permission> = 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( fun userSaveDto(
passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(),
id: Long = 0L, id: Long = 0L,
@ -155,6 +186,21 @@ fun userUpdateDto(
op: UserUpdateDto.() -> Unit = {} op: UserUpdateDto.() -> Unit = {}
) = UserUpdateDto(id, firstName, lastName, groupId, permissions).apply(op) ) = UserUpdateDto(id, firstName, lastName, groupId, permissions).apply(op)
// ==== Extensions ====
fun Set<Permission>.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 ==== // ==== Exceptions ====
private const val USER_NOT_FOUND_EXCEPTION_TITLE = "User not found" private const val USER_NOT_FOUND_EXCEPTION_TITLE = "User not found"
private const val USER_ALREADY_EXISTS_EXCEPTION_TITLE = "User already exists" private const val USER_ALREADY_EXISTS_EXCEPTION_TITLE = "User already exists"

View File

@ -3,13 +3,12 @@ package dev.fyloz.colorrecipesexplorer.rest
import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeEditUsers import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeEditUsers
import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeViewUsers import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeViewUsers
import dev.fyloz.colorrecipesexplorer.model.account.* import dev.fyloz.colorrecipesexplorer.model.account.*
import dev.fyloz.colorrecipesexplorer.service.UserService import dev.fyloz.colorrecipesexplorer.service.users.GroupService
import dev.fyloz.colorrecipesexplorer.service.GroupService import dev.fyloz.colorrecipesexplorer.service.users.UserService
import org.springframework.context.annotation.Profile import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import java.security.Principal
import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse
import javax.validation.Valid import javax.validation.Valid
@ -31,21 +30,6 @@ class UserController(private val userService: UserService) {
fun getById(@PathVariable id: Long) = fun getById(@PathVariable id: Long) =
ok(userService.getByIdForOutput(id)) 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 @PostMapping
@PreAuthorizeEditUsers @PreAuthorizeEditUsers
fun save(@Valid @RequestBody user: UserSaveDto) = fun save(@Valid @RequestBody user: UserSaveDto) =
@ -132,6 +116,12 @@ class GroupsController(
getRequestDefaultGroup(request).toOutput() getRequestDefaultGroup(request).toOutput()
}) })
@GetMapping("currentuser")
fun getCurrentGroupUser(request: HttpServletRequest) =
ok(with(groupService.getRequestDefaultGroup(request)) {
userService.getDefaultGroupUser(this).toOutputDto()
})
@PostMapping @PostMapping
@PreAuthorizeEditUsers @PreAuthorizeEditUsers
fun save(@Valid @RequestBody group: GroupSaveDto) = fun save(@Valid @RequestBody group: GroupSaveDto) =
@ -161,6 +151,7 @@ class GroupsController(
@Profile("!emergency") @Profile("!emergency")
class LogoutController(private val userService: UserService) { class LogoutController(private val userService: UserService) {
@GetMapping("logout") @GetMapping("logout")
@PreAuthorize("isFullyAuthenticated()")
fun logout(request: HttpServletRequest) = fun logout(request: HttpServletRequest) =
ok { ok {
userService.logout(request) userService.logout(request)

View File

@ -1,12 +1,13 @@
package dev.fyloz.colorrecipesexplorer.rest 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.ConfigurationDto
import dev.fyloz.colorrecipesexplorer.model.ConfigurationImageDto import dev.fyloz.colorrecipesexplorer.model.ConfigurationImageDto
import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.Permission
import dev.fyloz.colorrecipesexplorer.model.account.toAuthority import dev.fyloz.colorrecipesexplorer.model.account.toAuthority
import dev.fyloz.colorrecipesexplorer.restartApplication import dev.fyloz.colorrecipesexplorer.restartApplication
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService
import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.Authentication import org.springframework.security.core.Authentication
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
@ -20,13 +21,11 @@ class ConfigurationController(val configurationService: ConfigurationService) {
fun getAll(@RequestParam(required = false) keys: String?, authentication: Authentication?) = fun getAll(@RequestParam(required = false) keys: String?, authentication: Authentication?) =
ok(with(configurationService) { ok(with(configurationService) {
if (keys != null) getAll(keys) else getAll() if (keys != null) getAll(keys) else getAll()
}.filter { }.filter { authentication.hasAuthority(it) })
!it.type.secure && authentication.hasAuthority(it)
})
@GetMapping("{key}") @GetMapping("{key}")
fun get(@PathVariable key: String, authentication: Authentication?) = with(configurationService.get(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 @PutMapping
@ -35,20 +34,38 @@ class ConfigurationController(val configurationService: ConfigurationService) {
configurationService.set(configurations) 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") @PostMapping("restart")
@PreAuthorize("hasAuthority('ADMIN')") @PreAuthorize("hasAuthority('ADMIN')")
fun restart() = noContent { fun restart() = noContent {
restartApplication() 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 configuration.type.public -> true
this != null && Permission.ADMIN.toAuthority() in this.authorities -> true this != null && Permission.ADMIN.toAuthority() in this.authorities -> true
else -> false else -> false

View File

@ -2,8 +2,7 @@ package dev.fyloz.colorrecipesexplorer.rest
import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.ConfigurationType
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService
import dev.fyloz.colorrecipesexplorer.service.FileService import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService
import org.springframework.core.io.ByteArrayResource
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.access.prepost.PreAuthorize
@ -12,26 +11,18 @@ import org.springframework.web.multipart.MultipartFile
import java.net.URI import java.net.URI
const val FILE_CONTROLLER_PATH = "/api/file" const val FILE_CONTROLLER_PATH = "/api/file"
private const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE
@RestController @RestController
@RequestMapping(FILE_CONTROLLER_PATH) @RequestMapping(FILE_CONTROLLER_PATH)
class FileController( class FileController(
private val fileService: FileService, private val fileService: WriteableFileService,
private val configService: ConfigurationService private val configService: ConfigurationService
) { ) {
@GetMapping(produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE]) @GetMapping(produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE])
fun upload( fun upload(
@RequestParam path: String, @RequestParam path: String,
@RequestParam(required = false) mediaType: String? @RequestParam(required = false) mediaType: String?
): ResponseEntity<ByteArrayResource> { ) = okFile(fileService.read(path), mediaType)
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)
}
@PutMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @PutMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
@PreAuthorize("hasAnyAuthority('WRITE_FILE')") @PreAuthorize("hasAnyAuthority('WRITE_FILE')")
@ -46,17 +37,13 @@ class FileController(
@DeleteMapping @DeleteMapping
@PreAuthorize("hasAnyAuthority('WRITE_FILE')") @PreAuthorize("hasAnyAuthority('WRITE_FILE')")
fun delete(@RequestParam path: String): ResponseEntity<Void> { fun delete(@RequestParam path: String): ResponseEntity<Void> =
return noContent { noContent {
fileService.delete(path) fileService.delete(path)
} }
}
private fun created(path: String): ResponseEntity<Void> = private fun created(path: String): ResponseEntity<Void> =
ResponseEntity ResponseEntity
.created(URI.create("${configService.get(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=$path")) .created(URI.create("${configService.get(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=$path"))
.build() .build()
private fun getFileNameFromPath(path: String) =
path.split("/").last()
} }

View File

@ -2,12 +2,14 @@ package dev.fyloz.colorrecipesexplorer.rest
import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties
import dev.fyloz.colorrecipesexplorer.model.Model import dev.fyloz.colorrecipesexplorer.model.Model
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import java.net.URI import java.net.URI
const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE
lateinit var CRE_PROPERTIES: CreProperties lateinit var CRE_PROPERTIES: CreProperties
/** Creates a HTTP OK [ResponseEntity] from the given [body]. */ /** Creates a HTTP OK [ResponseEntity] from the given [body]. */
@ -24,6 +26,14 @@ fun ok(action: () -> Unit): ResponseEntity<Void> {
return ResponseEntity.ok().build() 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<Resource> =
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. */ /** Creates a HTTP CREATED [ResponseEntity] from the given [body] with the location set to [controllerPath]/id. */
fun <T : Model> created(controllerPath: String, body: T): ResponseEntity<T> = fun <T : Model> created(controllerPath: String, body: T): ResponseEntity<T> =
created(controllerPath, body, body.id!!) created(controllerPath, body, body.id!!)
@ -63,3 +73,6 @@ fun httpHeaders(
op() op()
} }
fun getFileNameFromPath(path: String) =
path.split("/").last()

View File

@ -5,7 +5,7 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitSaveDto
import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitUpdateDto import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitUpdateDto
import dev.fyloz.colorrecipesexplorer.service.TouchUpKitService import dev.fyloz.colorrecipesexplorer.service.TouchUpKitService
import org.springframework.context.annotation.Profile 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.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.access.prepost.PreAuthorize
@ -57,7 +57,7 @@ class TouchUpKitController(
} }
@GetMapping("pdf") @GetMapping("pdf")
fun getJobPdf(@RequestParam project: String): ResponseEntity<ByteArrayResource> { fun getJobPdf(@RequestParam project: String): ResponseEntity<Resource> {
with(touchUpKitService.generateJobPdfResource(project)) { with(touchUpKitService.generateJobPdfResource(project)) {
return ResponseEntity.ok() return ResponseEntity.ok()
.header("Content-Disposition", "filename=TouchUpKit_$project.pdf") .header("Content-Disposition", "filename=TouchUpKit_$project.pdf")

View File

@ -4,6 +4,7 @@ import dev.fyloz.colorrecipesexplorer.model.*
import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository
import dev.fyloz.colorrecipesexplorer.rest.FILE_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.rest.FILE_CONTROLLER_PATH
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService
import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService
import io.jsonwebtoken.lang.Assert import io.jsonwebtoken.lang.Assert
import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Lazy
import org.springframework.context.annotation.Profile import org.springframework.context.annotation.Profile
@ -39,7 +40,7 @@ class MaterialServiceImpl(
val recipeService: RecipeService, val recipeService: RecipeService,
val mixService: MixService, val mixService: MixService,
@Lazy val materialTypeService: MaterialTypeService, @Lazy val materialTypeService: MaterialTypeService,
val fileService: FileService, val fileService: WriteableFileService,
val configService: ConfigurationService val configService: ConfigurationService
) : ) :
AbstractExternalNamedModelService<Material, MaterialSaveDto, MaterialUpdateDto, MaterialOutputDto, MaterialRepository>( AbstractExternalNamedModelService<Material, MaterialSaveDto, MaterialUpdateDto, MaterialOutputDto, MaterialRepository>(
@ -59,7 +60,7 @@ class MaterialServiceImpl(
isMixType = this.isMixType, isMixType = this.isMixType,
materialType = this.materialType!!, materialType = this.materialType!!,
simdutUrl = if (fileService.exists(this.simdutFilePath)) 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( URLEncoder.encode(
this.simdutFilePath, this.simdutFilePath,
StandardCharsets.UTF_8 StandardCharsets.UTF_8

View File

@ -5,6 +5,8 @@ import dev.fyloz.colorrecipesexplorer.model.account.Group
import dev.fyloz.colorrecipesexplorer.model.validation.or import dev.fyloz.colorrecipesexplorer.model.validation.or
import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService 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 dev.fyloz.colorrecipesexplorer.utils.setAll
import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Lazy
import org.springframework.context.annotation.Profile import org.springframework.context.annotation.Profile
@ -78,7 +80,7 @@ class RecipeServiceImpl(
}.toSet(), }.toSet(),
this.groupsInformation, this.groupsInformation,
recipeImageService.getAllImages(this) recipeImageService.getAllImages(this)
.map { this.imageUrl(configService.get(ConfigurationType.INSTANCE_URL).content, it) } .map { this.imageUrl(configService.getContent(ConfigurationType.INSTANCE_URL), it) }
.toSet() .toSet()
) )
@ -87,7 +89,7 @@ class RecipeServiceImpl(
repository.existsByNameAndCompany(name, company) repository.existsByNameAndCompany(name, company)
override fun isApprobationExpired(recipe: Recipe): Boolean? = 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()) recipe.approbationDate?.plus(this)?.isBefore(LocalDate.now())
} }
@ -222,7 +224,7 @@ const val RECIPE_IMAGE_EXTENSION = ".jpg"
@Service @Service
@Profile("!emergency") @Profile("!emergency")
class RecipeImageServiceImpl( class RecipeImageServiceImpl(
val fileService: FileService val fileService: WriteableFileService
) : RecipeImageService { ) : RecipeImageService {
override fun getAllImages(recipe: Recipe): Set<String> { override fun getAllImages(recipe: Recipe): Set<String> {
val recipeDirectory = recipe.getDirectory() val recipeDirectory = recipe.getDirectory()

View File

@ -5,9 +5,12 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.*
import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository
import dev.fyloz.colorrecipesexplorer.rest.TOUCH_UP_KIT_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.rest.TOUCH_UP_KIT_CONTROLLER_PATH
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService 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 dev.fyloz.colorrecipesexplorer.utils.*
import org.springframework.context.annotation.Profile import org.springframework.context.annotation.Profile
import org.springframework.core.io.ByteArrayResource import org.springframework.core.io.ByteArrayResource
import org.springframework.core.io.Resource
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import java.time.LocalDate import java.time.LocalDate
import java.time.Period 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 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. * 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. */ /** Writes the given [document] to the [FileService] if TOUCH_UP_KIT_CACHE_PDF is enabled. */
fun String.cachePdfDocument(document: PdfDocument) fun String.cachePdfDocument(document: PdfDocument)
@ -41,14 +44,14 @@ interface TouchUpKitService :
@Service @Service
@Profile("!emergency") @Profile("!emergency")
class TouchUpKitServiceImpl( class TouchUpKitServiceImpl(
private val fileService: FileService, private val fileService: WriteableFileService,
private val configService: ConfigurationService, private val configService: ConfigurationService,
touchUpKitRepository: TouchUpKitRepository touchUpKitRepository: TouchUpKitRepository
) : AbstractExternalModelService<TouchUpKit, TouchUpKitSaveDto, TouchUpKitUpdateDto, TouchUpKitOutputDto, TouchUpKitRepository>( ) : AbstractExternalModelService<TouchUpKit, TouchUpKitSaveDto, TouchUpKitUpdateDto, TouchUpKitOutputDto, TouchUpKitRepository>(
touchUpKitRepository touchUpKitRepository
), TouchUpKitService { ), TouchUpKitService {
private val cacheGeneratedFiles by lazy { 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) override fun idNotFoundException(id: Long) = touchUpKitIdNotFoundException(id)
@ -90,7 +93,7 @@ class TouchUpKitServiceImpl(
} }
override fun isExpired(touchUpKit: TouchUpKit) = 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() 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) { if (cacheGeneratedFiles) {
with(job.pdfDocumentPath()) { with(job.pdfDocumentPath()) {
if (fileService.exists(this)) { if (fileService.exists(this)) {
@ -144,5 +147,5 @@ class TouchUpKitServiceImpl(
"$TOUCH_UP_KIT_FILES_PATH/$this.pdf" "$TOUCH_UP_KIT_FILES_PATH/$this.pdf"
private fun TouchUpKit.pdfUrl() = 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"
} }

View File

@ -2,32 +2,47 @@ package dev.fyloz.colorrecipesexplorer.service.config
import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties
import dev.fyloz.colorrecipesexplorer.model.* 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.decrypt
import dev.fyloz.colorrecipesexplorer.utils.encrypt import dev.fyloz.colorrecipesexplorer.utils.encrypt
import org.slf4j.Logger import org.slf4j.Logger
import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Lazy
import org.springframework.core.io.Resource
import org.springframework.security.crypto.keygen.KeyGenerators import org.springframework.security.crypto.keygen.KeyGenerators
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
interface ConfigurationService { interface ConfigurationService {
/** Gets all set configurations. */ /** Gets all set configurations. */
fun getAll(): List<Configuration> fun getAll(): List<ConfigurationBase>
/** /**
* Gets all configurations with keys contained in the given [formattedKeyList]. * Gets all configurations with keys contained in the given [formattedKeyList].
* The [formattedKeyList] contains wanted configuration keys separated by a semi-colon. * The [formattedKeyList] contains wanted configuration keys separated by a semi-colon.
*/ */
fun getAll(formattedKeyList: String): List<Configuration> fun getAll(formattedKeyList: String): List<ConfigurationBase>
/** /**
* Gets the configuration with the given [key]. * Gets the configuration with the given [key].
* If the [key] does not exists, an [InvalidConfigurationKeyException] will be thrown. * 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]. */ /** 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. */ /** Sets the content of each configuration in the given [configurations] list. */
fun set(configurations: List<ConfigurationDto>) fun set(configurations: List<ConfigurationDto>)
@ -41,20 +56,26 @@ interface ConfigurationService {
/** Sets the content given [configuration]. */ /** Sets the content given [configuration]. */
fun set(configuration: Configuration) fun set(configuration: Configuration)
/** Sets the content of the configuration matching the given [configuration] with a given image. */ /** Sets the app's icon. */
fun set(configuration: ConfigurationImageDto) fun setConfiguredIcon(icon: MultipartFile)
/** Sets the app's logo. */
fun setConfiguredLogo(logo: MultipartFile)
/** Initialize the properties matching the given [predicate]. */ /** Initialize the properties matching the given [predicate]. */
fun initializeProperties(predicate: (ConfigurationType) -> Boolean) 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_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_ICON_FILE_PATH = "images/icon"
const val CONFIGURATION_FORMATTED_LIST_DELIMITER = ';' const val CONFIGURATION_FORMATTED_LIST_DELIMITER = ';'
@Service("configurationService") @Service("configurationService")
class ConfigurationServiceImpl( class ConfigurationServiceImpl(
@Lazy private val fileService: FileService, @Lazy private val fileService: WriteableFileService,
private val resourceFileService: ResourceFileService,
private val configurationSource: ConfigurationSource, private val configurationSource: ConfigurationSource,
private val securityProperties: CreSecurityProperties, private val securityProperties: CreSecurityProperties,
private val logger: Logger private val logger: Logger
@ -89,18 +110,55 @@ class ConfigurationServiceImpl(
override fun get(key: String) = override fun get(key: String) =
get(key.toConfigurationType()) 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 // 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) if (type == ConfigurationType.GENERATED_ENCRYPTION_SALT) throw InvalidConfigurationKeyException(type.key)
val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type) val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type)
return if (type.secure) { return if (type.secure) {
decryptConfiguration(configuration) secureConfiguration(configuration)
} else { } else {
configuration 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<ConfigurationDto>) { override fun set(configurations: List<ConfigurationDto>) {
configurationSource.set( configurationSource.set(
configurations configurations
@ -116,14 +174,15 @@ class ConfigurationServiceImpl(
configurationSource.set(encryptConfigurationIfSecure(configuration)) configurationSource.set(encryptConfigurationIfSecure(configuration))
} }
override fun set(configuration: ConfigurationImageDto) { override fun setConfiguredIcon(icon: MultipartFile) =
val filePath = when (val configurationType = configuration.key.toConfigurationType()) { setConfiguredImage(icon, CONFIGURATION_ICON_FILE_PATH, ConfigurationType.INSTANCE_ICON_SET)
ConfigurationType.INSTANCE_LOGO_PATH -> CONFIGURATION_LOGO_FILE_PATH
ConfigurationType.INSTANCE_ICON_PATH -> CONFIGURATION_ICON_FILE_PATH
else -> throw InvalidImageConfigurationException(configurationType)
}
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) { override fun initializeProperties(predicate: (ConfigurationType) -> Boolean) {
@ -180,7 +239,7 @@ class ConfigurationServiceImpl(
private fun getGeneratedSalt(): String { private fun getGeneratedSalt(): String {
logger.warn("Sensitives configurations encryption salt was not configured, using generated salt") 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) var saltConfiguration = configurationSource.get(saltConfigurationType)
if (saltConfiguration == null) { if (saltConfiguration == null) {

View File

@ -8,7 +8,7 @@ import dev.fyloz.colorrecipesexplorer.model.Configuration
import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.ConfigurationType
import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.model.configuration
import dev.fyloz.colorrecipesexplorer.repository.ConfigurationRepository 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 dev.fyloz.colorrecipesexplorer.utils.excludeAll
import org.slf4j.Logger import org.slf4j.Logger
import org.springframework.boot.info.BuildProperties import org.springframework.boot.info.BuildProperties

View File

@ -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.config.properties.CreProperties
import dev.fyloz.colorrecipesexplorer.exception.RestException import dev.fyloz.colorrecipesexplorer.exception.RestException
import org.slf4j.Logger import org.slf4j.Logger
import org.springframework.core.io.ByteArrayResource import org.springframework.core.io.ByteArrayResource
import org.springframework.core.io.Resource
import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile import org.springframework.web.multipart.MultipartFile
@ -23,8 +24,13 @@ interface FileService {
fun exists(path: String): Boolean fun exists(path: String): Boolean
/** Reads the file at the given [path]. */ /** 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]. */ /** Creates a file at the given [path]. */
fun create(path: String) fun create(path: String)
@ -36,16 +42,13 @@ interface FileService {
/** Deletes the file at the given [path]. */ /** Deletes the file at the given [path]. */
fun delete(path: String) fun delete(path: String)
/** Completes the path of the given [String] by adding the working directory. */
fun String.fullPath(): FilePath
} }
@Service @Service
class FileServiceImpl( class FileServiceImpl(
private val creProperties: CreProperties, private val creProperties: CreProperties,
private val logger: Logger private val logger: Logger
) : FileService { ) : WriteableFileService {
override fun exists(path: String) = withFileAt(path.fullPath()) { override fun exists(path: String) = withFileAt(path.fullPath()) {
this.exists() && this.isFile this.exists() && this.isFile
} }

View File

@ -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)
}

View File

@ -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<Group, GroupSaveDto, GroupUpdateDto, GroupOutputDto, GroupRepository> {
/** Gets all the users of the group with the given [id]. */
fun getUsersForGroup(id: Long): Collection<User>
/** 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<Group, GroupSaveDto, GroupUpdateDto, GroupOutputDto, GroupRepository>(
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<User> =
userService.getByGroup(getById(id))
@Transactional
override fun save(entity: Group): Group {
return super<AbstractExternalNamedModelService>.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"
)
}
}

View File

@ -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<Map<String, *>>(objectMapper))
.signWith(secretKey)
}
private val jwtParser by lazy {
Jwts.parserBuilder()
.deserializeJsonWith(JacksonDeserializer<Map<String, *>>(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())
}

View File

@ -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<User>
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)
}
}

View File

@ -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.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.account.*
import dev.fyloz.colorrecipesexplorer.model.validation.or import dev.fyloz.colorrecipesexplorer.model.validation.or
import dev.fyloz.colorrecipesexplorer.repository.GroupRepository
import dev.fyloz.colorrecipesexplorer.repository.UserRepository 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.Lazy
import org.springframework.context.annotation.Profile 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.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import org.springframework.web.util.WebUtils import org.springframework.web.util.WebUtils
import java.time.LocalDateTime import java.time.LocalDateTime
import javax.servlet.http.HttpServletRequest 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 : interface UserService :
ExternalModelService<User, UserSaveDto, UserUpdateDto, UserOutputDto, UserRepository> { ExternalModelService<User, UserSaveDto, UserUpdateDto, UserOutputDto, UserRepository> {
@ -57,29 +50,11 @@ interface UserService :
fun logout(request: HttpServletRequest) fun logout(request: HttpServletRequest)
} }
interface GroupService :
ExternalNamedModelService<Group, GroupSaveDto, GroupUpdateDto, GroupOutputDto, GroupRepository> {
/** Gets all the users of the group with the given [id]. */
fun getUsersForGroup(id: Long): Collection<User>
/** 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 @Service
@Profile("!emergency") @Profile("!emergency")
class UserServiceImpl( class UserServiceImpl(
userRepository: UserRepository, userRepository: UserRepository,
@Lazy val groupService: GroupService, @Lazy val groupService: GroupService,
@Lazy val passwordEncoder: PasswordEncoder,
) : AbstractExternalModelService<User, UserSaveDto, UserUpdateDto, UserOutputDto, UserRepository>( ) : AbstractExternalModelService<User, UserSaveDto, UserUpdateDto, UserOutputDto, UserRepository>(
userRepository userRepository
), ),
@ -87,15 +62,7 @@ class UserServiceImpl(
override fun idNotFoundException(id: Long) = userIdNotFoundException(id) override fun idNotFoundException(id: Long) = userIdNotFoundException(id)
override fun idAlreadyExistsException(id: Long) = userIdAlreadyExistsException(id) override fun idAlreadyExistsException(id: Long) = userIdAlreadyExistsException(id)
override fun User.toOutput() = UserOutputDto( override fun User.toOutput() = this.toOutputDto()
this.id,
this.firstName,
this.lastName,
this.group,
this.flatPermissions,
this.permissions,
this.lastLoginTime
)
override fun existsByFirstNameAndLastName(firstName: String, lastName: String): Boolean = override fun existsByFirstNameAndLastName(firstName: String, lastName: String): Boolean =
repository.existsByFirstNameAndLastName(firstName, lastName) repository.existsByFirstNameAndLastName(firstName, lastName)
@ -122,11 +89,11 @@ class UserServiceImpl(
override fun save(entity: UserSaveDto): User = override fun save(entity: UserSaveDto): User =
save(with(entity) { save(with(entity) {
User( user(
id, id = id,
firstName, firstName = firstName,
lastName, lastName = lastName,
passwordEncoder.encode(password), plainPassword = password,
isDefaultGroupUser = false, isDefaultGroupUser = false,
isSystemUser = false, isSystemUser = false,
group = if (groupId != null) groupService.getById(groupId) else null, group = if (groupId != null) groupService.getById(groupId) else null,
@ -148,7 +115,7 @@ class UserServiceImpl(
id = 1000000L + group.id!!, id = 1000000L + group.id!!,
firstName = group.name, firstName = group.name,
lastName = "User", lastName = "User",
password = passwordEncoder.encode(group.name), plainPassword = group.name,
group = group, group = group,
isDefaultGroupUser = true isDefaultGroupUser = true
) )
@ -197,11 +164,11 @@ class UserServiceImpl(
override fun updatePassword(id: Long, password: String): User { override fun updatePassword(id: Long, password: String): User {
val persistedUser = getById(id, ignoreDefaultGroupUsers = true, ignoreSystemUsers = true) val persistedUser = getById(id, ignoreDefaultGroupUsers = true, ignoreSystemUsers = true)
return super.update(with(persistedUser) { return super.update(with(persistedUser) {
User( user(
id, id,
firstName, firstName,
lastName, lastName,
passwordEncoder.encode(password), plainPassword = password,
isDefaultGroupUser, isDefaultGroupUser,
isSystemUser, isSystemUser,
group, 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<Group, GroupSaveDto, GroupUpdateDto, GroupOutputDto, GroupRepository>(
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<User> =
userService.getByGroup(getById(id))
@Transactional
override fun save(entity: Group): Group {
return super<AbstractExternalNamedModelService>.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)
}
}

View File

@ -1,5 +1,7 @@
package dev.fyloz.colorrecipesexplorer.utils 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.Encryptors
import org.springframework.security.crypto.encrypt.TextEncryptor 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) = private fun withTextEncryptor(password: String, salt: String, op: (TextEncryptor) -> String) =
op(Encryptors.text(password, salt)) op(Encryptors.text(password, salt))
fun String.base64encode() =
with(Encoders.BASE64.encode(this.toByteArray())) {
Keys.hmacShaKeyFor(this.toByteArray())
}

View File

@ -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()
}

View File

@ -1,9 +1,18 @@
package dev.fyloz.colorrecipesexplorer.utils package dev.fyloz.colorrecipesexplorer.utils
import java.time.Instant
import java.time.Period import java.time.Period
import java.util.*
fun period(days: Int = 0, months: Int = 0, years: Int = 0): Period = fun period(days: Int = 0, months: Int = 0, years: Int = 0): Period =
Period.of(days, months, years) 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 val Int.months: Period
get() = period(months = this) get() = period(months = this)

View File

@ -3,7 +3,7 @@ server.port=9090
# CRE # CRE
cre.server.data-directory=data cre.server.data-directory=data
cre.server.config-directory=config cre.server.config-directory=config
cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE78WWOgl8InrbwBgQsMy0
cre.security.jwt-duration=18000000 cre.security.jwt-duration=18000000
cre.security.aes-secret=blabla cre.security.aes-secret=blabla
# Root user # Root user

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@ -10,8 +10,8 @@ import kotlin.test.assertEquals
@DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class])
class MaterialRepositoryTest @Autowired constructor( class MaterialRepositoryTest @Autowired constructor(
private val materialRepository: MaterialRepository, private val materialRepository: MaterialRepository,
private val entityManager: TestEntityManager private val entityManager: TestEntityManager
) { ) {
// updateInventoryQuantityById() // updateInventoryQuantityById()

View File

@ -10,8 +10,8 @@ import kotlin.test.assertEquals
@DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class])
class MixRepositoryTest @Autowired constructor( class MixRepositoryTest @Autowired constructor(
private val mixRepository: MixRepository, private val mixRepository: MixRepository,
private val entityManager: TestEntityManager private val entityManager: TestEntityManager
) { ) {
// updateLocationById() // updateLocationById()

View File

@ -5,8 +5,9 @@ import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName
import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException
import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException
import dev.fyloz.colorrecipesexplorer.model.account.* import dev.fyloz.colorrecipesexplorer.model.account.*
import dev.fyloz.colorrecipesexplorer.repository.UserRepository
import dev.fyloz.colorrecipesexplorer.repository.GroupRepository 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.junit.jupiter.api.*
import org.springframework.mock.web.MockHttpServletResponse import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.core.userdetails.UsernameNotFoundException
@ -18,24 +19,23 @@ import kotlin.test.assertEquals
import kotlin.test.assertFalse import kotlin.test.assertFalse
import kotlin.test.assertNotNull import kotlin.test.assertNotNull
import kotlin.test.assertTrue import kotlin.test.assertTrue
import org.springframework.security.core.userdetails.User as SpringUser
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserServiceTest : class UserServiceTest :
AbstractExternalModelServiceTest<User, UserSaveDto, UserUpdateDto, UserService, UserRepository>() { AbstractExternalModelServiceTest<User, UserSaveDto, UserUpdateDto, UserService, UserRepository>() {
private val passwordEncoder = BCryptPasswordEncoder() private val passwordEncoder = BCryptPasswordEncoder()
override val entity: User = user(passwordEncoder, id = 0L) override val entity: User = user(id = 0L, passwordEncoder = passwordEncoder)
override val anotherEntity: User = user(passwordEncoder, id = 1L) override val anotherEntity: User = user(id = 1L, passwordEncoder = passwordEncoder)
private val entityDefaultGroupUser = user(passwordEncoder, id = 2L, isDefaultGroupUser = true) private val entityDefaultGroupUser = user(id = 2L, isDefaultGroupUser = true, passwordEncoder = passwordEncoder)
private val entitySystemUser = user(passwordEncoder, id = 3L, isSystemUser = true) private val entitySystemUser = user(id = 3L, isSystemUser = true, passwordEncoder = passwordEncoder)
private val group = group(id = 0L) private val group = group(id = 0L)
override val entitySaveDto: UserSaveDto = spy(userSaveDto(passwordEncoder, id = 0L)) override val entitySaveDto: UserSaveDto = spy(userSaveDto(passwordEncoder, id = 0L))
override val entityUpdateDto: UserUpdateDto = spy(userUpdateDto(id = 0L)) override val entityUpdateDto: UserUpdateDto = spy(userUpdateDto(id = 0L))
override val repository: UserRepository = mock() override val repository: UserRepository = mock()
private val groupService: GroupService = 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( private val entitySaveDtoUser = User(
entitySaveDto.id, entitySaveDto.id,
@ -210,7 +210,7 @@ class GroupServiceTest :
override val entityWithEntityName: Group = group(id = 2L, name = entity.name) override val entityWithEntityName: Group = group(id = 2L, name = entity.name)
private val groupUserId = 1000000L + entity.id!! 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 @BeforeEach
override fun afterEach() { override fun afterEach() {
@ -303,7 +303,7 @@ class GroupServiceTest :
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserUserDetailsServiceTest { class UserUserDetailsServiceTest {
private val userService: UserService = mock() private val userService: UserService = mock()
private val service = spy(CreUserDetailsServiceImpl(userService)) private val service = spy(UserDetailsServiceImpl(userService))
private val user = user(id = 0L) private val user = user(id = 0L)
@ -317,8 +317,8 @@ class UserUserDetailsServiceTest {
@Test @Test
fun `loadUserByUsername() calls loadUserByUserId() with the given username as an id`() { fun `loadUserByUsername() calls loadUserByUserId() with the given username as an id`() {
whenever(userService.getById(eq(user.id), any(), any())).doReturn(user) whenever(userService.getById(eq(user.id), any(), any())).doReturn(user)
doReturn(SpringUser(user.id.toString(), user.password, listOf())).whenever(service) doReturn(UserDetails(user(id = user.id, plainPassword = user.password)))
.loadUserById(user.id) .whenever(service).loadUserById(user.id)
service.loadUserByUsername(user.id.toString()) service.loadUserByUsername(user.id.toString())

View File

@ -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.CONFIGURATION_FORMATTED_LIST_DELIMITER
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationServiceImpl import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationServiceImpl
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationSource 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 dev.fyloz.colorrecipesexplorer.utils.encrypt
import io.mockk.* import io.mockk.*
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows 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.assertEquals
import kotlin.test.assertFalse import kotlin.test.assertFalse
import kotlin.test.assertTrue import kotlin.test.assertTrue
class ConfigurationServiceTest { class ConfigurationServiceTest {
private val fileService = mockk<FileService>() private val fileService = mockk<WriteableFileService>()
private val resourceFileService = mockk<ResourceFileService>()
private val configurationSource = mockk<ConfigurationSource>() private val configurationSource = mockk<ConfigurationSource>()
private val securityProperties = mockk<CreSecurityProperties> { private val securityProperties = mockk<CreSecurityProperties> {
every { configSalt } returns "d32270943af7e1cc" every { configSalt } returns "d32270943af7e1cc"
} }
private val service = spyk(ConfigurationServiceImpl(fileService, configurationSource, securityProperties, mockk())) private val service = spyk(
ConfigurationServiceImpl(
fileService,
resourceFileService,
configurationSource,
securityProperties,
mockk()
)
)
@AfterEach @AfterEach
fun afterEach() { fun afterEach() {
@ -48,8 +61,8 @@ class ConfigurationServiceTest {
fun `getAll() only returns set configurations`() { fun `getAll() only returns set configurations`() {
val unsetConfigurationTypes = listOf( val unsetConfigurationTypes = listOf(
ConfigurationType.INSTANCE_NAME, ConfigurationType.INSTANCE_NAME,
ConfigurationType.INSTANCE_LOGO_PATH, ConfigurationType.INSTANCE_LOGO_SET,
ConfigurationType.INSTANCE_ICON_PATH ConfigurationType.INSTANCE_ICON_SET
) )
every { service.get(match<ConfigurationType> { it in unsetConfigurationTypes }) } answers { every { service.get(match<ConfigurationType> { it in unsetConfigurationTypes }) } answers {
@ -81,8 +94,8 @@ class ConfigurationServiceTest {
fun `getAll() only includes configurations matching the formatted formatted key list`() { fun `getAll() only includes configurations matching the formatted formatted key list`() {
val configurationTypes = listOf( val configurationTypes = listOf(
ConfigurationType.INSTANCE_NAME, ConfigurationType.INSTANCE_NAME,
ConfigurationType.INSTANCE_LOGO_PATH, ConfigurationType.INSTANCE_LOGO_SET,
ConfigurationType.INSTANCE_ICON_PATH ConfigurationType.INSTANCE_ICON_SET
) )
val formattedKeyList = configurationTypes val formattedKeyList = configurationTypes
.map { it.key } .map { it.key }
@ -112,7 +125,7 @@ class ConfigurationServiceTest {
@Test @Test
fun `get(key) calls get() with the ConfigurationType matching the given key`() { 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 val key = type.key
every { service.get(type) } answers { every { service.get(type) } answers {
@ -131,7 +144,7 @@ class ConfigurationServiceTest {
@Test @Test
fun `get(type) gets the configuration in the ConfigurationSource`() { 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) val configuration = configuration(type = type)
every { configurationSource.get(type) } returns configuration every { configurationSource.get(type) } returns configuration
@ -143,7 +156,7 @@ class ConfigurationServiceTest {
@Test @Test
fun `get(type) throws ConfigurationNotSetException when the given ConfigurationType has no set configuration`() { 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 every { configurationSource.get(type) } returns null
@ -165,7 +178,47 @@ class ConfigurationServiceTest {
} }
@Test @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<UnsupportedOperationException> { service.getContent(type) }
}
@Test
fun `getSecure(type) returns decrypted configuration content`() {
val type = ConfigurationType.DATABASE_PASSWORD val type = ConfigurationType.DATABASE_PASSWORD
val content = "securepassword" val content = "securepassword"
val configuration = configuration( val configuration = configuration(
@ -175,9 +228,67 @@ class ConfigurationServiceTest {
every { configurationSource.get(type) } returns configuration 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<UnsupportedOperationException> { service.getSecure(type) }
}
private fun getConfiguredImageTest(
configurationType: ConfigurationType,
imageSet: Boolean,
test: (Resource) -> Unit
) {
val resource = mockk<Resource>()
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 @Test
@ -197,7 +308,7 @@ class ConfigurationServiceTest {
fun `set(configuration) encrypts secure configurations`() { fun `set(configuration) encrypts secure configurations`() {
val type = ConfigurationType.DATABASE_PASSWORD val type = ConfigurationType.DATABASE_PASSWORD
val content = "securepassword" 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) val configuration = configuration(type = type, content = content)
mockkStatic(String::encrypt) mockkStatic(String::encrypt)
@ -213,4 +324,65 @@ class ConfigurationServiceTest {
}) })
} }
} }
private fun setConfiguredImageTest(test: (MultipartFile) -> Unit) {
val file = mockk<MultipartFile>()
every { service.set(any<Configuration>()) } just runs
every { fileService.write(any<MultipartFile>(), 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<Configuration> {
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<Configuration> {
it.key == type.key && it.content == true.toString()
})
}
}
}
} }

View File

@ -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<Map<String, *>>(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)
}
}

View File

@ -4,7 +4,7 @@ import com.nhaarman.mockitokotlin2.*
import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException
import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.model.*
import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository 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.AfterEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance
@ -21,7 +21,7 @@ class MaterialServiceTest :
private val recipeService: RecipeService = mock() private val recipeService: RecipeService = mock()
private val mixService: MixService = mock() private val mixService: MixService = mock()
private val materialTypeService: MaterialTypeService = mock() private val materialTypeService: MaterialTypeService = mock()
private val fileService: FileService = mock() private val fileService: WriteableFileService = mock()
override val service: MaterialService = override val service: MaterialService =
spy(MaterialServiceImpl(repository, recipeService, mixService, materialTypeService, fileService, mock())) spy(MaterialServiceImpl(repository, recipeService, mixService, materialTypeService, fileService, mock()))

View File

@ -87,9 +87,9 @@ class MixServiceTest : AbstractExternalModelServiceTest<Mix, MixSaveDto, MixUpda
// update() // update()
private fun mixUpdateDtoTest( private fun mixUpdateDtoTest(
scope: MixUpdateDtoTestScope = MixUpdateDtoTestScope(), scope: MixUpdateDtoTestScope = MixUpdateDtoTestScope(),
sharedMixType: Boolean = false, sharedMixType: Boolean = false,
op: MixUpdateDtoTestScope.() -> Unit op: MixUpdateDtoTestScope.() -> Unit
) { ) {
with(scope) { with(scope) {
doReturn(true).whenever(service).existsById(mix.id!!) doReturn(true).whenever(service).existsById(mix.id!!)

View File

@ -6,6 +6,8 @@ import dev.fyloz.colorrecipesexplorer.model.*
import dev.fyloz.colorrecipesexplorer.model.account.group import dev.fyloz.colorrecipesexplorer.model.account.group
import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService 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 io.mockk.*
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -80,9 +82,9 @@ class RecipeServiceTest :
@Test @Test
fun `isApprobationExpired() returns false when the approbation date of the given recipe is within the configured period`() { fun `isApprobationExpired() returns false when the approbation date of the given recipe is within the configured period`() {
val period = Period.ofMonths(4) val period = Period.ofMonths(4)
val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString())
val recipe = recipe(approbationDate = LocalDate.now()) 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) val approbationExpired = service.isApprobationExpired(recipe)
@ -93,9 +95,9 @@ class RecipeServiceTest :
@Test @Test
fun `isApprobationExpired() returns true when the approbation date of the given recipe is outside the configured period`() { fun `isApprobationExpired() returns true when the approbation date of the given recipe is outside the configured period`() {
val period = Period.ofMonths(4) 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)) 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) val approbationExpired = service.isApprobationExpired(recipe)
@ -106,9 +108,9 @@ class RecipeServiceTest :
@Test @Test
fun `isApprobationExpired() returns null when the given recipe as no approbation date`() { fun `isApprobationExpired() returns null when the given recipe as no approbation date`() {
val period = Period.ofMonths(4) val period = Period.ofMonths(4)
val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString())
val recipe = recipe(approbationDate = null) 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) val approbationExpired = service.isApprobationExpired(recipe)
@ -263,7 +265,7 @@ class RecipeServiceTest :
} }
private class RecipeImageServiceTestContext { private class RecipeImageServiceTestContext {
val fileService = mockk<FileService> { val fileService = mockk<WriteableFileService> {
every { write(any<MultipartFile>(), any(), any()) } just Runs every { write(any<MultipartFile>(), any(), any()) } just Runs
every { delete(any()) } just Runs every { delete(any()) } just Runs
} }

View File

@ -1,8 +1,11 @@
package dev.fyloz.colorrecipesexplorer.service package dev.fyloz.colorrecipesexplorer.service
import com.nhaarman.mockitokotlin2.* 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.account.group
import dev.fyloz.colorrecipesexplorer.model.recipeGroupInformation
import dev.fyloz.colorrecipesexplorer.model.recipeStep
import dev.fyloz.colorrecipesexplorer.repository.RecipeStepRepository import dev.fyloz.colorrecipesexplorer.repository.RecipeStepRepository
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance

View File

@ -1,11 +1,10 @@
package dev.fyloz.colorrecipesexplorer.service package dev.fyloz.colorrecipesexplorer.service
import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties
import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.ConfigurationType
import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.model.configuration
import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository
import dev.fyloz.colorrecipesexplorer.service.*
import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService 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.PdfDocument
import dev.fyloz.colorrecipesexplorer.utils.toByteArrayResource import dev.fyloz.colorrecipesexplorer.utils.toByteArrayResource
import io.mockk.* import io.mockk.*
@ -16,10 +15,9 @@ import kotlin.test.assertEquals
private class TouchUpKitServiceTestContext { private class TouchUpKitServiceTestContext {
val touchUpKitRepository = mockk<TouchUpKitRepository>() val touchUpKitRepository = mockk<TouchUpKitRepository>()
val fileService = mockk<FileService> { val fileService = mockk<WriteableFileService> {
every { write(any<ByteArrayResource>(), any(), any()) } just Runs every { write(any<ByteArrayResource>(), any(), any()) } just Runs
} }
val creProperties = mockk<CreProperties>()
val configService = mockk<ConfigurationService>(relaxed = true) val configService = mockk<ConfigurationService>(relaxed = true)
val touchUpKitService = spyk(TouchUpKitServiceImpl(fileService, configService, touchUpKitRepository)) val touchUpKitService = spyk(TouchUpKitServiceImpl(fileService, configService, touchUpKitRepository))
val pdfDocumentData = mockk<ByteArrayResource>() val pdfDocumentData = mockk<ByteArrayResource>()
@ -131,10 +129,7 @@ class TouchUpKitServiceTest {
this.setCachePdf(false) this.setCachePdf(false)
private fun TouchUpKitServiceTestContext.setCachePdf(enabled: Boolean) { private fun TouchUpKitServiceTestContext.setCachePdf(enabled: Boolean) {
every { configService.get(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns configuration( every { configService.getContent(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns enabled.toString()
type = ConfigurationType.TOUCH_UP_KIT_CACHE_PDF,
enabled.toString()
)
} }
private fun test(test: TouchUpKitServiceTestContext.() -> Unit) { private fun test(test: TouchUpKitServiceTestContext.() -> Unit) {

View File

@ -1,4 +1,4 @@
package dev.fyloz.colorrecipesexplorer.service package dev.fyloz.colorrecipesexplorer.service.files
import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties
import io.mockk.* import io.mockk.*

View File

@ -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<ResourceLoader>()
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<Resource> {
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<FileNotFoundException> {
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<Resource>()
every { resourceLoader.getResource(filePath.path) } returns resource
with(service) {
val found = filePath.resource
assertEquals(resource, found)
}
}
}

View File

@ -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