A working service for editing, querying, login and authentication of users. publishes events to kafka
This commit is contained in:
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
3
Dockerfile
Normal file
3
Dockerfile
Normal file
@@ -0,0 +1,3 @@
|
||||
FROM amazoncorretto:17
|
||||
COPY build/libs/BUFUS_USERS-0.0.1-SNAPSHOT.jar bufus_users.jar
|
||||
ENTRYPOINT ["java","-jar","/bufus_users.jar"]
|
||||
10
READMES/Docker.help
Normal file
10
READMES/Docker.help
Normal file
@@ -0,0 +1,10 @@
|
||||
for manually building and deploying this image
|
||||
|
||||
build the sources and the image
|
||||
|
||||
./gradlew build
|
||||
docker build . --tag=bufus_users_testing
|
||||
|
||||
launch the image ( port 8101 is the one expected by the gateway service )
|
||||
|
||||
docker run -p 8101:8080 bufus_users_testing:latest
|
||||
26
READMES/curl_commands.help
Normal file
26
READMES/curl_commands.help
Normal file
@@ -0,0 +1,26 @@
|
||||
# DEMO USERS
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"pino\", \"email\": \"pino@gmail.com\", \"password\": \"aaa\", \"type\": \"CUSTOMER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"babi\", \"email\": \"babi@gmail.com\", \"password\": \"bbb\", \"type\": \"CUSTOMER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"chris\", \"email\": \"chris@gmail.com\", \"password\": \"ccc\", \"type\": \"CUSTOMER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"dani\", \"email\": \"dani@gmail.com\", \"password\": \"ddd\", \"type\": \"CUSTOMER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"eric\", \"email\": \"eric@gmail.com\", \"password\": \"eee\", \"type\": \"CUSTOMER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"alberto\", \"email\": \"alberto@gmail.com\", \"password\": \"ffff6\", \"type\": \"SELLER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"escoshop\", \"email\": \"escoshop@legalmail.com\", \"password\": \"gggg7\", \"type\": \"SELLER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"SoundGarden\", \"email\": \"commercial@soundgarden.com\", \"password\": \"hhhh8\", \"type\": \"SELLER\" }" http://localhost:8101/users
|
||||
curl -X POST -H "Content-Type:application/json" -d "{ \"username\": \"tombolino\", \"email\": \"tombolino@administration.com\", \"password\": \"iiii9\", \"type\": \"ADMINISTRATOR\" }" http://localhost:8101/users
|
||||
|
||||
|
||||
# AUTH DEMO
|
||||
|
||||
# autentication part 1 ( login-like, get token )
|
||||
curl -X PUT -H "Authorization: Basic $( printf 'alberto@gmail.com:ffff6' | base64 )" http://localhost:8101/users
|
||||
|
||||
# autentication part 1 ( login-like, get token )
|
||||
curl -X PUT -H "Authorization: Basic $( printf 'tombolino@administration.com:iiii9' | base64 )" http://localhost:8101/users
|
||||
|
||||
# the returned token
|
||||
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDT01FIERJQU1JTkUgQ0hJQU1PIEJVRlVTIElERU5USVRJRVM_Iiwic3ViIjoibnVsbCIsInR5cGUiOiJBRE1JTklTVFJBVE9SIiwiZW1haWwiOiJ0b21ib2xpbm9AYWRtaW5pc3RyYXRpb24uY29tIiwiaWF0IjoxNzY0MDg3NzMwLCJuYmYiOjE3NjQwODc3MzAsImV4cCI6MTc2NDA5MTMzMH0.Z6MB8YNNaBtWTYnqbOFcVNErOjJFyRun7r1efpkDBg0
|
||||
|
||||
|
||||
# autentication part 2 ( use token )
|
||||
curl -X GET -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDT01FIERJQU1JTkUgQ0hJQU1PIEJVRlVTIElERU5USVRJRVM_Iiwic3ViIjoibnVsbCIsInR5cGUiOiJBRE1JTklTVFJBVE9SIiwiZW1haWwiOiJ0b21ib2xpbm9AYWRtaW5pc3RyYXRpb24uY29tIiwiaWF0IjoxNzY0MDg3NzMwLCJuYmYiOjE3NjQwODc3MzAsImV4cCI6MTc2NDA5MTMzMH0.Z6MB8YNNaBtWTYnqbOFcVNErOjJFyRun7r1efpkDBg0" http://localhost:8101/users
|
||||
37
build.gradle
Normal file
37
build.gradle
Normal file
@@ -0,0 +1,37 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.5.7'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
}
|
||||
|
||||
group = 'com.theycallmebeno'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
description = 'Demo project for Spring Boot'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.kafka:spring-kafka'
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.13.0'
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.13.0'
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.13.0' // or 'io.jsonwebtoken:jjwt-gson:0.13.0'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
251
gradlew
vendored
Executable file
251
gradlew
vendored
Executable file
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# 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/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
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
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# 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"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# 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" "$@"
|
||||
94
gradlew.bat
vendored
Normal file
94
gradlew.bat
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'BUFUS_USERS'
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.theycallmebeno.usersService;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
|
||||
import org.springframework.kafka.core.ProducerFactory;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.core.KafkaAdmin;
|
||||
import org.springframework.kafka.config.TopicBuilder;
|
||||
|
||||
import org.apache.kafka.clients.admin.NewTopic;
|
||||
import org.apache.kafka.clients.admin.AdminClientConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.common.config.TopicConfig;
|
||||
|
||||
import org.apache.kafka.common.serialization.IntegerSerializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
|
||||
public class KafkaConfiguration {
|
||||
@Bean
|
||||
public ProducerFactory producerFactory() {
|
||||
return new DefaultKafkaProducerFactory<>(producerConfigs());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Map producerConfigs() {
|
||||
Map props = new HashMap<>();
|
||||
/* the value is taken from application.properties, ignore this */
|
||||
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "host.docker.internal:9092");
|
||||
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
|
||||
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
|
||||
// See https://kafka.apache.org/41/documentation/#producerconfigs for more properties
|
||||
return props;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public KafkaTemplate kafkaTemplate() {
|
||||
return new KafkaTemplate(producerFactory());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public KafkaAdmin admin() {
|
||||
Map<String, Object> configs = new HashMap<>();
|
||||
configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "host.doecker.internal:9092");
|
||||
return new KafkaAdmin(configs);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NewTopic createdUsers() {
|
||||
return TopicBuilder.name("users.created")
|
||||
.partitions(10)
|
||||
.replicas(3)
|
||||
.compact()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.theycallmebeno.usersService;
|
||||
import com.theycallmebeno.usersService.user.UserReadConverter;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
|
||||
import org.springframework.data.mongodb.MongoDatabaseFactory;
|
||||
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions.MongoConverterConfigurationAdapter;
|
||||
|
||||
|
||||
|
||||
@Configuration
|
||||
public class MongoConfiguration extends AbstractMongoClientConfiguration {
|
||||
|
||||
String dbName = "bufus_users_testing";
|
||||
|
||||
@Override
|
||||
public MongoClient mongoClient() {
|
||||
String username = "users_service";
|
||||
String password = "usersServiceNeedsAPassword";
|
||||
String port = "27017";
|
||||
String host = "mongodb";
|
||||
|
||||
String conString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/" + dbName ;
|
||||
MongoClient mClient = MongoClients.create(conString);
|
||||
return mClient;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getDatabaseName() {
|
||||
return dbName;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MongoTemplate mongoTemplate() {
|
||||
MongoTemplate mt = new MongoTemplate(mongoClient(), getDatabaseName());
|
||||
return mt;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureConverters(MongoConverterConfigurationAdapter adapter) {
|
||||
adapter.registerConverter(new UserReadConverter());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.theycallmebeno.usersService;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class UsersServiceApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UsersServiceApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.theycallmebeno.usersService.event;
|
||||
|
||||
import com.theycallmebeno.usersService.user.User;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.support.SendResult;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
|
||||
|
||||
|
||||
@Service
|
||||
public class EventService {
|
||||
|
||||
@Autowired
|
||||
KafkaTemplate template;
|
||||
|
||||
public void userCreated(User u){
|
||||
String payload = String.format(
|
||||
"{ id: \"%s\", type: \"%s\" }",
|
||||
u.getId(), u.getType()
|
||||
);
|
||||
|
||||
sendToKafka(new ProducerRecord("users.created", payload));
|
||||
}
|
||||
|
||||
private void sendToKafka(ProducerRecord<String, String> record){
|
||||
CompletableFuture<SendResult<String, String>> future = template.send(record);
|
||||
future.whenComplete((result, ex) -> {
|
||||
if (ex == null) {
|
||||
//handleSuccess(data);
|
||||
}
|
||||
else {
|
||||
System.out.println("failure in sending kafka message");
|
||||
ex.printStackTrace();
|
||||
|
||||
//template.send(record);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
import from god knows where
|
||||
import io.jsonwebtoken.Jwts;
|
||||
|
||||
import from the root of the project ( root.model )
|
||||
import io.jsonwebtoken.jjwtfun.model.JwtResponse;
|
||||
*/
|
||||
package com.theycallmebeno.usersService.jwt;
|
||||
|
||||
|
||||
import com.theycallmebeno.usersService.user.User;
|
||||
import com.theycallmebeno.usersService.user.Customer;
|
||||
import com.theycallmebeno.usersService.user.Seller;
|
||||
import com.theycallmebeno.usersService.user.Administrator;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Date;
|
||||
import java.time.Instant;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class JwtService {
|
||||
|
||||
static long tokenDurationSeconds = 3600; /* an hour */
|
||||
|
||||
static SignatureAlgorithm defaultAlgo = SignatureAlgorithm.HS256;
|
||||
static SignatureAlgorithm strongAlgo = SignatureAlgorithm.HS512;
|
||||
|
||||
static String defaultSecret = "secret";
|
||||
static String strongSecret = "Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E=";
|
||||
|
||||
static SecretKey secretKey = Keys.hmacShaKeyFor(JwtService.strongSecret.getBytes());
|
||||
|
||||
|
||||
/* registered claims
|
||||
issuer iss, subject sub, audience aud,
|
||||
expiration exp, notBefore nbf, issuedAt iat,
|
||||
ID jti
|
||||
+ more...
|
||||
*/
|
||||
public String createToken(User user, Date notBefore){
|
||||
if(null == user){
|
||||
throw new NoSuchElementException("user is missing");
|
||||
}
|
||||
|
||||
Date iat = new Date();
|
||||
Date nbf = (null == notBefore) ? iat : notBefore;
|
||||
long epochNbf = nbf.toInstant().getEpochSecond();
|
||||
Date exp = Date.from(Instant.ofEpochSecond(epochNbf + JwtService.tokenDurationSeconds));
|
||||
|
||||
String jws = Jwts.builder()
|
||||
.setIssuer("COME DIAMINE CHIAMO BUFUS IDENTITIES?")
|
||||
.setSubject("" + user.getId())
|
||||
.claim("type", user.getType())
|
||||
.claim("email", user.getEmail())
|
||||
.claim("id", user.getId())
|
||||
.setIssuedAt(iat)
|
||||
.setNotBefore(nbf)
|
||||
.setExpiration(exp)
|
||||
.signWith(JwtService.secretKey)
|
||||
.compact();
|
||||
|
||||
|
||||
System.out.println("creted token");
|
||||
System.out.println(jws);
|
||||
return jws;
|
||||
}
|
||||
|
||||
public User decodeToken(String jwsString){
|
||||
System.out.println("decodeToken");
|
||||
|
||||
SecretKey secretKey;
|
||||
try {
|
||||
secretKey = new SecretKeySpec(
|
||||
TextCodec.BASE64.decode(JwtService.strongSecret),
|
||||
JwtService.defaultAlgo.getValue()
|
||||
);
|
||||
}
|
||||
catch(UnsupportedEncodingException e){
|
||||
System.out.println("crashing onn");
|
||||
throw new RuntimeException("mannagg");
|
||||
}
|
||||
|
||||
Jws<Claims> jws;
|
||||
|
||||
try {
|
||||
jws = Jwts.parser() // (1)
|
||||
|
||||
//.keyLocator(keyLocator) // (2) dynamically lookup verification keys based on each JWS
|
||||
/* works where SecretKeySpec fails */
|
||||
.verifyWith( Keys.hmacShaKeyFor(JwtService.strongSecret.getBytes()))
|
||||
.build() // (3)
|
||||
.parseSignedClaims(jwsString); // (4) or parseSignedContent(jwsString)
|
||||
|
||||
|
||||
Map<String, Object> claims = jws.getBody();
|
||||
|
||||
for(Map.Entry<String,Object> claim : claims.entrySet()){
|
||||
System.out.println("Claim " + claim.getKey() + " : " + claim.getValue());
|
||||
}
|
||||
|
||||
User decoded;
|
||||
switch((String) claims.get("type")){
|
||||
case "CUSTOMER":
|
||||
decoded = new Customer();
|
||||
break;
|
||||
case "SELLER":
|
||||
decoded = new Seller();
|
||||
break;
|
||||
case "ADMINISTRATOR":
|
||||
decoded = new Administrator();
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown User.Type");
|
||||
}
|
||||
decoded.setEmail((String) claims.get("email"));
|
||||
decoded.setId((String) claims.get("id"));
|
||||
|
||||
System.out.println("successfully decoded jwt");
|
||||
// we can safely trust the JWT
|
||||
return decoded;
|
||||
}
|
||||
catch (JwtException ex) { // (5)
|
||||
System.out.println("crash at last");
|
||||
System.out.println(ex);
|
||||
ex.printStackTrace();
|
||||
// we *cannot* use the JWT as intended by its creator
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.theycallmebeno.usersService.jwt;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class TextCodec {
|
||||
public static class BASE64 {
|
||||
static byte[] decode(String todecode) throws UnsupportedEncodingException {
|
||||
return todecode.getBytes("UTF-8");
|
||||
}
|
||||
|
||||
static String encode(byte[] toencode) throws UnsupportedEncodingException {
|
||||
return new String(toencode, "UTF-8");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import org.springframework.data.annotation.TypeAlias;
|
||||
|
||||
@TypeAlias("ADMINISTRATOR")
|
||||
public class Administrator extends User {
|
||||
|
||||
public Administrator(){
|
||||
this.setType(Type.ADMINISTRATOR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import org.springframework.data.annotation.TypeAlias;
|
||||
|
||||
@TypeAlias("CUSTOMER")
|
||||
public class Customer extends User {
|
||||
|
||||
public Customer(){
|
||||
this.setType(Type.CUSTOMER);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import org.springframework.data.annotation.TypeAlias;
|
||||
|
||||
@TypeAlias("SELLER")
|
||||
public class Seller extends User {
|
||||
|
||||
public Seller(){
|
||||
this.setType(Type.SELLER);
|
||||
}
|
||||
}
|
||||
111
src/main/java/com/theycallmebeno/usersService/user/User.java
Normal file
111
src/main/java/com/theycallmebeno/usersService/user/User.java
Normal file
@@ -0,0 +1,111 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
|
||||
@JsonTypeInfo(
|
||||
use = JsonTypeInfo.Id.NAME,
|
||||
include = JsonTypeInfo.As.EXISTING_PROPERTY,
|
||||
property = "type",
|
||||
visible = true
|
||||
)
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = Customer.class, name = "CUSTOMER"),
|
||||
@JsonSubTypes.Type(value = Seller.class, name = "SELLER"),
|
||||
@JsonSubTypes.Type(value = Administrator.class, name = "ADMINISTRATOR")
|
||||
})
|
||||
@Document(collection="users")
|
||||
public abstract class User {
|
||||
|
||||
public enum Type {
|
||||
CUSTOMER,
|
||||
SELLER,
|
||||
ADMINISTRATOR;
|
||||
|
||||
public static Type parse(String s){
|
||||
if(s == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
switch(s.toUpperCase()){
|
||||
case "CUSTOMER":
|
||||
return Type.CUSTOMER;
|
||||
case "SELLER":
|
||||
return Type.SELLER;
|
||||
case "ADMINISTRATOR":
|
||||
return Type.ADMINISTRATOR;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Id private String id;
|
||||
|
||||
private String username;
|
||||
private String email;
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private String password;
|
||||
private User.Type type;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public User.Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(User.Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(){
|
||||
return String.format(
|
||||
"{ \"id\": %s, \"username\": %s, \"email\": %s, \"type\": %s }",
|
||||
wrappedOrNull(this.id),
|
||||
wrappedOrNull(this.username),
|
||||
wrappedOrNull(this.email),
|
||||
wrappedOrNull(this.type)
|
||||
);
|
||||
}
|
||||
|
||||
private String wrappedOrNull(Object toWrap){
|
||||
return (null == toWrap) ? "null" : "\"" + toWrap.toString() + "\"";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import java.lang.IllegalArgumentException;
|
||||
|
||||
import org.springframework.data.convert.ReadingConverter;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.bson.Document;
|
||||
|
||||
|
||||
|
||||
@ReadingConverter
|
||||
public class UserReadConverter implements Converter<Document, User> {
|
||||
|
||||
@Override
|
||||
public User convert(Document source) {
|
||||
System.out.println("NA BELLA CALL TO READCONVERTER");
|
||||
System.out.println(source.keySet());
|
||||
String id = source.getObjectId("_id").toString();
|
||||
String username = (String) source.get("username");
|
||||
String email = (String) source.get("email");
|
||||
String password = (String) source.get("password");
|
||||
String type = (String) source.get("type");
|
||||
User.Type castedType = User.Type.parse(type);
|
||||
User genericRef = null;
|
||||
|
||||
switch(castedType){
|
||||
case CUSTOMER:
|
||||
genericRef = new Customer();
|
||||
break;
|
||||
case SELLER:
|
||||
genericRef = new Seller();
|
||||
break;
|
||||
case ADMINISTRATOR:
|
||||
genericRef = new Administrator();
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("typeless user");
|
||||
}
|
||||
|
||||
genericRef.setId(id);
|
||||
genericRef.setUsername(username);
|
||||
genericRef.setEmail(email);
|
||||
genericRef.setPassword(password);
|
||||
|
||||
return genericRef;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
/*
|
||||
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
|
||||
|
||||
@RepositoryRestResource(collectionResourceRel = "products", path = "products")
|
||||
*/
|
||||
public interface UserRepository extends MongoRepository<User, String> {
|
||||
public User findByEmail(String email);
|
||||
public User findByEmailAndPassword(String email, String password);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import com.theycallmebeno.usersService.jwt.JwtService;
|
||||
import com.theycallmebeno.usersService.validation.UserValidator;
|
||||
import com.theycallmebeno.usersService.validation.InvalidEntityException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Base64;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import javax.naming.AuthenticationException;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpClientErrorException.*;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/users")
|
||||
public class UsersController {
|
||||
|
||||
@Autowired
|
||||
UsersService US;
|
||||
|
||||
@Autowired
|
||||
JwtService JS;
|
||||
|
||||
@ExceptionHandler(NoSuchElementException.class)
|
||||
public ResponseEntity<String> handleNotFound() {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<String> handleBadInput() {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<String> handleUnauthenticated() {
|
||||
return ResponseEntity.status(401).build();
|
||||
}
|
||||
|
||||
@ExceptionHandler
|
||||
public ResponseEntity<String> handleInvalidInput(InvalidEntityException ex) {
|
||||
return ResponseEntity.status(409).body(ex.getEntity().toString());
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public List<User> allUsers()
|
||||
{
|
||||
System.out.println(US.getAll());
|
||||
return US.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{identifier}")
|
||||
public User getUser(@PathVariable(name = "identifier") String queryString){
|
||||
|
||||
System.out.println("getUser with query " + queryString + "!");
|
||||
|
||||
if(queryString.contains("@")){
|
||||
return US.findByEmail(queryString);
|
||||
}
|
||||
else {
|
||||
return US.findById(queryString);
|
||||
}
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public String authenticateUser(
|
||||
@RequestHeader("Authorization") String authorization
|
||||
)
|
||||
throws AuthenticationException
|
||||
{
|
||||
if(null == authorization){
|
||||
throw new AuthenticationException();
|
||||
}
|
||||
|
||||
System.out.println("raw header:\n" + authorization);
|
||||
|
||||
String toTrim = "Basic ";
|
||||
if( ! authorization.startsWith(toTrim)){
|
||||
throw new IllegalArgumentException("bad Authorization header, not Basic");
|
||||
}
|
||||
|
||||
String joined = new String(Base64.getDecoder().decode(authorization.substring(toTrim.length()).getBytes()));
|
||||
|
||||
System.out.println("decoded header:\n----\n" + joined + "\n----" );
|
||||
|
||||
String[] parts = joined.split(":");
|
||||
if(parts.length != 2){
|
||||
throw new IllegalArgumentException("bad Authorization header, more than two segments");
|
||||
}
|
||||
|
||||
User fetched = US.findByAuthentication(parts[0], parts[1]);
|
||||
if(null == fetched){
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return JS.createToken(fetched, null);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public User createUser(@RequestBody User user)
|
||||
throws InvalidEntityException
|
||||
{
|
||||
System.out.println("would try to create " + user);
|
||||
return US.insert(user);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public User updateUser(
|
||||
@PathVariable(name = "id") String userId,
|
||||
@RequestBody User user
|
||||
)
|
||||
throws InvalidEntityException
|
||||
{
|
||||
user.setId(userId);
|
||||
return US.update(user);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void closeUser(@PathVariable(name = "id") String userId){
|
||||
US.delete(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.theycallmebeno.usersService.user;
|
||||
|
||||
import com.theycallmebeno.usersService.validation.UserValidator;
|
||||
import com.theycallmebeno.usersService.validation.ValidationUser;
|
||||
import com.theycallmebeno.usersService.validation.InvalidEntityException;
|
||||
|
||||
import com.theycallmebeno.usersService.event.EventService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
|
||||
@Service
|
||||
public class UsersService
|
||||
{
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private EventService ES;
|
||||
|
||||
@Autowired
|
||||
private UserValidator validator;
|
||||
|
||||
public List<User> getAll(){
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
public User findById(String id){
|
||||
return userRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public User findByEmail(String email){
|
||||
return userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
public User findByAuthentication(String email, String password){
|
||||
System.out.println("UserService.findByAuthentication(" + email + ", " + password + ")" );
|
||||
return userRepository.findByEmailAndPassword(email, password);
|
||||
}
|
||||
|
||||
public User insert(User p)
|
||||
throws InvalidEntityException
|
||||
{
|
||||
p.setId(null);
|
||||
|
||||
ValidationUser validation = validator.validate(p, false);
|
||||
if(! validation.isValid()){
|
||||
System.out.println("violations on user " + validation.toErrorsMap());
|
||||
throw new InvalidEntityException(validation);
|
||||
}
|
||||
|
||||
User created;
|
||||
|
||||
try {
|
||||
created = userRepository.save(p);
|
||||
}
|
||||
catch(DuplicateKeyException e){
|
||||
validation.addGenericViolation("email already taken");
|
||||
throw new InvalidEntityException(validation);
|
||||
}
|
||||
if( null != created){
|
||||
ES.userCreated(created);
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
public User update(User u)
|
||||
throws InvalidEntityException
|
||||
{
|
||||
User fetched = findById(u.getId());
|
||||
if(null == fetched){
|
||||
throw new NoSuchElementException("User did not exist");
|
||||
}
|
||||
|
||||
ValidationUser validation = validator.validate(u);
|
||||
if(! validation.isValid()){
|
||||
throw new InvalidEntityException(validation);
|
||||
}
|
||||
|
||||
try {
|
||||
return userRepository.save(u);
|
||||
}
|
||||
catch(DuplicateKeyException e){
|
||||
validation.addGenericViolation("email already taken");
|
||||
throw new InvalidEntityException(validation);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String id)
|
||||
{
|
||||
User fetched = findById(id);
|
||||
|
||||
if(null == fetched){
|
||||
throw new NoSuchElementException("Product did not exist");
|
||||
}
|
||||
userRepository.delete(fetched);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.theycallmebeno.usersService.validation;
|
||||
|
||||
public class InvalidEntityException extends Exception {
|
||||
ValidationEntity entity;
|
||||
|
||||
public InvalidEntityException(ValidationEntity entity){
|
||||
this.entity = entity;
|
||||
}
|
||||
|
||||
public ValidationEntity getEntity(){
|
||||
return this.entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage(){
|
||||
return entity.toErrorsMap().toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.theycallmebeno.usersService.validation;
|
||||
|
||||
import com.theycallmebeno.usersService.user.User;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserValidator {
|
||||
|
||||
public ValidationUser validate(User u, boolean generatedFields){
|
||||
if(! generatedFields){
|
||||
return validateForCreate(u);
|
||||
}
|
||||
else{
|
||||
return validateForUpdate(u);
|
||||
}
|
||||
}
|
||||
|
||||
public ValidationUser validate(User u){
|
||||
return validate(u, true);
|
||||
}
|
||||
|
||||
// type gets already parsed/throw shtuff
|
||||
ValidationUser validateForCreate(User u){
|
||||
if(null == u){
|
||||
throw new IllegalArgumentException("missing User argument");
|
||||
}
|
||||
|
||||
ValidationUser v = new ValidationUser(u);
|
||||
String email = u.getEmail();
|
||||
if(null == email){
|
||||
v.addEmailViolation("missing");
|
||||
}
|
||||
else{
|
||||
String normalized = email.replaceAll("\\t", " ").trim();
|
||||
if(0 == normalized.length()){
|
||||
v.addEmailViolation("empty");
|
||||
}
|
||||
// alnum(+) ( . alnum(+) )(*) @ alnum(+) ( . alnum(+) )(+)
|
||||
if(! email.matches("^\\w+(\\.\\w+)*@\\w+(\\.\\w+)+$")){
|
||||
v.addEmailViolation("value not matching the email addresses schema");
|
||||
}
|
||||
}
|
||||
|
||||
String name = u.getUsername();
|
||||
if(null == name){
|
||||
v.addNameViolation("missing");
|
||||
}
|
||||
else{
|
||||
String normalized = name.replaceAll("\\t", " ").trim();
|
||||
if(0 == normalized.length()){
|
||||
v.addNameViolation("empty");
|
||||
}
|
||||
if(name.length() != normalized.length()){
|
||||
v.addNameViolation("bad whitespaces");
|
||||
}
|
||||
}
|
||||
|
||||
String password = u.getPassword();
|
||||
if(null == password){
|
||||
v.addPasswordViolation("missing");
|
||||
}
|
||||
else{
|
||||
String normalized = password.replaceAll("\\t", " ").trim();
|
||||
if(0 == normalized.length()){
|
||||
v.addPasswordViolation("empty");
|
||||
}
|
||||
if(password.length() != normalized.length()){
|
||||
v.addPasswordViolation("bad whitespaces");
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
ValidationUser validateForUpdate(User u){
|
||||
ValidationUser v = validateForCreate(u);
|
||||
String id = u.getId();
|
||||
if(null == id){
|
||||
v.addIdViolation("missing");
|
||||
}
|
||||
else{
|
||||
String normalized = id.replaceAll("\\t", " ").trim();
|
||||
if(0 == normalized.length()){
|
||||
v.addIdViolation("empty");
|
||||
}
|
||||
if(! id.matches("[\\d,A,B,C,D,E,F,a,b,c,d,e,f]{24}")){
|
||||
v.addIdViolation("value not matching the ObjectIds schema");
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.theycallmebeno.usersService.validation;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
// extended PersistentEntity
|
||||
public abstract class ValidationEntity<T extends Object> {
|
||||
|
||||
private T validData;
|
||||
|
||||
private Set<String> genericViolations = new HashSet<>();
|
||||
|
||||
public Set<String> getGenericViolations(){
|
||||
return genericViolations;
|
||||
}
|
||||
|
||||
public void setGenericViolations(Collection<String> violations) {
|
||||
genericViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addGenericViolation(String violation) {
|
||||
genericViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addGenericViolations(Collection<String> violations) {
|
||||
genericViolations.addAll(violations);
|
||||
}
|
||||
|
||||
public abstract boolean isValid();
|
||||
|
||||
public T getValidData() {
|
||||
return validData;
|
||||
}
|
||||
|
||||
public void setValidData(T target) {
|
||||
this.validData = target;
|
||||
}
|
||||
|
||||
protected static String violationSetToString(Set<String> violationSet) {
|
||||
return violationSet.stream().map(str -> "\"" + str + "\"").collect(Collectors.toSet()).toString();
|
||||
}
|
||||
|
||||
public abstract Map<String, Object> toErrorsMap();
|
||||
|
||||
protected Map<String, Object> mapWithGeneric(){
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("generic", new HashSet<>(genericViolations));
|
||||
return map;
|
||||
}
|
||||
|
||||
public String toString(){
|
||||
return toErrorsMap().entrySet().stream()
|
||||
.map(e -> "\"" + e.getKey() + "\": " + e.getValue())
|
||||
.collect(Collectors.joining(", ", "{ ", " }"));
|
||||
}
|
||||
|
||||
private String wrappedOrNull(Object toWrap){
|
||||
return (null == toWrap) ? "null" : "\"" + toWrap.toString() + "\"";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.theycallmebeno.usersService.validation;
|
||||
|
||||
import com.theycallmebeno.usersService.user.User;
|
||||
import com.theycallmebeno.usersService.user.Customer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationUser extends ValidationEntity<User> {
|
||||
|
||||
private Set<String> idViolations = new HashSet<>();
|
||||
private Set<String> nameViolations = new HashSet<>();
|
||||
private Set<String> emailViolations = new HashSet<>();
|
||||
private Set<String> passwordViolations = new HashSet<>();
|
||||
private Set<String> typeViolations = new HashSet<>();
|
||||
|
||||
public ValidationUser() {
|
||||
this.setValidData(new Customer());
|
||||
}
|
||||
|
||||
public ValidationUser(User u) {
|
||||
this.setValidData(u);
|
||||
}
|
||||
|
||||
public Set<String> getIdViolations(){
|
||||
return idViolations;
|
||||
}
|
||||
|
||||
public void setIdViolations(Collection<String> violations) {
|
||||
idViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addIdViolation(String violation) {
|
||||
idViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addIdViolations(Collection<String> violations) {
|
||||
idViolations.addAll(violations);
|
||||
}
|
||||
|
||||
public Set<String> getNameViolations(){
|
||||
return nameViolations;
|
||||
}
|
||||
|
||||
public void setNameViolations(Collection<String> violations) {
|
||||
nameViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addNameViolation(String violation) {
|
||||
nameViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addNameViolations(Collection<String> violations) {
|
||||
nameViolations.addAll(violations);
|
||||
}
|
||||
|
||||
public Set<String> getEmailViolations(){
|
||||
return emailViolations;
|
||||
}
|
||||
|
||||
public void setEmailViolations(Collection<String> violations) {
|
||||
emailViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addEmailViolation(String violation) {
|
||||
emailViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addEmailViolations(Collection<String> violations) {
|
||||
emailViolations.addAll(violations);
|
||||
}
|
||||
|
||||
public Set<String> getPasswordViolations() {
|
||||
return passwordViolations;
|
||||
}
|
||||
|
||||
public void setPasswordViolations(Collection<String> violations) {
|
||||
passwordViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addPasswordViolation(String violation) {
|
||||
passwordViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addPasswordViolations(Collection<String> violations) {
|
||||
passwordViolations.addAll(violations);
|
||||
}
|
||||
|
||||
public Set<String> getTypeViolations() {
|
||||
return typeViolations;
|
||||
}
|
||||
|
||||
public void setTypeViolations(Collection<String> violations) {
|
||||
typeViolations = new HashSet<String>(violations);
|
||||
}
|
||||
|
||||
public void addTypeViolation(String violation) {
|
||||
typeViolations.add(violation);
|
||||
}
|
||||
|
||||
public void addTypeViolations(Collection<String> violations) {
|
||||
typeViolations.addAll(violations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid() {
|
||||
boolean anyError =
|
||||
(! getIdViolations().isEmpty())
|
||||
||
|
||||
(! getNameViolations().isEmpty())
|
||||
||
|
||||
(! getEmailViolations().isEmpty())
|
||||
||
|
||||
(! getPasswordViolations().isEmpty())
|
||||
||
|
||||
(! getTypeViolations().isEmpty())
|
||||
||
|
||||
(! getGenericViolations().isEmpty());
|
||||
return ! anyError;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> toErrorsMap() {
|
||||
Map<String, Object> map = mapWithGeneric();
|
||||
map.put("id", getIdViolations());
|
||||
map.put("name", getNameViolations());
|
||||
map.put("email", getEmailViolations());
|
||||
map.put("password", getPasswordViolations());
|
||||
map.put("type", getTypeViolations());
|
||||
return map;
|
||||
}
|
||||
|
||||
}
|
||||
4
src/main/resources/application.properties
Normal file
4
src/main/resources/application.properties
Normal file
@@ -0,0 +1,4 @@
|
||||
spring.application.name=userService
|
||||
spring.data.mongodb.database=bufus_users_testing
|
||||
spring.data.mongodb.host=bufus_users_net_UNUSED
|
||||
spring.kafka.bootstrap-servers=host.docker.internal:9092
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.theycallmebeno.usersService;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class RestProductsServiceApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user