Compare commits
58
Commits
90a69d1663
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43473ebffc | ||
|
|
c5f37a9b5b | ||
|
|
371ba904e2 | ||
|
|
977187e0bb | ||
|
|
41ec2517a4 | ||
|
|
bc804bedbc | ||
|
|
d4eaad7361 | ||
|
|
b072de9eca | ||
|
|
20b4421998 | ||
|
|
0fe5c18f25 | ||
|
|
a930e59ecc | ||
|
|
7015eba8d1 | ||
|
|
37422b7e10 | ||
|
|
5980d30ad5 | ||
|
|
54e545094b | ||
|
|
cb591cf7da | ||
|
|
3162514d62 | ||
|
|
81d09cd60d | ||
|
|
b88115b04a | ||
|
|
e95b735bba | ||
|
|
04e97b9922 | ||
|
|
e2e5237dfa | ||
|
|
3549fa1272 | ||
|
|
53495fcae5 | ||
|
|
00dc2e0ce8 | ||
|
|
505cf3abe6 | ||
|
|
ae364d0962 | ||
|
|
b5ae070f83 | ||
|
|
8cfb4f627d | ||
|
|
0a5a78f153 | ||
|
|
fc7cb3c2f7 | ||
|
|
7e971fd079 | ||
|
|
572c41528d | ||
|
|
a86815cdd1 | ||
|
|
f3e2c295d9 | ||
|
|
ff87cca8c4 | ||
|
|
c7cc49fc70 | ||
|
|
a2adb00717 | ||
|
|
a406fc4182 | ||
|
|
c182c0478c | ||
|
|
8117640b5a | ||
|
|
c1940875e3 | ||
|
|
ac06b58696 | ||
|
|
a51115e8e7 | ||
|
|
db986c8fb5 | ||
|
|
d62a331ca9 | ||
|
|
c664aca308 | ||
|
|
51485e68a2 | ||
|
|
0d8f4c63d4 | ||
|
|
209696539a | ||
|
|
d938faf618 | ||
|
|
f20d14e3af | ||
|
|
95d5ba2193 | ||
|
|
0575164236 | ||
|
|
fbafbfe27b | ||
|
|
bec71fe108 | ||
|
|
2bf1bffdf0 | ||
|
|
586b5008a5 |
-26
@@ -1,26 +0,0 @@
|
||||
# ---> Java
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
replay_pid*
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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.
|
||||
wrapperVersion=3.3.2
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip
|
||||
@@ -1,3 +0,0 @@
|
||||
# auth-server
|
||||
|
||||
microserive for authentication and authoroization
|
||||
@@ -0,0 +1,8 @@
|
||||
services:
|
||||
rabbitmq:
|
||||
image: 'rabbitmq:latest'
|
||||
environment:
|
||||
- 'RABBITMQ_DEFAULT_PASS=secret'
|
||||
- 'RABBITMQ_DEFAULT_USER=myuser'
|
||||
ports:
|
||||
- '5672'
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.2
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
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"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
@@ -0,0 +1,149 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. 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,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.2
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
|
||||
}
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
@@ -0,0 +1,317 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.4.0-SNAPSHOT</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.stktrk</groupId>
|
||||
<artifactId>app</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>app</name>
|
||||
<description>stktrk backend</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- FIXME these three are from the sample code-->
|
||||
<!-- Spring Security and JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>0.9.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- OAuth2 Client -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Web and JPA -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<!-- FIXME these three are from the sample code-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jooq</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.flywaydb/flyway-database-postgresql -->
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
<version>10.4.1</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-docker-compose</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-testcontainers</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.amqp</groupId>
|
||||
<artifactId>spring-rabbit-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>rabbitmq</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>io.undertow</groupId>
|
||||
<artifactId>undertow-servlet</artifactId>
|
||||
<version>2.3.17.Final</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.arcadedb</groupId>
|
||||
<artifactId>arcadedb-gremlin</artifactId>
|
||||
<version>24.6.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.arcadedb</groupId>
|
||||
<artifactId>arcadedb-server</artifactId>
|
||||
<version>24.6.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tinkerpop</groupId>
|
||||
<artifactId>gremlin-driver</artifactId>
|
||||
<version>3.7.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.tinkerpop/gremlin-server -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tinkerpop</groupId>
|
||||
<artifactId>gremlin-server</artifactId>
|
||||
<version>3.7.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.opencypher/util-9.0 -->
|
||||
<dependency>
|
||||
<groupId>org.opencypher</groupId>
|
||||
<artifactId>util-9.0</artifactId>
|
||||
<version>9.0.1</version>
|
||||
</dependency>
|
||||
<!--
|
||||
leaving these here for now, documentation apparently lied about needing them...
|
||||
-->
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.tinkerpop/gremlin-groovy -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tinkerpop</groupId>
|
||||
<artifactId>gremlin-groovy</artifactId>
|
||||
<version>3.7.2</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.opencypher/util-9.0 -->
|
||||
<dependency>
|
||||
<groupId>org.opencypher.gremlin</groupId>
|
||||
<artifactId>translation</artifactId>
|
||||
<version>1.0.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hashids</groupId>
|
||||
<artifactId>hashids</artifactId>
|
||||
<version>1.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>2.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.javafaker</groupId>
|
||||
<artifactId>javafaker</artifactId>
|
||||
<version>1.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-maven-plugin</artifactId>
|
||||
<version>10.17.2</version>
|
||||
<configuration>
|
||||
|
||||
|
||||
|
||||
<configFiles>${project.basedir}/src/main/resources/application.properties</configFiles>
|
||||
<locations>
|
||||
<location>classpath:com/stktrk/app/db/migrations</location>
|
||||
</locations>
|
||||
|
||||
<sqlMigrationSeparator>__</sqlMigrationSeparator>
|
||||
|
||||
|
||||
<url>jdbc:postgresql://192.168.178.50:7654/flyway_db</url>
|
||||
<user>flyway_user</user>
|
||||
<password>7e7v55UcYGrY0e3UPYI0qtyMA4YJ1ZkTEaoyZ252GluFkiEMHVT9U5ULS7Rg2rGi</password>
|
||||
<schemas>
|
||||
<schema>flyway_db</schema>
|
||||
</schemas>
|
||||
|
||||
</configuration>
|
||||
|
||||
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!- https://mvnrepository.com/artifact/org.postgresql/postgresql
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.4</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
</plugin>
|
||||
|
||||
-->
|
||||
</plugins>
|
||||
</build>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,16 @@
|
||||
# stktrk.com repository
|
||||
|
||||
Might have to
|
||||
- Build -> Build Project
|
||||
- maven reload all projects
|
||||
- generate sources
|
||||
- mvn clean install
|
||||
- To run
|
||||
- mvn spring-boot:run
|
||||
- in IntelliJ: Run Icon in `src/main/java/com/stktrk/app/AppApplication.java`
|
||||
|
||||
http://localhost:9090/swagger-ui/index.html
|
||||
http://localhost:9090/actuator
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
// https://stackoverflow.com/questions/51221777/failed-to-configure-a-datasource-url-attribute-is-not-specified-and-no-embedd
|
||||
@SpringBootApplication(exclude = {FlywayAutoConfiguration.class})
|
||||
|
||||
public class AppApplication extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(@Nullable String[] args) {
|
||||
SpringApplication.run(AppApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public class CustomGrantedAuthority implements GrantedAuthority {
|
||||
|
||||
private final String role;
|
||||
|
||||
public CustomGrantedAuthority(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return "ROLE_" + role.toUpperCase(); // Converts to Spring-standard role format
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import com.stktrk.auth.domain.account.AccountService;
|
||||
import com.stktrk.auth.domain.account.types.Account;
|
||||
import com.stktrk.auth.domain.account.types.Role;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.SneakyThrows;
|
||||
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
|
||||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
|
||||
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
|
||||
|
||||
@Nonnull
|
||||
private final AccountService accountService;
|
||||
|
||||
@Nonnull public CustomOAuth2UserService(@Nonnull AccountService accountService) {
|
||||
this.accountService = accountService;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@Nonnull public OAuth2User loadUser(@Nonnull OAuth2UserRequest userRequest) {
|
||||
OAuth2User oAuth2User = super.loadUser(userRequest);
|
||||
|
||||
Map<String, Object> attributes = oAuth2User.getAttributes();
|
||||
String email = (String) attributes.get("email");
|
||||
|
||||
// Check if user exists, else create a new user
|
||||
Account existingAccount = accountService.findByEmail(email);
|
||||
if (existingAccount == null) {
|
||||
try {
|
||||
accountService.registerUser(email, "generated-password", List.of(Role.USER));
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
return new DefaultOAuth2User(
|
||||
Collections.singleton(() -> "ROLE_USER"),
|
||||
attributes,
|
||||
"id"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
|
||||
@Configuration
|
||||
public class JwtConfig {
|
||||
|
||||
@Bean
|
||||
public KeyPair keyPair() throws Exception {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(2048);
|
||||
return keyPairGenerator.generateKeyPair();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JWKSource<SecurityContext> jwkSource(KeyPair keyPair) {
|
||||
RSAKey rsaKey = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic())
|
||||
.privateKey((RSAPrivateKey) keyPair.getPrivate())
|
||||
.keyID("my-key-id")
|
||||
.build();
|
||||
return new ImmutableJWKSet<>(new com.nimbusds.jose.jwk.JWKSet(rsaKey));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
|
||||
return new NimbusJwtEncoder(jwkSource);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtDecoder jwtDecoder(KeyPair keyPair) {
|
||||
return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class RBACConfig {
|
||||
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public String adminOnlyOperation() {
|
||||
return "Admin operation success!";
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
public String userOperation() {
|
||||
return "User operation success!";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class RoleAuthentication implements Authentication {
|
||||
private final List<String> roles;
|
||||
private boolean authenticated = false;
|
||||
|
||||
public RoleAuthentication(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "roles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean implies(Subject subject) {
|
||||
return Authentication.super.implies(subject);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles.stream()
|
||||
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDetails() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthenticated() {
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
this.authenticated = isAuthenticated;
|
||||
}
|
||||
|
||||
// Implement other methods as required
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
// **SecurityConfig.java**
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity(prePostEnabled = true)
|
||||
@AllArgsConstructor
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
@Nonnull
|
||||
private final JwtDecoder jwtDecoder;
|
||||
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/public/**", "/auth/**", "/test/signup").permitAll()
|
||||
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**").permitAll()
|
||||
//.requestMatchers("/bearer/**").authenticated() ANNOTATION SEEMS TO WORK?
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
|
||||
.addFilterBefore(new TokenValidatorFilter(jwtDecoder), UsernamePasswordAuthenticationFilter.class)
|
||||
|
||||
.oauth2Login(oauth2 -> oauth2
|
||||
.defaultSuccessUrl("/auth/success")
|
||||
.failureUrl("/auth/failure")
|
||||
)
|
||||
// FiXME !!!! this is a security risk.
|
||||
|
||||
.sessionManagement(session -> session
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
)
|
||||
.csrf(csrf -> csrf.disable());
|
||||
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
ClientRegistration facebookRegistration = ClientRegistration.withRegistrationId("facebook")
|
||||
.clientId("your-facebook-client-id")
|
||||
.clientSecret("your-facebook-client-secret")
|
||||
.redirectUri("{baseUrl}/auth/login/oauth2/code/facebook")
|
||||
.authorizationUri("https://www.facebook.com/v11.0/dialog/oauth")
|
||||
.tokenUri("https://graph.facebook.com/v11.0/oauth/access_token")
|
||||
.userInfoUri("https://graph.facebook.com/me?fields=id,name,email")
|
||||
.userNameAttributeName("id")
|
||||
.clientName("Facebook")
|
||||
.scope("email", "public_profile")
|
||||
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
|
||||
.build();
|
||||
|
||||
return new InMemoryClientRegistrationRepository(facebookRegistration);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
public class TokenValidatorFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtDecoder jwtDecoder;
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
try {
|
||||
// Decode and validate the JWT token
|
||||
Jwt jwt = jwtDecoder.decode(token);
|
||||
|
||||
// Extract claims (e.g., role and username)
|
||||
String username = jwt.getSubject();
|
||||
List<String> roles = jwt.getClaim("role"); // Assumes your JWT has a 'role' claim
|
||||
|
||||
// Set up Spring Security's authentication
|
||||
if (roles != null && !roles.isEmpty()) {
|
||||
RoleAuthentication roleAuth = new RoleAuthentication(roles);
|
||||
roleAuth.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(roleAuth);
|
||||
}
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
// Log error and send unauthorized response
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Proceed with the filter chain
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.stktrk.auth.application;
|
||||
|
||||
import com.stktrk.auth.domain.account.AccountService;
|
||||
import com.stktrk.auth.domain.account.types.Account;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class AuthController {
|
||||
@Nonnull
|
||||
@Autowired
|
||||
private final AccountService accountService;
|
||||
|
||||
@Autowired
|
||||
@Nonnull
|
||||
private final JwtEncoder jwtEncoder;
|
||||
|
||||
@Autowired
|
||||
@Nonnull
|
||||
private final KeyPair keyPair;
|
||||
|
||||
|
||||
/**
|
||||
* @return success notification for social login
|
||||
*/
|
||||
@Nonnull
|
||||
@GetMapping("/success")
|
||||
public String success() {
|
||||
return "Login successful!";
|
||||
}
|
||||
|
||||
/**
|
||||
* @return failure notification for social login
|
||||
*/
|
||||
@Nonnull
|
||||
@GetMapping("/failure")
|
||||
public String failure() {
|
||||
return "Login failed.";
|
||||
}
|
||||
|
||||
|
||||
// FIXME this creates valid tokens on the fly, should be removed from production, or protected for local and dev use only
|
||||
@PostMapping("/token")
|
||||
public String generateToken(@RequestParam String username, @RequestParam String role) {
|
||||
JwtClaimsSet claims = JwtClaimsSet.builder()
|
||||
.issuer("auth-service")
|
||||
.issuedAt(Instant.now())
|
||||
.expiresAt(Instant.now().plusSeconds(3600))
|
||||
.subject(username)
|
||||
.claim("role", role)
|
||||
.build();
|
||||
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Login to local account
|
||||
*
|
||||
* @param username usanername
|
||||
* @param password password
|
||||
* @return JWT token
|
||||
*/
|
||||
@Nonnull
|
||||
@PostMapping("/login")
|
||||
public String login(@RequestParam String username, @RequestParam String password) {
|
||||
Account account = accountService.findByEmail(username);
|
||||
if (account == null || !accountService.verifyPassword(password, account.getPassword())) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials");
|
||||
}
|
||||
|
||||
|
||||
// Generate JWT
|
||||
JwtClaimsSet claims = JwtClaimsSet.builder()
|
||||
.issuer("auth-service")
|
||||
.issuedAt(Instant.now())
|
||||
.expiresAt(Instant.now().plusSeconds(3600))
|
||||
.subject(username)
|
||||
.claim("role", account.getRoles().stream().map ( r-> r.name()).toList())
|
||||
.build();
|
||||
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
// check result in https://fusionauth.io/dev-tools/jwt-decoder
|
||||
|
||||
/**
|
||||
* Offers the possibility for other severs to get to the public key
|
||||
* FIXME should probably not be a thing in production?
|
||||
* @return public key used by the server
|
||||
*/
|
||||
@GetMapping("/publicKey")
|
||||
public String publicKey() {
|
||||
|
||||
|
||||
return "{\"public\":\"" + HexFormat.of().formatHex(keyPair.getPublic().getEncoded()) + "\"}";
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.stktrk.auth.application;
|
||||
|
||||
import com.stktrk.auth.domain.account.types.Role;
|
||||
import com.stktrk.auth.domain.account.AccountService;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/test")
|
||||
public class LocalSignupController {
|
||||
|
||||
@Nullable
|
||||
private final AccountService accountService;
|
||||
|
||||
public LocalSignupController(@Nullable AccountService accountService) {
|
||||
this.accountService = accountService;
|
||||
}
|
||||
|
||||
|
||||
@Nonnull
|
||||
@PostMapping("/signup")
|
||||
public String signUp(@Nonnull @RequestParam String email, @Nonnull @RequestParam String password, @Nonnull @RequestParam List<Role> roles) {
|
||||
|
||||
|
||||
// Register the user
|
||||
try {
|
||||
accountService.registerUser(email, password, roles);
|
||||
} catch (SQLException e) {
|
||||
return e.getMessage();
|
||||
}
|
||||
return "User registered successfully!";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.stktrk.auth.application;
|
||||
|
||||
import jakarta.annotation.Nonnull;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/bearer")
|
||||
public class TestController {
|
||||
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
@Nonnull
|
||||
@GetMapping ("/user")
|
||||
public String isUser () {
|
||||
return "OK";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.stktrk.auth.domain.account;
|
||||
|
||||
import com.stktrk.auth.domain.account.types.Role;
|
||||
import com.stktrk.auth.domain.account.types.Account;
|
||||
import jakarta.annotation.Nonnull;
|
||||
|
||||
import java.util.List;
|
||||
/**
|
||||
* Profile repository
|
||||
*/
|
||||
public interface AccountRepository {
|
||||
/**
|
||||
* Check if a user profile exists, by email
|
||||
* @param email account email
|
||||
* @return account exits
|
||||
*/
|
||||
boolean accountExists(@Nonnull String email);
|
||||
|
||||
/**
|
||||
* returns a single account, with roles
|
||||
* @param email account email
|
||||
* @return account, incl Roles.
|
||||
*/
|
||||
@Nonnull
|
||||
Account findByEmail (@Nonnull String email);
|
||||
|
||||
/**
|
||||
* Create a new user account
|
||||
*
|
||||
* @param email account email serves as unique id
|
||||
* @param password password.
|
||||
* @param roles roles the account is created with.
|
||||
*/
|
||||
void createAccount(@Nonnull String email, @Nonnull String password, List<Role> roles);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.stktrk.auth.domain.account;
|
||||
|
||||
import com.stktrk.auth.domain.account.types.Role;
|
||||
import com.stktrk.auth.domain.account.types.Account;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* account service
|
||||
*/
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class AccountService {
|
||||
@Nonnull
|
||||
private final AccountRepository accountRepository;
|
||||
@Nonnull
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
/**
|
||||
* register a new user account
|
||||
* @param email account email, serves as uniwue ID
|
||||
* @param password password
|
||||
* @param roles roles to be assigned to the account
|
||||
* @throws SQLException thrown on duplicate account creation FIXME
|
||||
*/
|
||||
public void registerUser(@Nonnull String email, @Nonnull String password,@Nonnull List<Role> roles) throws SQLException {
|
||||
|
||||
String encodedPassword = passwordEncoder.encode(password);
|
||||
if (accountRepository.accountExists(email)) {
|
||||
throw new SQLException("User already exists.");
|
||||
}
|
||||
accountRepository.createAccount (email,encodedPassword, roles);
|
||||
}
|
||||
|
||||
/**
|
||||
* used during login to check password validity FIXME we should not expose the password to anywhere should we?
|
||||
* @param rawPassword
|
||||
* @param encodedPassword
|
||||
* @return
|
||||
*/
|
||||
public boolean verifyPassword(@Nonnull String rawPassword, @Nonnull String encodedPassword) {
|
||||
return passwordEncoder.matches(rawPassword, encodedPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* search account by email
|
||||
* @param email account email
|
||||
* @return account
|
||||
*/
|
||||
public Account findByEmail (@Nonnull String email) {
|
||||
return accountRepository.findByEmail (email);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.stktrk.auth.domain.account.types;
|
||||
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.annotation.Nullable;
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Value
|
||||
@Builder
|
||||
public class Account {
|
||||
@Nonnull
|
||||
private final String email;
|
||||
@Nullable
|
||||
private final String password;
|
||||
@Nullable private final List<Role> roles;
|
||||
@Nullable private final String id;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.stktrk.auth.domain.account.types;
|
||||
|
||||
public enum Role {
|
||||
ADMIN,
|
||||
USER
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.stktrk.auth.integration.account;
|
||||
|
||||
import com.arcadedb.gremlin.ArcadeGraph;
|
||||
import com.stktrk.auth.domain.account.types.Role;
|
||||
import com.stktrk.auth.domain.account.AccountRepository;
|
||||
import com.stktrk.auth.domain.account.types.Account;
|
||||
import com.stktrk.auth.integration.flyway.ConnectionPool;
|
||||
import com.stktrk.auth.utils.EncryptId;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
|
||||
import org.apache.tinkerpop.gremlin.structure.Vertex;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.outE;
|
||||
|
||||
/**
|
||||
* Profile repository
|
||||
*/
|
||||
@Repository
|
||||
public class AccountRepositoryImpl implements AccountRepository {
|
||||
/**
|
||||
* Check if a user profile exists, by email
|
||||
* @param email account email
|
||||
* @return account exits
|
||||
*/
|
||||
@Override
|
||||
public boolean accountExists(@Nonnull String email) {
|
||||
ArcadeGraph g = ConnectionPool.getGraph();
|
||||
List<? extends Vertex> accounts = g.traversal().V().hasLabel("Account").has("email", email).toList();
|
||||
g.close();
|
||||
|
||||
return !accounts.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* returns a single account, with roles
|
||||
* @param email account email
|
||||
* @return account, incl Roles.
|
||||
*/
|
||||
@Override
|
||||
public Account findByEmail(@Nonnull String email) {
|
||||
ArcadeGraph g = ConnectionPool.getGraph();
|
||||
List<Map<String, Object>> accounts = g.traversal().V().hasLabel("Account").has("email", email) .project("vertex" ,"roles") // removed "edges"
|
||||
.by() // Include the vertex itself
|
||||
//.by(outE("hasRole").fold()) // Include outgoing edges with "hasRole"
|
||||
.by(outE("hasRole").inV().fold()) // Include target vertices
|
||||
.toList();
|
||||
g.close();
|
||||
|
||||
return accounts.isEmpty() ? null : buildAccount(accounts.getFirst());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user account
|
||||
*
|
||||
* @param email account email serves as unique id
|
||||
* @param password password.
|
||||
* @param roles roles the account is created with.
|
||||
*/
|
||||
@Override
|
||||
public void createAccount(@Nonnull String email, @Nonnull String password, List<Role> roles) {
|
||||
ArcadeGraph g = ConnectionPool.getGraph();
|
||||
|
||||
// TODO remove inject, see if it still works
|
||||
// FIXME we need to deal with roles properly.
|
||||
GraphTraversal<Integer, Vertex> ts = g.traversal().inject(0)
|
||||
.addV("Account")
|
||||
.as("a")
|
||||
.property("email", email)
|
||||
.property("password", password);
|
||||
|
||||
roles.forEach(r -> {
|
||||
ts.V().hasLabel("Role").has("name", r.name()).as(r.name())
|
||||
.addE("hasRole").from ("a"). to (r.name());
|
||||
});
|
||||
|
||||
ts.iterate();
|
||||
g.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* create an account from the DB
|
||||
* @param entry Map with the vettices for account and roles
|
||||
* @return account
|
||||
*/
|
||||
@Nonnull
|
||||
private Account buildAccount(@Nonnull Map<String, Object> entry) {
|
||||
|
||||
Iterable<Vertex> targets = (Iterable<Vertex>) entry.get("roles");
|
||||
List<Role> roles = StreamSupport.stream(targets.spliterator(), false)
|
||||
.map (e -> e.property("name"))
|
||||
.map (p ->(String) p.value())
|
||||
.map (Role::valueOf)
|
||||
.toList();
|
||||
|
||||
Vertex v = (Vertex) entry.get("vertex");
|
||||
|
||||
// FIXMe we should probably ot return the password?
|
||||
return Account.builder()
|
||||
.email((String) v.property("email").value())
|
||||
.password((String) v.property("password").value())
|
||||
.id(EncryptId.encrypt((String) v.id()))
|
||||
.roles(roles)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.stktrk.auth.integration.configuration.types;
|
||||
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "graph")
|
||||
|
||||
public class GraphDbConfig {
|
||||
@Nonnull
|
||||
String host;
|
||||
int httpPort;
|
||||
int postgresPort;
|
||||
@Nonnull
|
||||
String graphName;
|
||||
@Nonnull
|
||||
String user;
|
||||
@Nonnull
|
||||
String password;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.stktrk.auth.integration.flyway;
|
||||
|
||||
import com.arcadedb.database.Database;
|
||||
import com.arcadedb.database.DatabaseFactory;
|
||||
import com.arcadedb.event.BeforeRecordCreateListener;
|
||||
import com.arcadedb.gremlin.ArcadeGraph;
|
||||
import com.arcadedb.gremlin.ArcadeGraphFactory;
|
||||
import com.stktrk.auth.integration.configuration.types.GraphDbConfig;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* provides connection pool for arcade DB
|
||||
*/
|
||||
@Component
|
||||
public class ConnectionPool {
|
||||
@Nullable
|
||||
static ArcadeGraphFactory pool;
|
||||
|
||||
@Autowired
|
||||
@Nullable
|
||||
GraphDbConfig graphDbConfig;
|
||||
|
||||
/**
|
||||
* runautomatically after construction of bean, to late-grab config parameters
|
||||
*/
|
||||
@PostConstruct
|
||||
void init() {
|
||||
pool = ArcadeGraphFactory.withRemote(graphDbConfig.getHost(),
|
||||
graphDbConfig.getHttpPort(),
|
||||
graphDbConfig.getGraphName(),
|
||||
graphDbConfig.getUser(),
|
||||
graphDbConfig.getPassword());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides DB connection from pool
|
||||
*
|
||||
* @return graphFactory to run queries against
|
||||
*/
|
||||
@Nonnull
|
||||
public static ArcadeGraph getGraph() {
|
||||
return pool.get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.stktrk.auth.integration.flyway;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
import org.flywaydb.core.api.output.MigrateResult;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@Configuration
|
||||
public class FlywayConfig {
|
||||
// TODO move to properties
|
||||
// Custom migration history table name
|
||||
@Nullable
|
||||
private static final String SCHEMA_HISTORY_TABLE = "flyway_schema_history_auth_server";
|
||||
|
||||
@Autowired
|
||||
@Nullable
|
||||
private DataSource dataSource;
|
||||
|
||||
@Autowired
|
||||
@Nullable
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
@PostConstruct
|
||||
public void migrate() throws SQLException {
|
||||
|
||||
// Retrieving all migration implementation classes through the Spring container
|
||||
// All implementation classes no longer need to be defined in the `db.migration` package,
|
||||
// they can be placed in any location that supports Bean scanning
|
||||
JavaMigration[] migrationBeans = applicationContext
|
||||
.getBeansOfType(JavaMigration.class)
|
||||
.values()
|
||||
.toArray(new JavaMigration[0]);
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource) // No need to configure flyway JDBC URL by using the original DataSource
|
||||
.defaultSchema(dataSource.getConnection().getSchema())
|
||||
.locations("integration/flyway/migration") // Default migration script path
|
||||
.table(SCHEMA_HISTORY_TABLE) // Default migration history table is `flyway_schema_history`
|
||||
.baselineOnMigrate(true) // Default false, must be set to true for initial migration on existing databases
|
||||
.baselineVersion("0") // Default "1"
|
||||
.executeInTransaction(true) // Performing migration as a transaction
|
||||
.installedBy(applicationContext.getId()) // Using microservice name as migration executor
|
||||
.javaMigrations(migrationBeans) // Registering migration classes
|
||||
.load();
|
||||
MigrateResult migrate = flyway.migrate(); // Executing migration by calling subclass implementations sequentially
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.stktrk.auth.integration.flyway;
|
||||
|
||||
import com.stktrk.auth.integration.configuration.types.GraphDbConfig;
|
||||
import jakarta.annotation.Nonnull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* helper interface to reduce overhead on DB migration classes
|
||||
*/
|
||||
public interface MigrationWrapper {
|
||||
/**
|
||||
* default method to allow easy application of arbitrary SQL
|
||||
*
|
||||
* @param graphDbConfig DB configuration
|
||||
* @param query SQL query
|
||||
* @throws ClassNotFoundException Driver missing
|
||||
* @throws SQLException SQL error
|
||||
*/
|
||||
default void executeQuery(@Nonnull GraphDbConfig graphDbConfig, @Nonnull String query) throws ClassNotFoundException, SQLException {
|
||||
|
||||
Class.forName("org.postgresql.Driver");
|
||||
Properties props = new Properties();
|
||||
|
||||
props.setProperty("user", graphDbConfig.getUser());
|
||||
props.setProperty("password", graphDbConfig.getPassword());
|
||||
props.setProperty("ssl", "false");
|
||||
props.setProperty("sslmode", "disable");
|
||||
|
||||
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://" + graphDbConfig.getHost() + ":" + graphDbConfig.getPostgresPort() + "/" + graphDbConfig.getGraphName(), props)) {
|
||||
Statement st = connection.createStatement();
|
||||
st.execute(query);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.stktrk.auth.integration.flyway.migrations;
|
||||
|
||||
import com.stktrk.auth.integration.configuration.types.GraphDbConfig;
|
||||
import com.stktrk.auth.integration.flyway.MigrationWrapper;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Value;
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Component
|
||||
@Value
|
||||
public class V1__CreateAccount extends BaseJavaMigration implements MigrationWrapper {
|
||||
@Nonnull
|
||||
@Autowired
|
||||
GraphDbConfig graphDbConfig;
|
||||
|
||||
public void migrate(@Nonnull Context context) throws Exception {
|
||||
this.executeQuery(graphDbConfig,"CREATE VERTEX TYPE Account IF NOT EXISTS; CREATE PROPERTY Account.email STRING (MANDATORY true, notnull true); CREATE PROPERTY Account.password STRING (MANDATORY true, notnull true);");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.stktrk.auth.integration.flyway.migrations;
|
||||
|
||||
import com.stktrk.auth.integration.configuration.types.GraphDbConfig;
|
||||
import com.stktrk.auth.integration.flyway.MigrationWrapper;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Value;
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Component
|
||||
@Value
|
||||
public class V2__CreateRoles extends BaseJavaMigration implements MigrationWrapper {
|
||||
@Nonnull
|
||||
@Autowired
|
||||
GraphDbConfig graphDbConfig;
|
||||
|
||||
public void migrate(@Nonnull Context context) throws Exception {
|
||||
this.executeQuery(graphDbConfig,"CREATE VERTEX TYPE Role IF NOT EXISTS; CREATE PROPERTY Role.name STRING (MANDATORY true, notnull true); CREATE VERTEX Role SET name = 'USER'; CREATE VERTEX Role SET name = 'ADMIN'; CREATE EDGE TYPE hasRole IF NOT EXISTS; create index on hasRole (`@in`, `@out`) UNIQUE ; create property hasRole.`@out` LINK OF Account; create property hasRole.`@in` LINK OF Role;");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.stktrk.auth.integration.flyway.migrations;
|
||||
|
||||
import com.stktrk.auth.integration.configuration.types.GraphDbConfig;
|
||||
import com.stktrk.auth.integration.flyway.MigrationWrapper;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Value;
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Component
|
||||
@Value
|
||||
public class V3__427__BaseTypes extends BaseJavaMigration implements MigrationWrapper {
|
||||
@Nonnull
|
||||
@Autowired
|
||||
GraphDbConfig graphDbConfig;
|
||||
|
||||
public void migrate(@Nonnull Context context) throws Exception {
|
||||
this.executeQuery(graphDbConfig,"CREATE VERTEX TYPE V IF NOT EXISTS; CREATE PROPERTY V.createdOn DATETIME (MANDATORY true, notnull true); CREATE PROPERTY V.createdBy STRING (MANDATORY true); CREATE PROPERTY V.changedOn DATETIME; CREATE PROPERTY V.changedBy STRING; CREATE EDGE TYPE E IF NOT EXISTS; CREATE PROPERTY E.createdOn DATETIME (MANDATORY true, notnull true); CREATE PROPERTY E.createdBy STRING (MANDATORY true); CREATE PROPERTY E.changedOn DATETIME; CREATE PROPERTY E.changedBy STRING; ALTER TYPE Account SUPERTYPE +V; Alter Type Role SUPERTYPE +V; Alter Type hasRole SUPERTYPE +E");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.stktrk.auth.utils;
|
||||
|
||||
import com.arcadedb.database.RID;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import org.hashids.Hashids;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
public class EncryptId {
|
||||
|
||||
// TODO move salt into properties
|
||||
@Nonnull
|
||||
private static final String SALT = "yG8kWVG0kei4wqwXGgt99AXxJWD7K2fnK4xv3BDR0M0AHchvFFCjFJK4VH1nLvm1";
|
||||
|
||||
@Nonnull
|
||||
public static String encrypt(@Nonnull RID rid) {
|
||||
return new Hashids(SALT).encode(rid.getBucketId(), rid.getPosition());
|
||||
}
|
||||
|
||||
// TODO illegal argument exception thrown from RID - if we only allow this to come from the DB, we should be good.
|
||||
@Nonnull
|
||||
public static String encrypt(@NotEmpty String rid) {
|
||||
RID obj = new RID(rid);
|
||||
return new Hashids(SALT).encode(obj.getBucketId(), obj.getPosition());
|
||||
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static RID decrypt(@NotEmpty String hash) throws InvalidKeyException {
|
||||
long[] res = new Hashids(SALT).decode(hash);
|
||||
if (res == null || res.length != 2 ) {
|
||||
throw new InvalidKeyException("invalid id");
|
||||
}
|
||||
return new RID((int) res[0], res[1]);
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Boolean isValidRid (String rid) {
|
||||
return rid.matches("#\\d+\\.\\d+");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
spring.application.name=app
|
||||
server.port=9091
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.datasource.url= jdbc:postgresql://192.168.178.50:7654/flyway_db
|
||||
spring.datasource.username=flyway_user
|
||||
spring.datasource.password=7e7v55UcYGrY0e3UPYI0qtyMA4YJ1ZkTEaoyZ252GluFkiEMHVT9U5ULS7Rg2rGi
|
||||
spring.datasource.defaultSchema=flyway_db
|
||||
spring.datasource.hikari.schema=flyway_db
|
||||
|
||||
graph.user=root
|
||||
graph.password=playwithdata
|
||||
graph.connection=jdbc:postgresql://192.168.178.50:5432/auth
|
||||
graph.http-port:2480
|
||||
graph.postgres-port:5432
|
||||
graph.host=192.168.178.50
|
||||
graph.graph-name=auth
|
||||
@@ -0,0 +1,47 @@
|
||||
spring.application.name=auth
|
||||
server.port=9091
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
|
||||
#spring.flyway.user=flyway_user
|
||||
#spring.flyway.password=7e7v55UcYGrY0e3UPYI0qtyMA4YJ1ZkTEaoyZ252GluFkiEMHVT9U5ULS7Rg2rGi
|
||||
#spring.flyway.schemas=flyway_db
|
||||
#spring.flyway.url=jdbc:postgresql://192.168.178.50:7654/flyway_db
|
||||
#spring.flyway.locations=classpath:com/stktrk/app/db/migrations
|
||||
|
||||
|
||||
#spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
#spring.datasource.url= jdbc:postgresql://192.168.178.50:7654/flyway_db
|
||||
#spring.datasource.username=flyway_user2
|
||||
#spring.datasource.password=7e7v55UcYGrY0e3UPYI0qtyMA4YJ1ZkTEaoyZ252GluFkiEMHVT9U5ULS7Rg2rGi
|
||||
#spring.datasource.defaultSchema=flyway_db
|
||||
#spring.datasource.hikari.schema=flyway_db
|
||||
|
||||
#graph.user=root
|
||||
##graph.password=playwithdata
|
||||
#graph.connection=jdbc:postgresql://192.168.178.50:5432/graph
|
||||
#graph.http-port:2480
|
||||
#graph.postgres-port:5432
|
||||
#graph.host=192.168.178.50
|
||||
#graph.graph-name=graph
|
||||
|
||||
#spring.flyway.user=flyway_user
|
||||
#spring.flyway.password=7e7v55UcYGrY0e3UPYI0qtyMA4YJ1ZkTEaoyZ252GluFkiEMHVT9U5ULS7Rg2rGi
|
||||
#spring.flyway.schemas=flyway_db
|
||||
#spring.flyway.url=jdbc:postgresql://192.168.178.50:7654/flyway_db
|
||||
#spring.flyway.locations=classpath:com/stktrk/app/db/migrations
|
||||
|
||||
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.datasource.url= jdbc:postgresql://localhost:7654/flyway_db
|
||||
spring.datasource.username=flyway_user
|
||||
spring.datasource.password=stdUNmu7KTUQV6KGMKjzHIiwQ2gbipArvg02
|
||||
spring.datasource.defaultSchema=flyway_db
|
||||
spring.datasource.hikari.schema=flyway_db
|
||||
|
||||
graph.user=root
|
||||
graph.password=playwithdata
|
||||
graph.connection=jdbc:postgresql://localhost:5432/graph
|
||||
graph.http-port:2480
|
||||
graph.postgres-port:5432
|
||||
graph.host=localhost
|
||||
graph.graph-name=graph
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@Import(TestcontainersConfiguration.class)
|
||||
@SpringBootTest
|
||||
class AppApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import jakarta.annotation.Nonnull;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
|
||||
public class TestAppApplication {
|
||||
|
||||
public static void main(@Nonnull String[] args) {
|
||||
SpringApplication.from(AppApplication::main).with(TestcontainersConfiguration.class).run(args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.stktrk.auth;
|
||||
|
||||
import jakarta.annotation.Nonnull;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.testcontainers.containers.RabbitMQContainer;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
@TestConfiguration(proxyBeanMethods = false)
|
||||
class TestcontainersConfiguration {
|
||||
|
||||
@Bean
|
||||
@ServiceConnection
|
||||
@Nonnull
|
||||
RabbitMQContainer rabbitContainer() {
|
||||
return new RabbitMQContainer(DockerImageName.parse("rabbitmq:latest"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.stktrk.auth.utils;
|
||||
|
||||
import com.arcadedb.database.RID;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
class EncryptIdTest {
|
||||
|
||||
|
||||
@Test
|
||||
void encrypt() {
|
||||
Assertions.assertEquals("nOua", EncryptId.encrypt(new RID(1,2L)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void decrypt() throws InvalidKeyException {
|
||||
Assertions.assertEquals(new RID(1,2L), EncryptId.decrypt("nOua"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user