This commit is contained in:
Universall 2025-02-18 18:09:27 +03:00
commit 5ee43aca29
50 changed files with 1659 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

19
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@ -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
#
# http://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.9/apache-maven-3.9.9-bin.zip

259
mvnw vendored Normal file
View File

@ -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
#
# http://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 "$@"

149
mvnw.cmd vendored Normal file
View File

@ -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 http://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"

134
pom.xml Normal file
View File

@ -0,0 +1,134 @@
<?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.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.displaynone</groupId>
<artifactId>ACSS</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ACSS</name>
<description>ACSS</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<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>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.displaynone.acss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AcssApplication {
public static void main(String[] args) {
SpringApplication.run(AcssApplication.class, args);
}
}

View File

@ -0,0 +1,90 @@
package com.displaynone.acss.components.auth;
import com.displaynone.acss.components.auth.internal_utils.JWTUtils;
import com.displaynone.acss.components.auth.models.AuthTokenPair;
import com.displaynone.acss.components.auth.models.user.UserDTO;
import com.displaynone.acss.components.auth.models.user.UserMapper;
import com.displaynone.acss.components.auth.models.user.UserModel;
import com.displaynone.acss.components.auth.models.user.service.UserService;
import com.displaynone.acss.exception.generics.UnauthorizedHTTPException;
import com.displaynone.acss.utils.Pair;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
@RequiredArgsConstructor
public class AuthComponent implements UserDetailsService {
private JWTUtils jwtUtils;
private final UserService userService;
@Autowired
public AuthComponent(JWTUtils jwtUtils, UserService userService) {
this.jwtUtils = jwtUtils;
this.userService = userService;
}
private AuthTokenPair _generateTokenPair(@NonNull UserDetails user) {
String accessToken = jwtUtils.generateAccessToken(user);
String refreshToken = jwtUtils.generateRefreshToken(user);
return new AuthTokenPair(accessToken, refreshToken);
}
private Optional<UserModel> _findModelByLogin(@NonNull String login) {
return userService.findByLogin(login);
}
private UserModel _findModelByLoginStrict(@NonNull String login) {
return userService.findByLoginStrict(login);
}
public UsernamePasswordAuthenticationToken authenticateByAccessToken(@NonNull String accessToken) {
if (!jwtUtils.validateToken(accessToken)) throw new UnauthorizedHTTPException("Invalid access token");
String username = jwtUtils.getLogin(accessToken);
UserModel userModel = _findModelByLoginStrict(username);
return new UsernamePasswordAuthenticationToken(userModel, null, userModel.getAuthorities());
}
public AuthTokenPair refresh(@NonNull String refreshToken) {
if (!jwtUtils.validateToken(refreshToken)) throw new UnauthorizedHTTPException("Invalid refresh token");
String login = jwtUtils.getLogin(refreshToken);
System.out.println(login);
UserModel userModel = _findModelByLoginStrict(login);
return _generateTokenPair(userModel);
}
public Optional<UserDTO> findByLogin(@NonNull String login) {
Optional<UserModel> userModel = _findModelByLogin(login);
return userModel.map(UserMapper::convertToDTO);
}
public UserDTO findByLoginStrict(@NonNull String login) {
return UserMapper.convertToDTO(userService.findByLoginStrict(login));
}
public Pair<UserModel, AuthTokenPair> authenticate(@NonNull String login) {
UserModel userModel = _findModelByLoginStrict(login);
return Pair.of(userModel, authenticate(userModel));
}
public AuthTokenPair authenticate(@NonNull UserDetails user) {
return _generateTokenPair(user);
}
@Override
public UserDetails loadUserByUsername(@NonNull String username) throws UsernameNotFoundException {
return _findModelByLoginStrict(username);
}
}

View File

@ -0,0 +1,77 @@
package com.displaynone.acss.components.auth.internal_utils;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Component
public class JWTUtils {
@Value("${app.jwtSecret}")
private String SECRET_KEY;
@Value("${app.jwtExpirationMs}")
private int ACCESS_TOKEN_EXPIRATION;
@Value("${app.jwtRefreshExpirationMs}")
private int REFRESH_TOKEN_EXPIRATION;
public String generateAccessToken(@NonNull UserDetails userDetails) {
Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
System.out.println(userDetails);
return Jwts.builder()
.setSubject(userDetails.getUsername())
.claim("roles", userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION))
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
public String generateRefreshToken(@NonNull UserDetails userDetails) {
Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRATION))
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
public Jws<Claims> parseToken(@NonNull String token) {
Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
}
public String getLogin(@NonNull String token) {
return parseToken(token).getBody().getSubject();
}
public Set<String> extractRoles(@NonNull String token) {
Claims claims = parseToken(token).getBody();
List<?> rawRoles = claims.get("roles", List.class);
return rawRoles.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.toSet());
}
public boolean validateToken(@NonNull String token) {
try {
parseToken(token);
return true;
} catch (JwtException e) {
return false;
}
}
}

View File

@ -0,0 +1,14 @@
package com.displaynone.acss.components.auth.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthTokenPair {
private String accessToken;
private String refreshToken;
}

View File

@ -0,0 +1,9 @@
package com.displaynone.acss.components.auth.models.role;
import lombok.Data;
@Data
public class RoleDTO {
private Long id;
private RoleType name;
}

View File

@ -0,0 +1,23 @@
package com.displaynone.acss.components.auth.models.role;
import com.displaynone.acss.utils.GlobalUtils;
import lombok.experimental.UtilityClass;
import java.util.Collection;
import java.util.List;
@UtilityClass
public class RoleMapper {
public RoleDTO convertToDTO(RoleModel model) {
RoleDTO dto = new RoleDTO();
dto.setId(model.getId());
dto.setName(model.getName());
return dto;
}
public List<RoleDTO> convertAllToDTO(Collection<RoleModel> models) {
return GlobalUtils.convertAllToDTO(models, RoleMapper::convertToDTO);
}
}

View File

@ -0,0 +1,27 @@
package com.displaynone.acss.components.auth.models.role;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RoleModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
@Enumerated(EnumType.STRING)
private RoleType name;
// @ToString.Exclude
// @ManyToMany(mappedBy = "roles")
// private Set<UserModel> users;
}

View File

@ -0,0 +1,9 @@
package com.displaynone.acss.components.auth.models.role;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface RoleRepository extends JpaRepository<RoleModel, Long> {
Optional<RoleModel> findByName(RoleType name);
}

View File

@ -0,0 +1,6 @@
package com.displaynone.acss.components.auth.models.role;
public enum RoleType {
ROLE_USER,
ROLE_ADMIN
}

View File

@ -0,0 +1,4 @@
package com.displaynone.acss.components.auth.models.role.service;
public interface RoleService {
}

View File

@ -0,0 +1,11 @@
package com.displaynone.acss.components.auth.models.role.service;
import com.displaynone.acss.components.auth.models.role.RoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RoleServiceImpl {
private final RoleRepository roleRepository;
}

View File

@ -0,0 +1,18 @@
package com.displaynone.acss.components.auth.models.user;
import com.displaynone.acss.components.auth.models.role.RoleModel;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Set;
@Data
public class UserDTO {
private Long id;
private String login;
private String name;
private String photo;
private String position;
private LocalDateTime lastVisit;
private Set<RoleModel> roles;
}

View File

@ -0,0 +1,28 @@
package com.displaynone.acss.components.auth.models.user;
import com.displaynone.acss.utils.GlobalUtils;
import lombok.experimental.UtilityClass;
import java.util.Collection;
import java.util.List;
@UtilityClass
public class UserMapper {
public UserDTO convertToDTO(UserModel model) {
UserDTO dto = new UserDTO();
dto.setId(model.getId());
dto.setLogin(model.getLogin());
dto.setName(model.getName());
dto.setPhoto(model.getPhoto());
dto.setPosition(model.getPosition());
dto.setLastVisit(model.getLastVisit());
dto.setRoles(model.getRoles());
return dto;
}
public List<UserDTO> convertAllToDTO(Collection<UserModel> models) {
return GlobalUtils.convertAllToDTO(models, UserMapper::convertToDTO);
}
}

View File

@ -0,0 +1,86 @@
package com.displaynone.acss.components.auth.models.user;
import com.displaynone.acss.components.auth.models.role.RoleModel;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserModel implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String login;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String photo;
@Column(nullable = false)
private String position;
@Column(nullable = false)
private LocalDateTime lastVisit;
@EqualsAndHashCode.Exclude
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<RoleModel> roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toSet());
}
@Override
public String getUsername() {
return login;
}
@Override
public String getPassword() {
return "";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@ -0,0 +1,9 @@
package com.displaynone.acss.components.auth.models.user;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<UserModel, Long> {
Optional<UserModel> findByLogin(String login);
}

View File

@ -0,0 +1,13 @@
package com.displaynone.acss.components.auth.models.user.service;
import com.displaynone.acss.components.auth.models.user.UserModel;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public interface UserService {
Optional<UserModel> findByLogin(String login);
UserModel findByLoginStrict(String login);
}

View File

@ -0,0 +1,28 @@
package com.displaynone.acss.components.auth.models.user.service;
import com.displaynone.acss.components.auth.models.user.UserModel;
import com.displaynone.acss.components.auth.models.user.UserRepository;
import com.displaynone.acss.exception.generics.NotFoundHTTPException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public Optional<UserModel> findByLogin(String login) {
return userRepository.findByLogin(login);
}
@Override
public UserModel findByLoginStrict(String login) {
Optional<UserModel> user = findByLogin(login);
if (user.isEmpty()) throw new NotFoundHTTPException("User not found");
return user.get();
}
}

View File

@ -0,0 +1,58 @@
package com.displaynone.acss.controllers.auth;
import com.displaynone.acss.components.auth.AuthComponent;
import com.displaynone.acss.components.auth.models.AuthTokenPair;
import com.displaynone.acss.components.auth.models.user.UserDTO;
import com.displaynone.acss.components.auth.models.user.UserModel;
import com.displaynone.acss.exception.generics.BadRequestHTTPException;
import com.displaynone.acss.exception.generics.NotFoundHTTPException;
import com.displaynone.acss.exception.generics.UnauthorizedHTTPException;
import com.displaynone.acss.utils.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthComponent authComponent;
@Autowired
public AuthController(AuthComponent authComponent) {
this.authComponent = authComponent;
}
@PostMapping("/login")
public ResponseEntity<AuthTokenPair> login(@RequestBody LoginRequestBody loginRequest) {
String login = loginRequest.getLogin();
if (login == null) throw new BadRequestHTTPException("Login not specified");
Pair<UserModel, AuthTokenPair> authInfo;
try {
authInfo = authComponent.authenticate(login);
} catch (NotFoundHTTPException e) {
throw new UnauthorizedHTTPException(e.getMessage());
}
return ResponseEntity.ok(authInfo.getSecond());
}
@PostMapping("/refresh")
public ResponseEntity<?> refreshToken(@RequestBody TokenRefreshRequestBody request) {
String requestRefreshToken = request.getRefreshToken();
if (requestRefreshToken == null) throw new BadRequestHTTPException("Refresh token not specified");
AuthTokenPair authTokenPair;
try {
authTokenPair = authComponent.refresh(requestRefreshToken);
} catch (NotFoundHTTPException e) {
throw new UnauthorizedHTTPException(e.getMessage());
}
return ResponseEntity.ok(authTokenPair);
}
}

View File

@ -0,0 +1,8 @@
package com.displaynone.acss.controllers.auth;
import lombok.Data;
@Data
public class LoginRequestBody {
private String login;
}

View File

@ -0,0 +1,8 @@
package com.displaynone.acss.controllers.auth;
import lombok.Data;
@Data
public class TokenRefreshRequestBody {
public String refreshToken;
}

View File

@ -0,0 +1,20 @@
package com.displaynone.acss.controllers.user;
import com.displaynone.acss.components.auth.models.user.UserDTO;
import com.displaynone.acss.components.auth.models.user.UserMapper;
import com.displaynone.acss.components.auth.models.user.UserModel;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/me")
public ResponseEntity<UserDTO> getMe() {
UserModel user = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return ResponseEntity.ok(UserMapper.convertToDTO(user));
}
}

View File

@ -0,0 +1,12 @@
package com.displaynone.acss.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class ErrorResponse {
private int status;
private String error;
private String message;
}

View File

@ -0,0 +1,11 @@
package com.displaynone.acss.exception.generics;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class AlreadyExistsHTTPException extends RuntimeException {
public AlreadyExistsHTTPException(String message) {
super(message);
}
}

View File

@ -0,0 +1,12 @@
package com.displaynone.acss.exception.generics;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestHTTPException extends RuntimeException {
public BadRequestHTTPException(String message) {
super(message);
}
}

View File

@ -0,0 +1,11 @@
package com.displaynone.acss.exception.generics;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundHTTPException extends RuntimeException {
public NotFoundHTTPException(String message) {
super(message);
}
}

View File

@ -0,0 +1,11 @@
package com.displaynone.acss.exception.generics;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class UnauthorizedHTTPException extends RuntimeException {
public UnauthorizedHTTPException(String message) {
super(message);
}
}

View File

@ -0,0 +1,76 @@
package com.displaynone.acss.exception.handler;
import com.displaynone.acss.exception.*;
import com.displaynone.acss.exception.generics.AlreadyExistsHTTPException;
import com.displaynone.acss.exception.generics.BadRequestHTTPException;
import com.displaynone.acss.exception.generics.NotFoundHTTPException;
import com.displaynone.acss.exception.generics.UnauthorizedHTTPException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
@RestControllerAdvice
public class GlobalExceptionHandler {
public static ResponseEntity<ErrorResponse> buildErrorResponse(Exception e, HttpStatus status, @Nullable String message) {
ErrorResponse errorResponse = new ErrorResponse(
status.value(),
status.getReasonPhrase(),
message == null ? e.getMessage() : message
);
return new ResponseEntity<>(errorResponse, status);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception e, WebRequest request) {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
logger.error("Unexpected error occurred", e);
return buildErrorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR, "Unexpected error occurred");
}
@ExceptionHandler(BadRequestHTTPException.class)
public ResponseEntity<ErrorResponse> handleBadBadRequestHTTPException(BadRequestHTTPException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.BAD_REQUEST, null);
}
@ExceptionHandler(NotFoundHTTPException.class)
public ResponseEntity<ErrorResponse> handleNotFoundHTTPException(NotFoundHTTPException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.NOT_FOUND, null);
}
@ExceptionHandler(AlreadyExistsHTTPException.class)
public ResponseEntity<ErrorResponse> handleAlreadyExistsHTTPException(AlreadyExistsHTTPException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.CONFLICT, null);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ErrorResponse> handleHttpMessageNotReadableException(InvalidFormatException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.BAD_REQUEST, "Bad request payload format: failed to parse");
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<ErrorResponse> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.METHOD_NOT_ALLOWED, null);
}
@ExceptionHandler(UnauthorizedHTTPException.class)
public ResponseEntity<ErrorResponse> handleUnauthorizedHTTPException(UnauthorizedHTTPException e, WebRequest request) {
return buildErrorResponse(e, HttpStatus.UNAUTHORIZED, null);
}
@ExceptionHandler(InternalAuthenticationServiceException.class)
public ResponseEntity<ErrorResponse> handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e, WebRequest request) {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
logger.error("Unexpected error occurred", e);
return buildErrorResponse(e, HttpStatus.UNAUTHORIZED, "Unauthorized: unexpected error occurred");
}
}

View File

@ -0,0 +1,57 @@
package com.displaynone.acss.security;
import com.displaynone.acss.components.auth.AuthComponent;
import com.displaynone.acss.exception.ErrorResponse;
import com.displaynone.acss.exception.generics.NotFoundHTTPException;
import com.displaynone.acss.exception.generics.UnauthorizedHTTPException;
import com.displaynone.acss.exception.handler.GlobalExceptionHandler;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final AuthComponent authComponent;
private String _getJWTHeader(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) return headerAuth.substring(7);
return null;
}
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
String jwt = _getJWTHeader(request);
if (jwt == null) {
filterChain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication;
try {
authentication = authComponent.authenticateByAccessToken(jwt);
} catch (NotFoundHTTPException e) {
ResponseEntity<ErrorResponse> responseEntity = GlobalExceptionHandler.buildErrorResponse(new UnauthorizedHTTPException(e.getMessage()), HttpStatus.UNAUTHORIZED, null);
return; // TODO
}
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}

View File

@ -0,0 +1,61 @@
package com.displaynone.acss.security;
import com.displaynone.acss.components.auth.AuthComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
private final AuthComponent authComponent;
public WebSecurityConfig(AuthComponent authComponent) {
this.authComponent = authComponent;
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(authComponent);
provider.setPasswordEncoder(passwordEncoder());
provider.setHideUserNotFoundExceptions(false);
return provider;
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authBuilder.authenticationProvider(daoAuthenticationProvider());
return authBuilder.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtAuthenticationFilter(authComponent), org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,5 @@
package com.displaynone.acss.utils;
public interface EntityMapper<EntityT, DtoT> {
DtoT convertToDTO(EntityT entity);
}

View File

@ -0,0 +1,34 @@
package com.displaynone.acss.utils;
import lombok.experimental.UtilityClass;
import org.springframework.lang.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@UtilityClass
public class GlobalUtils {
public boolean hasAnyNullField(Object obj, @Nullable List<String> fieldsToIgnore) {
return Arrays.stream(obj.getClass().getDeclaredFields())
.filter(field -> fieldsToIgnore == null || !fieldsToIgnore.contains(field.getName()))
.peek(field -> field.setAccessible(true))
.anyMatch(field -> {
try {
return field.get(obj) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
public <T> void updateIfNotNull(T value, Consumer<T> setter) {
if (value != null) setter.accept(value);
}
public <EntityT, DtoT> List<DtoT> convertAllToDTO(Collection<EntityT> entities, EntityMapper<EntityT, DtoT> mapper) {
return entities.stream().map(mapper::convertToDTO).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,50 @@
package com.displaynone.acss.utils;
import lombok.Getter;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@Getter
public final class Pair<S, T> {
private final S first;
private final T second;
private Pair(@NonNull S first, @NonNull T second) {
Assert.notNull(first, "First must not be null");
Assert.notNull(second, "Second must not be null");
this.first = first;
this.second = second;
}
public static <S, T> Pair<S, T> of(@NonNull S first, @NonNull T second) {
return new Pair<>(first, second);
}
public static <S, T> Collector<Pair<S, T>, ?, Map<S, T>> toMap() {
return Collectors.toMap(Pair::getFirst, Pair::getSecond);
}
public boolean equals(@Nullable Object object) {
if (this == object) return true;
if (!(object instanceof Pair<?, ?> pair)) return false;
return ObjectUtils.nullSafeEquals(this.first, pair.first) && ObjectUtils.nullSafeEquals(this.second, pair.second);
}
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(this.first);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.second);
return result;
}
public String toString() {
return String.format("%s->%s", this.first, this.second);
}
}

View File

@ -0,0 +1,19 @@
server.port=8080
spring.application.name=ACSS
spring.datasource.url=jdbc:h2:mem:db
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
# Liquibase
spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml
spring.liquibase.enabled=true
spring.jpa.properties.hibernate.transaction.jta.platform=org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform
app.jwtSecret=${JWT_SECRET_KEY}
app.jwtExpirationMs=3600000
app.jwtRefreshExpirationMs=86400000

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet id="1" author="universall">
<createTable tableName="users">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints primaryKey="true"/>
</column>
<column name="login" type="VARCHAR(100)">
<constraints unique="true" nullable="false"/>
</column>
<column name="name" type="VARCHAR(100)"/>
<column name="photo" type="VARCHAR(200)"/>
<column name="position" type="VARCHAR(100)"/>
<column name="last_visit" type="DATETIME"/>
<column name="password" type="VARCHAR(300)"/>
</createTable>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet id="1" author="universall">
<createTable tableName="roles">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints primaryKey="true"/>
</column>
<column name="name" type="VARCHAR(100)">
<constraints unique="true" nullable="false"/>
</column>
</createTable>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<changeSet id="2" author="universall">
<createTable tableName="user_roles">
<column name="user_id" type="INTEGER">
<constraints nullable="false"/>
</column>
<column name="role_id" type="INTEGER">
<constraints nullable="false"/>
</column>
</createTable>
<addForeignKeyConstraint baseTableName="user_roles"
baseColumnNames="user_id"
referencedTableName="users"
referencedColumnNames="id"
constraintName="fk_user_roles_users"/>
<addForeignKeyConstraint baseTableName="user_roles"
baseColumnNames="role_id"
referencedTableName="roles"
referencedColumnNames="id"
constraintName="fk_user_roles_roles"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">
<changeSet id="0001-users-data" author="universall">
<loadData tableName="users" file="db/changelog/data/csv/0001-users-data.csv" separator=";" quotchar='"'/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">
<changeSet id="0002-roles-data" author="universall">
<loadData tableName="roles" file="db/changelog/data/csv/0002-roles-data.csv" separator=";" quotchar='"'/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">
<changeSet id="0002-user_roles-data" author="universall">
<loadData tableName="user_roles" file="db/changelog/data/csv/0003-user_roles-data.csv" separator=";" quotchar='"'/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,11 @@
id;login;name;photo;position;last_visit
1;john_doe;John Doe;https://dummyimage.com/600x400/ff0/000;Software Engineer;2025-02-16T09:00:00
2;jane_smith;Jane Smith;https://dummyimage.com/600x400/ff0/000;Product Manager;2025-02-15T10:30:00
3;bob_jones;Bob Jones;https://dummyimage.com/600x400/ff0/000;QA Engineer;2025-02-14T11:45:00
4;alice_johnson;Alice Johnson;https://dummyimage.com/600x400/ff0/000;UX Designer;2025-02-13T08:15:00
5;charlie_brown;Charlie Brown;https://dummyimage.com/600x400/ff0/000;DevOps Engineer;2025-02-12T14:00:00
6;diana_ross;Diana Ross;https://dummyimage.com/600x400/ff0/000;HR Manager;2025-02-11T13:25:00
7;edward_norton;Edward Norton;https://dummyimage.com/600x400/ff0/000;Backend Developer;2025-02-10T16:50:00
8;fiona_green;Fiona Green;https://dummyimage.com/600x400/ff0/000;Frontend Developer;2025-02-09T12:10:00
9;george_hill;George Hill;https://dummyimage.com/600x400/ff0/000;Data Scientist;2025-02-08T09:30:00
10;helen_white;Helen White;https://dummyimage.com/600x400/ff0/000;Project Manager;2025-02-07T17:20:00
1 id login name photo position last_visit
2 1 john_doe John Doe https://dummyimage.com/600x400/ff0/000 Software Engineer 2025-02-16T09:00:00
3 2 jane_smith Jane Smith https://dummyimage.com/600x400/ff0/000 Product Manager 2025-02-15T10:30:00
4 3 bob_jones Bob Jones https://dummyimage.com/600x400/ff0/000 QA Engineer 2025-02-14T11:45:00
5 4 alice_johnson Alice Johnson https://dummyimage.com/600x400/ff0/000 UX Designer 2025-02-13T08:15:00
6 5 charlie_brown Charlie Brown https://dummyimage.com/600x400/ff0/000 DevOps Engineer 2025-02-12T14:00:00
7 6 diana_ross Diana Ross https://dummyimage.com/600x400/ff0/000 HR Manager 2025-02-11T13:25:00
8 7 edward_norton Edward Norton https://dummyimage.com/600x400/ff0/000 Backend Developer 2025-02-10T16:50:00
9 8 fiona_green Fiona Green https://dummyimage.com/600x400/ff0/000 Frontend Developer 2025-02-09T12:10:00
10 9 george_hill George Hill https://dummyimage.com/600x400/ff0/000 Data Scientist 2025-02-08T09:30:00
11 10 helen_white Helen White https://dummyimage.com/600x400/ff0/000 Project Manager 2025-02-07T17:20:00

View File

@ -0,0 +1,3 @@
id;name
1;ROLE_ADMIN
2;ROLE_USER
1 id name
2 1 ROLE_ADMIN
3 2 ROLE_USER

View File

@ -0,0 +1,11 @@
user_id;role_id
1;1
2;2
3;2
4;1
5;2
6;2
7;1
8;1
9;2
10;1
1 user_id role_id
2 1 1
3 2 2
4 3 2
5 4 1
6 5 2
7 6 2
8 7 1
9 8 1
10 9 2
11 10 1

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
<include file="db/changelog/01/0002-roles.xml"/>
<include file="db/changelog/01/0001-users.xml"/>
<include file="db/changelog/01/0003-user_roles.xml"/>
<include file="db/changelog/data/0002-roles-data.xml"/>
<include file="db/changelog/data/0001-user-data.xml"/>
<include file="db/changelog/data/0003-user_roles-data.xml"/>
</databaseChangeLog>

View File

@ -0,0 +1,13 @@
package com.displaynone.acss;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AcssApplicationTests {
@Test
void contextLoads() {
}
}