Compare commits

...

9 Commits

181 changed files with 9294 additions and 22 deletions

2
.gitattributes vendored Normal file
View File

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

51
.gitignore vendored
View File

@ -1,26 +1,33 @@
# ---> Java
# Compiled class file
*.class
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
# Log file
*.log
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
# BlueJ files
*.ctxt
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
# 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*
### 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

21
compose.yaml Normal file
View File

@ -0,0 +1,21 @@
services:
mongodb:
image: 'mongo:latest'
environment:
- 'MONGO_INITDB_DATABASE=mydatabase'
- 'MONGO_INITDB_ROOT_PASSWORD=secret'
- 'MONGO_INITDB_ROOT_USERNAME=root'
ports:
- '27017'
postgres:
image: 'postgres:latest'
environment:
- 'POSTGRES_DB=mydatabase'
- 'POSTGRES_PASSWORD=secret'
- 'POSTGRES_USER=myuser'
ports:
- '5432'
redis:
image: 'redis:latest'
ports:
- '6379'

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"

200
pom.xml Normal file
View File

@ -0,0 +1,200 @@
<?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.3.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zsc.edu</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>iot-gateway</name>
<description>iot-gateway</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
<mybatis-plus.version>3.5.8</mybatis-plus.version>
<mapstruct.version>1.6.2</mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.17.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</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,61 @@
package com.zsc.edu.gateway;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.gateway.modules.system.dto.RoleDto;
import com.zsc.edu.gateway.modules.system.entity.*;
import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
import com.zsc.edu.gateway.modules.system.repo.RoleRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRolesRepository;
import com.zsc.edu.gateway.modules.system.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* @author zhuang
*/
@RequiredArgsConstructor
@Component
@Profile("!test")
public class FirstTimeInitializer implements CommandLineRunner {
private final DeptRepository deptRepo;
private final RoleRepository roleRepo;
private final RoleService roleService;
private final UserRolesRepository userRolesRepo;
private final UserRepository userRepo;
private final PasswordEncoder passwordEncoder;
@Override
public void run(String... args) throws Exception {
Dept dept1 = new Dept();
Role role = new Role();
if (deptRepo.selectCount(new QueryWrapper<>()) == 0) {
dept1.setName("管理部门");
deptRepo.insert(dept1);
}
if (roleRepo.selectCount(new QueryWrapper<>()) == 0) {
RoleDto dto = new RoleDto();
dto.setName("超级管理员");
// dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
role = roleService.create(dto);
}
if (userRepo.selectCount(new QueryWrapper<>()) == 0) {
User user = new User();
user.setUsername("管理员");
user.setPassword(passwordEncoder.encode("123456"));
user.setEnableState(true);
user.setPhone("13827993921");
user.setEmail("123@qq.com");
user.setDeptId(dept1.getId());
user.setRoleId(role.getId());
userRepo.insert(user);
}
}
}

View File

@ -0,0 +1,16 @@
package com.zsc.edu.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author zhuang
*/
@SpringBootApplication
public class IotGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(IotGatewayApplication.class, args);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.common.enums;
import com.baomidou.mybatisplus.annotation.IEnum;
public enum EnableState implements IEnum<Boolean> {
ENABLE(Boolean.TRUE),
DISABLE(Boolean.FALSE);
private boolean value;
EnableState(Boolean value) {
this.value = value;
}
@Override
public Boolean getValue() {
return this.value;
}
public EnableState reverse() {
return this == ENABLE ? DISABLE : ENABLE;
}
}

View File

@ -0,0 +1,36 @@
package com.zsc.edu.gateway.common.enums;
import com.zsc.edu.gateway.exception.StateException;
import java.util.EnumSet;
/**
* @author harry_yao
*/
public interface IState<T extends Enum<T>> {
/**
* 用于检查对象当前状态是否等于correctStatus
*
* @param correctState 正确状态
*/
default void checkStatus(T correctState) {
if (this != correctState) {
throw new StateException(correctState.getClass(), this, correctState);
}
}
/**
* 用于检查对象当前状态是否在集合correctStates中
*
* @param correctStates 正确状态集合
*/
@SuppressWarnings("SuspiciousMethodCalls")
default void checkStatus(EnumSet<T> correctStates) {
if (!correctStates.contains(this)) {
throw new StateException(this.getClass(), this, correctStates);
}
}
}

View File

@ -0,0 +1,19 @@
package com.zsc.edu.gateway.common.mapstruct;
import org.mapstruct.MappingTarget;
import java.util.List;
public interface BaseMapper<D, E> {
D toDto(E entity);
E toEntity(D dto);
List<D> toDto(List<E> entityList);
List<E> toEntity(List<D> dtoList);
/**
* 更新实体类
* @param dto
* @param entity
*/
void convert(D dto, @MappingTarget E entity);
}

View File

@ -0,0 +1,32 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class ApiException extends RuntimeException {
public ApiException() {
super("发生服务器内部异常,请联系管理员提交故障");
}
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable cause) {
super(message, cause);
}
public ApiException(Throwable cause) {
super(cause);
}
public ApiException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,74 @@
package com.zsc.edu.gateway.exception;
//import com.zsc.study.module.common.domain.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
/**
* @author harry_yao
*/
@Slf4j
@AllArgsConstructor
@RestControllerAdvice
public class ApiExceptionHandler {
@Resource
private ObjectMapper objectMapper;
@ExceptionHandler(value = {ConstraintException.class})
public ResponseEntity<Object> handleException(ConstraintException ex) throws JsonProcessingException {
log.error("ConstraintException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = {NotExistException.class})
public ResponseEntity<Object> handleException(NotExistException ex) throws JsonProcessingException {
log.error("NotExistException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = {StateException.class})
public ResponseEntity<Object> handleException(StateException ex) throws JsonProcessingException {
log.error("StateException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = {StorageException.class})
public ResponseEntity<Object> handleException(StorageException ex) throws JsonProcessingException {
log.error("StorageException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = {UserHasNoIdentityException.class})
public ResponseEntity<Object> handleException(UserHasNoIdentityException ex) throws JsonProcessingException {
log.error("UserHasNoIdentityException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(value = {ValidateException.class})
public ResponseEntity<Object> handleException(ValidateException ex) throws JsonProcessingException {
log.error("ValidateException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(value = {ApiException.class})
public ResponseEntity<Object> handleException(ApiException ex) throws JsonProcessingException {
log.error("ApiException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleException(Exception ex) throws JsonProcessingException {
log.error("Exception: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class ConstraintException extends ApiException {
public ConstraintException(String fieldName, Object fieldValue) {
super(String.format("字段%s的值'%s'不符合要求。", fieldName, fieldValue));
}
public ConstraintException(String fieldName, Object fieldValue, String message) {
super(String.format("字段%s的值'%s'不符合要求,%s", fieldName, fieldValue, message));
}
public ConstraintException(String message) {
super(message);
}
}

View File

@ -0,0 +1,10 @@
package com.zsc.edu.gateway.exception;
/**
* @author zhuang
*/
public class EmptyIdsException extends RuntimeException {
public EmptyIdsException(String message) {
super(message);
}
}

View File

@ -0,0 +1,17 @@
package com.zsc.edu.gateway.exception;
import lombok.AllArgsConstructor;
import java.time.LocalDateTime;
/**
* @author harry_yao
*/
@AllArgsConstructor
public class ExceptionResult {
public final String msg;
public final Object code;
public final LocalDateTime timestamp;
}

View File

@ -0,0 +1,12 @@
package com.zsc.edu.gateway.exception;
import org.springframework.security.core.AuthenticationException;
/**
* @author Yao
*/
public class JwtAuthenticationException extends AuthenticationException {
public JwtAuthenticationException(String msg) {
super(msg);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotExistException extends ApiException {
public NotExistException(Class<?> entity) {
super(String.format("%s对象不存在", entity.getSimpleName()));
}
public NotExistException() {
super("对象不存在");
}
public NotExistException(String message) {
super(message);
}
}

View File

@ -0,0 +1,19 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class OutlineException extends ApiException {
public OutlineException() {
super("设备不在线");
}
public OutlineException(String message) {
super(message);
}
}

View File

@ -0,0 +1,13 @@
package com.zsc.edu.gateway.exception;
/**
* @author zhuang
*/
public class PublishFailedException extends RuntimeException {
public PublishFailedException(String message) {
super(message);
}
}

View File

@ -0,0 +1,19 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class StateException extends ApiException {
public StateException(Class<?> statusClass, Object currentStatus, Object correctStatus) {
super(String.format("%s当前的状态值'%s'不符合要求,正确的状态值可以是:%s。", statusClass.getSimpleName(), currentStatus, correctStatus));
}
public StateException(String message) {
super(message);
}
}

View File

@ -0,0 +1,19 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class StorageException extends ApiException {
public StorageException() {
super("文件存储失败");
}
public StorageException(String message) {
super(message);
}
}

View File

@ -0,0 +1,21 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.DisabledException;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class UserHasNoIdentityException extends DisabledException {
public UserHasNoIdentityException() {
super("没有给用户分配身份");
}
public UserHasNoIdentityException(String message) {
super(message);
}
}

View File

@ -0,0 +1,21 @@
package com.zsc.edu.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class ValidateException extends ApiException {
public ValidateException() {
super("验证码失效或错误!");
}
public ValidateException(String message) {
super(message);
}
public ValidateException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,17 @@
package com.zsc.edu.gateway.framework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
/**
* @author zhuang
*/
@Configuration
public class AppConfig {
@Bean
public RestClient restClient() {
return RestClient.builder().build();
}
}

View File

@ -0,0 +1,66 @@
package com.zsc.edu.gateway.framework;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.vo.DeptTree;
import com.zsc.edu.gateway.modules.system.vo.UserTree;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Component
public class DeptTreeUtil {
public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
return list.stream()
.filter(rootCheck)
.peek(x -> setSubChildren.accept(x, makeChildren(x, list, parentCheck, setSubChildren)))
.collect(Collectors.toList());
}
private static <E> List<E> makeChildren(E parent, List<E> allData, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
return allData.stream()
.filter(x -> parentCheck.apply(parent, x))
.peek(x -> setSubChildren.accept(x, makeChildren(x, allData, parentCheck, setSubChildren)))
.collect(Collectors.toList());
}
public static List<DeptTree> buildDeptTree(List<Dept> depots, Map<Long, List<User>> userMap) {
List<DeptTree> deptTrees = depots.stream()
.map(DeptTreeUtil::convertToDeptTree)
.collect(Collectors.toList());
deptTrees.forEach(deptTree -> {
List<User> users = userMap.getOrDefault(deptTree.getId(), Collections.emptyList());
deptTree.setMembers(users.stream()
.map(DeptTreeUtil::convertToUserTree)
.collect(Collectors.toList()));
});
return makeTree(
deptTrees,
deptTree -> deptTree.getPid() == null || deptTree.getPid() == 0L,
(parent, child) -> parent.getId().equals(child.getPid()),
DeptTree::setChildren
);
}
private static DeptTree convertToDeptTree(Dept dept) {
DeptTree deptTree = new DeptTree();
deptTree.setId(dept.getId());
deptTree.setPid(dept.getPid());
deptTree.setName(dept.getName());
return deptTree;
}
private static UserTree convertToUserTree(User user) {
UserTree userTree = new UserTree();
userTree.setId(user.getId());
userTree.setName(user.getName());
return userTree;
}
}

View File

@ -0,0 +1,21 @@
package com.zsc.edu.gateway.framework;
import org.springframework.http.HttpStatus;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author harry yao
*/
public class JsonExceptionUtil {
public static Map<String, Object> jsonExceptionResult(HttpStatus code, String message, String path) {
Map<String, Object> exceptionMap = new LinkedHashMap<>();
exceptionMap.put("timestamp", Calendar.getInstance().getTime());
exceptionMap.put("message", message);
exceptionMap.put("path", path);
exceptionMap.put("code", code.value());
return exceptionMap;
}
}

View File

@ -0,0 +1,29 @@
package com.zsc.edu.gateway.framework;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
/**
* @author harry yao
*/
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
}

View File

@ -0,0 +1,47 @@
package com.zsc.edu.gateway.framework;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import java.util.List;
/**
* @author harry_yao
*/
@Configuration
@AllArgsConstructor
public class WebMvcConfiguration implements WebMvcConfigurer {
private final WebProperties webProperties;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations(webProperties.getResources().getStaticLocations())
.resourceChain(webProperties.getResources().getChain().isCache())
.addResolver(new FallbackPathResourceResolver());
}
private static class FallbackPathResourceResolver extends PathResourceResolver {
@Override
public Resource resolveResource(
HttpServletRequest request,
@NonNull String requestPath,
@NonNull List<? extends Resource> locations,
@NonNull ResourceResolverChain chain) {
Resource resource = super.resolveResource(request, requestPath, locations, chain);
if (resource == null) {
resource = super.resolveResource(request, "/index.html", locations, chain);
}
return resource;
}
}
}

View File

@ -0,0 +1,52 @@
package com.zsc.edu.gateway.framework.async;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
/**
* @author harry_yao
*/
@Slf4j
@EnableAsync
@Configuration
//@Profile("!test") // test 环境下不启动异步
public class AsyncConfiguration implements AsyncConfigurer {
// @Bean
// public AsyncTaskExecutor taskExecutor() {
// ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// executor.setCorePoolSize(20);
// executor.setMaxPoolSize(20);
// executor.setQueueCapacity(500);
// executor.setThreadNamePrefix("Executor");
// executor.initialize();
// return executor;
// }
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("Executor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
return (Throwable throwable, Method method, Object... obj)->{
log.info("Method name -{} Exception message -{}", method.getName(),throwable);
};
}
}

View File

@ -0,0 +1,15 @@
package com.zsc.edu.gateway.framework.message.email;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author harry_yao
*/
@Data
@ConfigurationProperties("spring.mail")
@Configuration
public class EmailProperties {
public String username;
}

View File

@ -0,0 +1,108 @@
package com.zsc.edu.gateway.framework.message.email;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.attachment.service.AttachmentService;
import com.zsc.edu.gateway.modules.notice.entity.Message;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Objects;
import java.util.Set;
/**
* @author pegnzheng
*/
@AllArgsConstructor
@Component
public class EmailSender {
private final static String TEMPLATE = "message.ftl";
private final EmailProperties config;
private final Configuration freemarkerConfig;
@Resource
private final JavaMailSender sender;
private final AttachmentService attachmentService;
@Async
public void send(String email, Message message) {
if (StringUtils.hasText(email)) {
return;
}
InternetAddress to;
try {
to = new InternetAddress(email);
to.validate();
} catch (AddressException e) {
return;
}
send(new InternetAddress[]{to}, message);
}
@Async
public void send(Set<String> emails, Message message) {
InternetAddress[] to = emails.stream().filter(Objects::nonNull).map(email ->
{
try {
return new InternetAddress(email);
} catch (AddressException e) {
return null;
}
}).filter(Objects::nonNull).filter(internetAddress -> {
try {
internetAddress.validate();
} catch (AddressException e) {
return false;
}
return true;
}).toArray(InternetAddress[]::new);
if (to.length == 0) {
return;
}
send(to, message);
}
private void send(InternetAddress[] to, Message message) {
try {
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setFrom(config.username);
helper.setSubject(message.getTitle());
if (message.html) {
StringWriter sw = new StringWriter();
Template tp = freemarkerConfig.getTemplate(TEMPLATE, "UTF-8");
tp.process(message, sw);
helper.setText(sw.toString(), true);
} else {
helper.setText(message.content);
}
if (Objects.nonNull(message.attachments)) {
for (Attachment attachment : message.attachments) {
helper.addAttachment(attachment.fileName, attachmentService.loadAsResource(attachment.id), attachment.mimeType);
}
}
sender.send(mimeMessage);
} catch (MessagingException | IOException | TemplateException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,17 @@
package com.zsc.edu.gateway.framework.message.sms;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author harry_yao
*/
@Data
@ConfigurationProperties("sms")
@Configuration
public class SmsProperties {
public String apiKey = "4d8de516324886549d0ba3ddc4bf6f47";
public String singleSendUrl = "https://sms.yunpian.com/v2/sms/single_send.json";
public String batchSendUrl = "https://sms.yunpian.com/v2/sms/batch_send.json";
}

View File

@ -0,0 +1,47 @@
package com.zsc.edu.gateway.framework.message.sms;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author pegnzheng
*/
@AllArgsConstructor
@Component
public class SmsSender {
private final SmsProperties properties;
@Resource
private final RestClient restClient;
@Async
public void send(String mobile, String text) {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("apikey", properties.apiKey);
params.add("mobile", mobile);
params.add("text", text);
restClient.post().uri(properties.singleSendUrl).body(params);
}
@Async
public void send(Set<String> mobiles, String text) {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("apikey", properties.apiKey);
params.add("mobile", mobiles.stream().filter(StringUtils::hasText).collect(Collectors.joining(",")));
params.add("text", text);
restClient.post().uri(properties.batchSendUrl).body(params);
}
}

View File

@ -0,0 +1,50 @@
package com.zsc.edu.gateway.framework.mybatisplus;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author : wshuo
* @date : 2023/1/11 15:59
*/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({ArrayList.class})
public class ListTypeHandler extends BaseTypeHandler<ArrayList<String>> {
private static final String DELIM = ",";
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, ArrayList<String> strings, JdbcType jdbcType) throws SQLException {
String value = StringUtils.collectionToDelimitedString(strings, DELIM);
preparedStatement.setString(i, value);
}
@Override
public ArrayList<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
String value = resultSet.getString(s);
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
}
@Override
public ArrayList<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
String value = resultSet.getString(i);
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
}
@Override
public ArrayList<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
String value = callableStatement.getString(i);
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
}
}

View File

@ -0,0 +1,37 @@
package com.zsc.edu.gateway.framework.mybatisplus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zsc.edu.gateway.framework.security.SecurityUtil;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author Yao
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
this.strictInsertFill(metaObject, "createdBy", userInfo::getUsername, String.class);
}
@Override
public void updateFill(MetaObject metaObject) {
UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
this.strictUpdateFill(metaObject, "updatedBy", userInfo::getUsername, String.class);
}
}

View File

@ -0,0 +1,31 @@
package com.zsc.edu.gateway.framework.mybatisplus;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Yao
*/
@MapperScan(basePackages = "com.zsc.edu.gateway.modules.*.repo")
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
// // 添加数据权限插件
// MyDataPermissionInterceptor dataPermissionInterceptor = new MyDataPermissionInterceptor();
// // 添加自定义的数据权限处理器
// dataPermissionInterceptor.setDataPermissionHandler(new MyDataPermissionHandler());
// interceptor.addInnerInterceptor(dataPermissionInterceptor);
return interceptor;
}
}

View File

@ -0,0 +1,47 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.gateway.exception.ExceptionResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
private final ObjectMapper objectMapper;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException ex) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
ExceptionResult result;
if (ex instanceof MissingCsrfTokenException) {
System.out.println("MissingCsrfTokenException");
// 会话已注销返回401
response.setStatus(HttpStatus.UNAUTHORIZED.value());
result = new ExceptionResult("凭证已过期,请重新登录", HttpStatus.UNAUTHORIZED.value(),
LocalDateTime.now());
} else {
// 403
response.setStatus(HttpStatus.FORBIDDEN.value());
result = new ExceptionResult("禁止操作", HttpStatus.FORBIDDEN.value(),
LocalDateTime.now());
}
response.getWriter().print(objectMapper.writeValueAsString(result));
response.flushBuffer();
}
}

View File

@ -0,0 +1,35 @@
package com.zsc.edu.gateway.framework.security;///*
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* 认证处理
* 当用户尝试访问安全的REST资源而不提供任何凭据时将调用此方法发送401 响应
* @author Yao
*/
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Resource
private ObjectMapper objectMapper;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().println(objectMapper.writeValueAsString(Map.of("msg", "认证失败: " + authException.getMessage())));
response.flushBuffer();
}
}

View File

@ -0,0 +1,37 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.gateway.exception.ExceptionResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=utf-8");
ExceptionResult result = new ExceptionResult(exception.getMessage(), HttpStatus.UNAUTHORIZED.value(),
LocalDateTime.now());
response.getWriter().print(objectMapper.writeValueAsString(result));
response.flushBuffer();
}
}

View File

@ -0,0 +1,46 @@
package com.zsc.edu.gateway.framework.security;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// private final OnlineUserService onlineUserService;
// private final UserService userService;
// private final LoginLogService loginLogService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
// Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// String sessionId = request.getRequestedSessionId();
// String remoteAddr = request.getRemoteAddr();
// User user = userService.getOne(((UserDetailsImpl) principal).getId());
// String agent = request.getHeader("User-Agent");
// UserAgent userAgent = new UserAgent(agent);
// OnlineUser onlineUser = onlineUserService.create(
// sessionId,
// user.username,
// user.name,
// null,//user.identity.dept.name,
// remoteAddr,
// userAgent.getBrowser().getName(),
// userAgent.getOperatingSystem().getName(),
// LocalDateTime.now()
// );
// loginLogService.create(onlineUser.username, onlineUser.name, onlineUser.deptName,
// onlineUser.ip, onlineUser.browser, onlineUser.os,
// onlineUser.loginTime, LoginLog.Result.登陆成功);
}
}

View File

@ -0,0 +1,30 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.gateway.exception.ExceptionResult;
import com.zsc.edu.gateway.framework.SpringBeanUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* @author harry_yao
*/
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
ObjectMapper objectMapper = SpringBeanUtil.getBean(ObjectMapper.class);
HttpServletResponse response = event.getResponse();
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=utf-8");
ExceptionResult result = new ExceptionResult("会话已过期(有可能是您同时登录了太多的太多的客户端)",
HttpStatus.UNAUTHORIZED.value(),
LocalDateTime.now());
response.getWriter().print(objectMapper.writeValueAsString(result));
response.flushBuffer();
}
}

View File

@ -0,0 +1,46 @@
package com.zsc.edu.gateway.framework.security;
import com.zsc.edu.gateway.exception.StateException;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
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.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepo;
private final AuthorityRepository authorityRepository;
@Override
@Transactional(rollbackFor = Exception.class)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.selectByUsername(username);
if (!user.getEnableState()) {
throw new StateException("用户 '" + username + "' 已被禁用!请联系管理员");
}
user.role.authorities = authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
// =roleAuthorities.stream()
// .map(i -> Authority.valueOf(i.getAuthority()))
// .collect(Collectors.toSet());
// .orElseThrow(() ->
// new UsernameNotFoundException("用户 '" + username + "' 不存在!")
// );
// user.getIdentities().stream().filter(identity -> identity.role.enableState == EnableState.启用)
// .forEach(identity -> Hibernate.initialize(identity.role.roleAuthorities));
return UserDetailsImpl.from(user);
}
}

View File

@ -0,0 +1,45 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.io.IOException;
import java.util.Map;
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = map.get("username").toString();
String password = map.get("password").toString();
username = (username != null) ? username : "";
username = username.trim();
password = (password != null) ? password : "";
password = password.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
e.printStackTrace();
}
}
return super.attemptAuthentication(request, response);
}
}

View File

@ -0,0 +1,30 @@
package com.zsc.edu.gateway.framework.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.session.HttpSessionEventPublisher;
/**
* @author harry_yao
*/
@Configuration
public class SecurityBeanConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
}

View File

@ -0,0 +1,19 @@
package com.zsc.edu.gateway.framework.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author Yao
*/
public class SecurityUtil {
public static UserDetailsImpl getUserInfo() {
return getPrincipal();
}
private static UserDetailsImpl getPrincipal() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (UserDetailsImpl) authentication.getPrincipal();
}
}

View File

@ -0,0 +1,100 @@
package com.zsc.edu.gateway.framework.security;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import javax.sql.DataSource;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Configuration
public class SpringSecurityConfig {
private final UserDetailsService userDetailsService;
private final CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
private final CustomAccessDeniedHandler customAccessDeniedHandler;
private final SessionRegistry sessionRegistry;
private final SecurityBeanConfig securityBeanConfig;
@Resource
private final DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
@Bean
AuthenticationManager authenticationManager() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(securityBeanConfig.passwordEncoder());
return new ProviderManager(daoAuthenticationProvider);
}
@Bean
public JsonAuthenticationFilter jsonAuthenticationFilter() throws Exception {
JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
filter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
filter.setFilterProcessesUrl("/api/rest/user/login");
filter.setAuthenticationManager(authenticationManager());
// 将登录后的请求信息保存到Session中不然会报null
filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
return filter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/rest/user/me","/api/rest/user/register","/api/rest/user/send-email").permitAll()
.requestMatchers(HttpMethod.POST, "/api/rest/user/login","/api/rest/user/register").permitAll()
.requestMatchers("/api/**").authenticated())
.addFilterAt(jsonAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin(form -> form
.loginPage("/user/login")
.loginProcessingUrl("/api/rest/user/login")
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler))
.logout(logout -> logout
.logoutUrl("/api/user/logout")
.logoutSuccessHandler((request, response, authentication) -> {}))
// 添加自定义未授权和未登录结果返回
.exceptionHandling(exception -> exception
.authenticationEntryPoint(customAuthenticationEntryPoint)
.accessDeniedHandler(customAccessDeniedHandler)
)
.rememberMe(rememberMe -> rememberMe
.userDetailsService(userDetailsService)
.tokenRepository(persistentTokenRepository()))
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/internal/**", "/api/rest/user/logout","/api/rest/user/register"))
.sessionManagement(session -> session
.maximumSessions(3)
.sessionRegistry(sessionRegistry)
.expiredSessionStrategy(new CustomSessionInformationExpiredStrategy()))
.build();
}
}

View File

@ -0,0 +1,88 @@
package com.zsc.edu.gateway.framework.security;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zsc.edu.gateway.common.enums.EnableState;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.User;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author harry yao
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonIgnoreProperties("password")
public class UserDetailsImpl implements UserDetails {
public Long id;
public String username;
public String password;
public Boolean enableState;
public String name;
public Dept dept;
public Role role;
public Set<Authority> authorities;
public UserDetailsImpl(Long id, String username, String password, String name, Boolean enableState, Dept dept, Role role, Set<Authority> authorities) {
this.id = id;
this.username = username;
this.password = password;
this.enableState = enableState;
this.name = name;
this.dept = dept;
this.role = role;
this.authorities = authorities;
}
public static UserDetailsImpl from(User user) {
return new UserDetailsImpl(
user.id,
user.username,
user.password,
user.name,
user.enableState,
user.dept,
user.role,
user.role.authorities
);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enableState;
}
}

View File

@ -0,0 +1,25 @@
package com.zsc.edu.gateway.framework.storage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author harry_yao
*/
@ConfigurationProperties("storage")
@Component
public class StorageProperties {
/**
* 附件存储路径
*/
@Value("${storage.attachment}")
public String attachment;
/**
* 临时文件存储路径
*/
@Value("${storage.temp}")
public String temp;
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.framework.storage.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class StorageException extends RuntimeException {
public StorageException() {
super("文件存储出错");
}
public StorageException(String message) {
super(message);
}
public StorageException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.framework.storage.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class StorageFileEmptyException extends StorageException {
public StorageFileEmptyException() {
super("存储的是空文件!");
}
public StorageFileEmptyException(String message) {
super(message);
}
public StorageFileEmptyException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.framework.storage.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author harry_yao
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
public class StorageFileNotFoundException extends StorageException {
public StorageFileNotFoundException() {
super("文件不存在!");
}
public StorageFileNotFoundException(String message) {
super(message);
}
public StorageFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,94 @@
package com.zsc.edu.gateway.modules.attachment.controller;
import com.zsc.edu.gateway.exception.StorageException;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.attachment.service.AttachmentService;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* 附件Controller
*
* @author harry_yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("api/rest/attachment")
public class AttachmentController {
private final AttachmentService service;
/**
* 上传附件
*
* @param type 附件功能类型
* @param file 文件
* @return 附件信息
*/
@PostMapping()
public Attachment upload(
@RequestParam(required = false, defaultValue = "其他") Attachment.Type type,
@RequestParam("file") MultipartFile file
) {
try {
if (type == null) {
type = Attachment.Type.其他;
}
return service.store(type, file);
} catch (IOException e) {
throw new StorageException("文件上传出错");
}
}
/**
* 下载附件
*
* @param id 附件ID
* @return 附件文件内容
*/
@GetMapping("{id}")
public ResponseEntity<Resource> download(
@PathVariable("id") String id
) {
Attachment.Wrapper wrapper = service.loadAsWrapper(id);
if (wrapper.attachment.fileName != null) {
ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(wrapper.attachment.fileName, StandardCharsets.UTF_8).build();
return ResponseEntity.ok().
header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString()).
header(HttpHeaders.CONTENT_TYPE, wrapper.attachment.mimeType).
body(wrapper.resource);
}
return ResponseEntity.ok(wrapper.resource);
}
/**
* 根据附件ID获取附件信息
* */
@GetMapping("find/{id}")
public Attachment getAttachmentInfo(@PathVariable("id") String id) {
return service.getById(id);
}
@PostMapping("uploadMultipleFiles")
public List<Attachment> uploadMultipleFiles(
@RequestParam(defaultValue = "其他") Attachment.Type type,
@RequestParam("files") List<MultipartFile> files
) throws IOException {
List<Attachment> attachments = new ArrayList<>();
for (MultipartFile file : files) {
if (!file.isEmpty()) {
attachments.add(service.stores(type, file));
}
}
return attachments;
}
}

View File

@ -0,0 +1,64 @@
package com.zsc.edu.gateway.modules.attachment.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author ftz
* 创建时间:29/1/2024 上午10:00
* 描述: 附件Dto
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AttachmentDto {
/**
* 文件名 文件名详细说明
*/
private String saveFilename;
/**
* 文件UUID 返回给前端的文件UUID
*/
private String uuid;
/**
* 上传时的文件名 原文件名
*/
private String originFilename;
/**
* 文件大小
*/
private Long fileSize;
/**
* 文件类型
*/
private String fileType;
/**
* 文件扩展名
*/
private String extendName;
/**
* 票据id 附件对应的票据id
*/
private Long ticketId;
private String remark;
/**
*文件url
*/
private String fileUrl;
}

View File

@ -0,0 +1,97 @@
package com.zsc.edu.gateway.modules.attachment.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.*;
import org.springframework.core.io.FileSystemResource;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 附件
*
* @author harry_yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value ="attachment")
public class Attachment implements Serializable {
/**
* ID用文件和文件名的SHA-1值生成
*/
@TableId
public String id;
/**
* 文件名
*/
public String fileName;
/**
* 附件作用类型
*/
public String mimeType;
/**
* 附件功能类型
*/
// @Column(nullable = false)
// @Enumerated(EnumType.STRING)
// public Type type = Type.其他;
/**
* 文件上传时间
*/
public LocalDateTime uploadTime;
/**
* 文件下载链接
*/
@JsonSerialize
@TableField(exist = false)
public String url;
public Attachment(String id, String fileName, String mimeType, Type type, LocalDateTime uploadTime) {
this.id = id;
this.fileName = fileName;
this.mimeType = mimeType;
// this.type = type;
this.uploadTime = uploadTime;
this.url = "/api/rest/attachment/" + id;
}
public void setId(String id) {
this.id = id;
this.url = "/api/rest/attachment/" + id;
}
public String getUrl() {
return "/api/rest/attachment/" + id;
}
/**
* 枚举类附件功能类型
*/
public enum Type {
其他,
头像
}
@AllArgsConstructor
public static final class Wrapper {
public Attachment attachment;
public FileSystemResource resource;
}
}

View File

@ -0,0 +1,12 @@
package com.zsc.edu.gateway.modules.attachment.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
/**
* @author ftz
* 创建时间:29/1/2024 上午9:55
* 描述: TODO
*/
public interface AttachmentRepository extends BaseMapper<Attachment>{
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.modules.attachment.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* @author fantianzhi
* &#064;description 针对表attach_file(票据附件表)的数据库操作Service
* &#064;createDate 2024-01-28 19:48:22
*/
public interface AttachmentService extends IService<Attachment> {
Attachment store(Attachment.Type type, MultipartFile file) throws IOException;
Attachment stores(Attachment.Type type, MultipartFile file)throws IOException;
Resource loadAsResource(String id);
Attachment.Wrapper loadAsWrapper(String id);
}

View File

@ -0,0 +1,204 @@
package com.zsc.edu.gateway.modules.attachment.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.framework.storage.StorageProperties;
import com.zsc.edu.gateway.framework.storage.exception.StorageFileEmptyException;
import com.zsc.edu.gateway.framework.storage.exception.StorageFileNotFoundException;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.attachment.repo.AttachmentRepository;
import com.zsc.edu.gateway.modules.attachment.service.AttachmentService;
import jakarta.annotation.PostConstruct;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tika.Tika;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* 附件Service
*
* @author harry_yao
*/
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentRepository, Attachment> implements AttachmentService {
final static int[] illegalChars = {34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47};
private final AttachmentRepository repo;
private final Path attachmentPath;
private final Path tempPath;
public AttachmentServiceImpl(AttachmentRepository repo, StorageProperties storageProperties) {
this.repo = repo;
this.attachmentPath = Paths.get(storageProperties.attachment);
this.tempPath = Paths.get(storageProperties.temp);
}
@PostConstruct
public void init() throws IOException {
if (Files.notExists(attachmentPath)) {
Files.createDirectories(attachmentPath);
}
if (Files.notExists(tempPath)) {
Files.createDirectories(tempPath);
}
}
public Attachment store(Attachment.Type type, MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new StorageFileEmptyException();
}
MessageDigest digest = DigestUtils.getSha1Digest();
String filename = file.getOriginalFilename();
if (filename != null) {
digest.update(filename.getBytes());
}
Path temp = tempPath.resolve(String.valueOf(System.nanoTime()));
byte[] fileContent = file.getBytes();
ByteArrayInputStream input = new ByteArrayInputStream(fileContent);
Tika tika = new Tika();
String mimeType = tika.detect(input, filename);
OutputStream output = Files.newOutputStream(temp);
digest.update(fileContent);
output.write(fileContent);
input.close();
output.flush();
output.close();
String sha1 = Hex.encodeHexString(digest.digest());
return save(temp, sha1, filename, mimeType, type);
}
@Override
public Attachment stores(Attachment.Type type, MultipartFile file) throws IOException{
if (file.isEmpty()) {
throw new StorageFileEmptyException("上传的文件不能为空");
}
String filename = file.getOriginalFilename();
if (filename == null || filename.trim().isEmpty()) {
throw new IllegalArgumentException("文件名不能为空");
}
MessageDigest digest = DigestUtils.getSha1Digest();
digest.update(filename.getBytes(StandardCharsets.UTF_8));
Path temp = tempPath.resolve(String.valueOf(System.nanoTime()));
byte[] fileContent = file.getBytes();
// 使用try-with-resources自动关闭流
try (ByteArrayInputStream input = new ByteArrayInputStream(fileContent);
OutputStream output = Files.newOutputStream(temp)) {
Tika tika = new Tika();
String mimeType = tika.detect(input, filename);
digest.update(fileContent);
output.write(fileContent);
String sha1 = Hex.encodeHexString(digest.digest());
return save(temp, sha1, filename, mimeType, type);
}
}
public Attachment store(Attachment.Type type, File file) throws IOException {
MessageDigest digest = DigestUtils.getSha1Digest();
String filename = file.getName();
if (filename != null) {
digest.update(filename.getBytes());
}
Tika tika = new Tika();
String mimeType = tika.detect(file);
String sha1 = Hex.encodeHexString(digest.digest());
return save(file.toPath(), sha1, filename, mimeType, type);
}
public Attachment store(Attachment.Type type, Path file) throws IOException {
String filename = file.getFileName().toString();
MessageDigest digest = DigestUtils.getSha1Digest();
if (filename != null) {
digest.update(filename.getBytes());
}
Tika tika = new Tika();
String mimeType = tika.detect(file);
InputStream input = Files.newInputStream(file);
byte[] buf = new byte[8192];
int n;
while ((n = input.read(buf)) > 0) {
digest.update(buf, 0, n);
}
String sha1 = Hex.encodeHexString(digest.digest());
return save(file, sha1, filename, mimeType, type);
}
@Override
public Resource loadAsResource(String id) {
Path file = attachmentPath.resolve(id);
FileSystemResource resource = new FileSystemResource(file);
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new StorageFileNotFoundException();
}
}
@Override
public Attachment.Wrapper loadAsWrapper(String id) {
Path file = attachmentPath.resolve(id);
FileSystemResource resource = new FileSystemResource(file);
if (!resource.exists() || !resource.isReadable()) {
throw new StorageFileNotFoundException();
}
Attachment attachment = repo.selectById(id); //.orElseThrow(NotExistException::new);
return new Attachment.Wrapper(attachment, resource);
}
public Attachment findById(String id) {
return repo.selectById(id); //.orElseThrow(NotExistException::new);
}
public List<Attachment> findAllById(Collection<String> ids) {
return (ids != null && !ids.isEmpty()) ? repo.selectList(new LambdaQueryWrapper<Attachment>().in(Attachment::getId, ids)) : new ArrayList<>();
}
public Path convertToTempPath(String fileName) {
fileName = fileName.replace("/", "");
Path path;
try {
path = tempPath.resolve(fileName);
} catch (Exception e) {
StringBuilder cleanName = new StringBuilder();
for (int i = 0; i < fileName.length(); i++) {
int c = fileName.charAt(i);
if (Arrays.binarySearch(illegalChars, c) < 0) {
cleanName.append((char) c);
}
}
path = tempPath.resolve(cleanName.toString());
}
return path;
}
private Attachment save(Path temp, String id, String filename, String mimeType, Attachment.Type type) throws IOException {
Path dest = attachmentPath.resolve(id);
if (Files.exists(dest)) {
return findById(id);
}
Files.move(temp, dest);
Attachment attachment = new Attachment(id, filename, mimeType, type, LocalDateTime.now());
repo.insert(attachment);
return attachment;
}
}

View File

@ -0,0 +1,12 @@
package com.zsc.edu.gateway.modules.attachment.vo;
import lombok.Data;
/**
* @author zhuang
*/
@Data
public class AttachmentVo {
public String fileName;
public String url;
}

View File

@ -0,0 +1,164 @@
package com.zsc.edu.gateway.modules.notice.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.BulletinDto;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.service.BulletinService;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
/**
* 公告Controller
*
* @author harry_yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/bulletin")
public class BulletinController {
private final BulletinService service;
/**
* 普通用户查看公告详情
*
* @param id ID
* @return 公告
*/
@GetMapping("/self/{id}")
public List<BulletinVo> selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
return service.detail(userDetails,id, Bulletin.State.publish);
}
/**
* 普通用户分页查询公告
*
* @param query 查询表单
* @return 分页数据
*/
@GetMapping("/self")
public IPage<BulletinVo> getBulletins( BulletinQuery query) {
query.setState(Bulletin.State.publish);
Page<BulletinVo> page = new Page<>(query.getPageNum(), query.getPageSize());
return service.selectPageByConditions(page, query);
}
/**
* 管理查询公告详情
*
* @param id ID
* @return 公告
*/
@GetMapping("/{id}")
@PreAuthorize("hasAuthority('BULLETIN_QUERY')")
public List<BulletinVo> detail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
return service.detail(userDetails,id, null);
}
/**
* 管理员分页查询公告
*
* @param query 查询参数
* @return 分页数据
*/
@GetMapping()
@PreAuthorize("hasAuthority('BULLETIN_QUERY')")
public IPage<BulletinVo> query( BulletinQuery query) {
Page<BulletinVo> page = new Page<>(query.getPageNum(), query.getPageSize());
return service.selectPageByConditions(page, query);
}
/**
* 创建公告
*
* @param userDetails 操作用户
* @param dto 表单数据
* @return 公告
*/
@PostMapping
@PreAuthorize("hasAuthority('BULLETIN_CREATE')")
public Bulletin create(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody BulletinDto dto) {
return service.create(userDetails, dto);
}
/**
* 更新公告只能修改"编辑中""已发布"的公告"已发布"的公告修改后会改为"编辑中"
*
* @param userDetails 操作用户
* @param dto 表单数据
* @param id ID
* @return 公告
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('BULLETIN_UPDATE')")
public Boolean update(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody BulletinDto dto, @PathVariable("id") Long id) {
return service.update(userDetails, dto, id);
}
/**
* 切换公告置顶状态
*
* @param id ID
* @return 公告
*/
@PatchMapping("/{id}/toggle-top")
@PreAuthorize("hasAuthority('BULLETIN_UPDATE')")
public Boolean toggleTop(@PathVariable("id") Long id) {
return service.toggleTop(id);
}
/**
* 发布公告只能发布"编辑中"的公告
*
* @param userDetails 操作用户
* @param ids IDs
* @return 公告
*/
@PatchMapping("/publish")
@PreAuthorize("hasAuthority('BULLETIN_PUBLISH')")
public List<String> publish(@AuthenticationPrincipal UserDetailsImpl userDetails,@RequestBody List<Long> ids) {
return service.publish(userDetails, ids);
}
/**
* 关闭公告只能关闭"已发布"的公告
*
* @param userDetails 操作用户
* @param id ID
* @return 公告
*/
@PatchMapping("/{id}/toggleClose")
@PreAuthorize("hasAuthority('BULLETIN_CLOSE')")
public Boolean toggleClose(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
return service.close(userDetails, id);
}
/**
* 删除公告只能删除"编辑中"的公告
*
* @param id ID
* @return
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('BULLETIN_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
/**
*为公告添加附件
*/
@PostMapping("/{id}/add")
@PreAuthorize("hasAuthority('BULLETIN_CREATE')")
public Boolean insertInto(@PathVariable Long id,@RequestBody Set<String> attachments){
return service.insertInto(id, attachments);
}
}

View File

@ -0,0 +1,157 @@
package com.zsc.edu.gateway.modules.notice.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.UserMessageDto;
import com.zsc.edu.gateway.modules.notice.entity.MessagePayload;
import com.zsc.edu.gateway.modules.notice.entity.MessageSetting;
import com.zsc.edu.gateway.modules.notice.query.UserMessageQuery;
import com.zsc.edu.gateway.modules.notice.service.UserMessageService;
import com.zsc.edu.gateway.modules.notice.vo.UserMessageVo;
import com.zsc.edu.gateway.modules.system.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
/**
* 用户消息Controller
*
* @author harry_yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("api/rest/message")
public class UserMessageController {
private final UserMessageService service;
/**
* 普通用户查看消息详情
*
* @param userDetails 操作用户
* @param messageId 消息ID
* @return 用户消息详情
*/
@GetMapping("/self/{messageId}")
public UserMessageVo selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("messageId") Long messageId) {
return service.detail(messageId, userDetails.getId());
}
/**
* 普通用户分页查询消息不能设置查询参数userId和username
*
* @param userDetails 操作用户
* @param query 查询参数
* @return 分页数据
*/
@GetMapping("/self")
public IPage<UserMessageVo> selfPage(@AuthenticationPrincipal UserDetailsImpl userDetails, UserMessageQuery query) {
query.userId = userDetails.id;
query.name = null;
Page<UserMessageVo> page = new Page<>(query.getPageNum(), query.getPageSize());
return service.page(page, query);
}
/**
* 普通用户统计自己未读消息数量
*
* @param userDetails 操作用户
* @return 数据
*/
@GetMapping("/countUnread")
public int countUnread(@AuthenticationPrincipal UserDetailsImpl userDetails) {
return service.countUnread(userDetails);
}
/**
* 普通用户确认消息已读如果提交的已读消息ID集合为空则将所有未读消息设为已读
*
* @param userDetails 操作用户
* @param messageIds 已读消息ID集合
* @return 确认已读数量
*/
@PatchMapping("/read")
public int acknowledge(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody List<Long> messageIds) {
return service.markAsRead(userDetails, messageIds);
}
/**
* 管理查询消息详情
*
* @param userId 用户ID
* @param messageId 消息ID
* @return 用户消息详情
*/
@GetMapping("/{userId}/{messageId}")
@PreAuthorize("hasAuthority('MESSAGE_QUERY')")
public UserMessageVo detail(@PathVariable("userId") Long userId, @PathVariable("messageId") Long messageId) {
return service.detail(messageId, userId);
}
/**
* 管理员分页查询消息
*
* @param query 查询参数
* @return 分页数据
*/
@GetMapping
@PreAuthorize("hasAuthority('MESSAGE_QUERY')")
public IPage<UserMessageVo> page(UserMessageQuery query) {
Page<UserMessageVo> page = new Page<>(query.getPageNum(), query.getPageSize());
return service.page(page, query);
}
/**
* 管理员手动创建消息
*
* @param dto 表单数据
* @return 消息列表
*/
@PostMapping
@PreAuthorize("hasAuthority('MESSAGE_CREATE')")
public Boolean create(@RequestBody UserMessageDto dto) {
return service.createByAdmin(dto);
}
/**
* 管理员为消息添加附件
*
* @param messageId 消息ID
* @param attachmentIds 附件ID集合
* @return 消息列表
*/
@PostMapping("/attachment/{messageId}")
@PreAuthorize("hasAuthority('MESSAGE_CREATE')")
public Boolean insertInto(@PathVariable("messageId") Long messageId, @RequestBody List<String> attachmentIds) {
return service.insertInto(messageId, attachmentIds);
}
/**
* 获取消息推送方式
*
* @return 消息推送方式列表
*/
@GetMapping("/setting")
@PreAuthorize("hasAuthority('MESSAGE_SETTING')")
public List<MessageSetting> getSetting() {
return service.getSetting();
}
/**
* 设置消息推送方式
*
* @param settings 表单数据
* @return 消息设置
*/
@PatchMapping("/setting")
@PreAuthorize("hasAuthority('MESSAGE_SETTING')")
public List<MessageSetting> saveSetting(@RequestBody List<MessageSetting> settings) {
return service.saveSetting(settings);
}
}

View File

@ -0,0 +1,18 @@
package com.zsc.edu.gateway.modules.notice.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author zhuang
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BulletinAttachmentDto {
private Long bulletinId;
private String attachmentId;
}

View File

@ -0,0 +1,44 @@
package com.zsc.edu.gateway.modules.notice.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
/**
* @author harry_yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BulletinDto {
/**
* 标题
*/
@NotBlank(message = "接收用户不能为空")
public String title;
/**
* 是否置顶
*/
public boolean top;
/**
* 内容
*/
@NotBlank(message = "消息内容不能为空")
public String content;
/**
* 备注
*/
public String remark;
//
// /**
// * 附件ID集合
// */
// private List<String> attachmentIds;
}

View File

@ -0,0 +1,24 @@
package com.zsc.edu.gateway.modules.notice.dto;
import lombok.Data;
import java.util.List;
/**
* @author zhuang
*/
@Data
public class PageDto<T> {
/**
* 总条数
*/
private Long total;
/**
* 总页数
*/
private Integer pages;
/**
* 集合
*/
private List<T> list;
}

View File

@ -0,0 +1,61 @@
package com.zsc.edu.gateway.modules.notice.dto;
import com.zsc.edu.gateway.modules.notice.entity.MessageType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.Set;
/**
* @author harry_yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserMessageDto {
/**
* 用户ID集合
*/
@NotEmpty(message = "接收用户不能为空")
public Set<Long> userIds;
/**
* 消息类型
*/
@NotNull(message = "消息类型不能为空")
public MessageType type;
/**
* 是否需要发送邮件
*/
public Boolean email;
/**
* 是否需要发送短信
*/
public Boolean sms;
/**
* 消息内容是否富文本True则以富文本形式发送
*/
public Boolean html;
/**
* 消息标题
*/
@NotBlank(message = "消息标题不能为空")
public String title;
/**
* 消息内容
*/
@NotBlank(message = "消息内容不能为空")
public String content;
}

View File

@ -0,0 +1,127 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.IEnum;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.zsc.edu.gateway.common.enums.IState;
import com.zsc.edu.gateway.modules.system.entity.BaseEntity;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import lombok.*;
import java.time.LocalDateTime;
import java.util.List;
/**
* 系统公告Domain
*
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_bulletin")
public class Bulletin extends BaseEntity {
/**
* 标题
*/
public String title;
/**
* 状态
*/
public State state = State.edit;
/**
* 是否置顶
*/
public Boolean top;
/**
* 编辑者ID
*/
public Long editUserId;
/**
* 编辑者
*/
@TableField(exist = false)
public String editUsername;
/**
* 编辑时间
*/
public LocalDateTime editTime;
/**
* 审核发布者ID
*/
public Long publishUserId;
/**
* 审核发布者
*/
@TableField(exist = false)
public String publishUsername;
/**
* 审核发布时间
*/
public LocalDateTime publishTime;
/**
* 关闭者ID
*/
public Long closeUserId;
/**
* 关闭者
*/
@TableField(exist = false)
public String closeUsername;
/**
* 关闭时间
*/
public LocalDateTime closeTime;
/**
* 内容
*/
public String content;
/**
* 已读状态
*/
@TableField(exist = false)
public Boolean isRead;
/**
* 附件列表
*/
@TableField(exist = false)
public List<Attachment> attachments;
public enum State implements IEnum<Integer>, IState<State> {
edit(1,"编辑中"),
publish(2,"已发布"),
close(3,"已关闭");
private final Integer value;
private final String name;
State(int value, String name) {
this.value=value;
this.name = name;
}
@Override
public Integer getValue() {
return this.value;
}
@Override
public String toString() {
return this.name;
}
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_bulletin_attach")
public class BulletinAttachment {
private Long bulletinId;
private String attachmentId;
}

View File

@ -0,0 +1,65 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.zsc.edu.gateway.modules.system.entity.BaseEntity;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
/**
* 消息
*
* @author harry_yao
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_message")
public class Message extends BaseEntity {
/**
* 消息类型
*/
public MessageType type = MessageType.other;
/**
* 是否系统生成
*/
public Boolean system;
/**
* 是否需要发送邮件
*/
public Boolean email;
/**
* 是否需要发送短信
*/
public Boolean sms;
/**
* 消息内容是否富文本True则以富文本形式发送
*/
public Boolean html;
/**
* 标题
*/
public String title;
/**
* 消息内容
*/
public String content;
/**
* 附件
*/
public List<Attachment> attachments;
}

View File

@ -0,0 +1,22 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author zhuang
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_message_attachment")
public class MessageAttachment {
private Long messageId;
private String attachmentId;
}

View File

@ -0,0 +1,39 @@
package com.zsc.edu.gateway.modules.notice.entity;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 消息内容
*
* @author harry_yao
*/
public abstract class MessagePayload {
public MessageType type;
public String content;
public Boolean html;
public static class Other extends MessagePayload {
public Other(String content) {
this.content = content;
this.type = MessageType.other;
}
}
public static class ResetPassword extends MessagePayload {
public String username;
public String password;
public LocalDateTime resetTime;
public ResetPassword(String username, String password, LocalDateTime resetTime) {
this.username = username;
this.password = password;
this.resetTime = resetTime;
this.type =MessageType.resetThePassword;
this.content = String.format("尊敬的用户%s您的密码已于%s被管理员重置新密码为%s" +
"请及时登录系统修改密码!", username, resetTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), password);
}
}
}

View File

@ -0,0 +1,57 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Objects;
/**
* 消息设置
*
* @author harry_yao
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_message_setting")
public class MessageSetting {
/**
* 消息类型
*/
@TableId
public Long id;
/**
* 是否发送邮件
*/
public Boolean email;
/**
* 是否发送短信
*/
public Boolean sms;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MessageSetting that = (MessageSetting) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}

View File

@ -0,0 +1,32 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.IEnum;
import com.zsc.edu.gateway.common.enums.IState;
/**
* 消息类型
*
* @author zhuang
*/
public enum MessageType implements IEnum<Integer>,IState<MessageType> {
other(1,"其他"),
resetThePassword(2,"重置密码");
private final Integer value;
private final String name;
MessageType(Integer value, String name) {
this.value = value;
this.name = name;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String toString() {
return name;
}
}

View File

@ -0,0 +1,48 @@
package com.zsc.edu.gateway.modules.notice.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.zsc.edu.gateway.modules.system.entity.User;
import lombok.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 用户消息
*
* @author harry_yao
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_user_message")
public class UserMessage implements Serializable {
@TableId
private Long id;
/**
* 用户ID
*/
public Long userId;
/**
* 消息ID
*/
public Long messageId;
/**
* 是否已读
*/
public Boolean isRead;
/**
* 阅读时间
*/
public LocalDateTime readTime;
}

View File

@ -0,0 +1,15 @@
package com.zsc.edu.gateway.modules.notice.mapper;
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
import com.zsc.edu.gateway.modules.notice.dto.BulletinAttachmentDto;
import com.zsc.edu.gateway.modules.notice.entity.BulletinAttachment;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhuang
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BulletinAttachmentMapper extends BaseMapper<BulletinAttachmentDto, BulletinAttachment> {
}

View File

@ -0,0 +1,14 @@
package com.zsc.edu.gateway.modules.notice.mapper;
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
import com.zsc.edu.gateway.modules.notice.dto.BulletinDto;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhuang
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BulletinMapper extends BaseMapper<BulletinDto, Bulletin> {
}

View File

@ -0,0 +1,34 @@
package com.zsc.edu.gateway.modules.notice.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* 系统公告Query
*
* @author harry_yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BulletinQuery {
private Integer pageNum = 1;
private Integer pageSize = 10;
private String title;
private Bulletin.State state;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime publishTimeBegin;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime publishTimeEnd;
}

View File

@ -0,0 +1,26 @@
package com.zsc.edu.gateway.modules.notice.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.modules.notice.entity.Message;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;
import java.util.Set;
/**
* @author zhuang
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MessageQuery {
Set<Long> messageIds;
public LambdaQueryWrapper<Message> wrapper() {
LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(StringUtils.hasText((CharSequence) this.messageIds), Message::getId, this.messageIds);
return queryWrapper;
}
}

View File

@ -0,0 +1,72 @@
package com.zsc.edu.gateway.modules.notice.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.entity.Message;
import com.zsc.edu.gateway.modules.notice.entity.MessageType;
import com.zsc.edu.gateway.modules.notice.entity.UserMessage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* 用户消息Query
*
* @author harry_yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserMessageQuery {
/**
* 用户ID
*/
public Long userId;
/**
* 标题模糊查询
*/
public String title;
/**
* 消息类型
*/
public MessageType type;
/**
* 用户名或真实姓名用户名准确查询姓名模糊查询
*/
public String name;
/**
* 是否系统自动生成
*/
public Boolean system;
/**
* 是否已读
*/
public Boolean isRead;
/**
* 消息创建时间区间起始
*/
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
public LocalDateTime createAtBegin;
/**
* 消息创建时间区间终止
*/
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
public LocalDateTime createAtEnd;
private Integer pageNum = 1;
private Integer pageSize = 10;
}

View File

@ -0,0 +1,11 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.notice.entity.BulletinAttachment;
/**
* @author zhuang
*/
public interface BulletinAttachmentRepository extends BaseMapper<BulletinAttachment> {
}

View File

@ -0,0 +1,27 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 公告Repo
*
* @author harry_yao
*/
public interface BulletinRepository extends BaseMapper<Bulletin> {
List<BulletinVo> selectByBulletinId(@Param("bulletinId") Long bulletinId);
IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, @Param("query") BulletinQuery query);
}

View File

@ -0,0 +1,7 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.notice.entity.MessageAttachment;
public interface MessageAttachmentRepository extends BaseMapper<MessageAttachment> {
}

View File

@ -0,0 +1,14 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.notice.entity.Message;
/**
* 消息Repo
*
* @author harry_yao
*/
public interface MessageRepository extends BaseMapper<Message> {
}

View File

@ -0,0 +1,18 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.gateway.modules.notice.entity.MessageSetting;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 消息设置Repo
*
* @author harry_yao
*/
public interface MessageSettingRepository extends BaseMapper<MessageSetting> {
@Select("select * from sys_message_setting")
List<MessageSetting> findAll();
}

View File

@ -0,0 +1,22 @@
package com.zsc.edu.gateway.modules.notice.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.modules.notice.entity.UserMessage;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.query.UserMessageQuery;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import com.zsc.edu.gateway.modules.notice.vo.UserMessageVo;
import org.apache.ibatis.annotations.Param;
/**
* 用户消息Repo
*
* @author harry_yao
*/
public interface UserMessageRepository extends BaseMapper<UserMessage> {
UserMessageVo selectByMessageIdAndUserId(@Param("messageId") Long messageId, @Param("userId") Long userId);
IPage<UserMessageVo> query(Page<UserMessageVo> page, @Param("query") UserMessageQuery query);
}

View File

@ -0,0 +1,12 @@
package com.zsc.edu.gateway.modules.notice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.modules.notice.entity.BulletinAttachment;
/**
* @author zhuang
*/
public interface BulletinAttachmentService extends IService<BulletinAttachment> {
}

View File

@ -0,0 +1,39 @@
package com.zsc.edu.gateway.modules.notice.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.BulletinDto;
import com.zsc.edu.gateway.modules.notice.dto.PageDto;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import java.util.List;
import java.util.Set;
/**
* 系统公告Service
*
* @author harry_yao
*/
public interface BulletinService extends IService<Bulletin> {
List<BulletinVo> detail(UserDetailsImpl userDetails, Long id, Bulletin.State state);
Bulletin create(UserDetailsImpl userDetails, BulletinDto dto);
Boolean update(UserDetailsImpl userDetails, BulletinDto dto, Long id);
Boolean toggleTop(Long id);
List<String> publish(UserDetailsImpl userDetails, List<Long> id);
Boolean close(UserDetailsImpl userDetails,Long id);
Boolean insertInto(Long bulletinId, Set<String> attachmentIds);
IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, BulletinQuery query);
}

View File

@ -0,0 +1,7 @@
package com.zsc.edu.gateway.modules.notice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.modules.notice.entity.MessageAttachment;
public interface MessageAttachmentService extends IService<MessageAttachment> {
}

View File

@ -0,0 +1,45 @@
package com.zsc.edu.gateway.modules.notice.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.UserMessageDto;
import com.zsc.edu.gateway.modules.notice.entity.MessagePayload;
import com.zsc.edu.gateway.modules.notice.entity.MessageSetting;
import com.zsc.edu.gateway.modules.notice.entity.UserMessage;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.query.UserMessageQuery;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import com.zsc.edu.gateway.modules.notice.vo.UserMessageVo;
import com.zsc.edu.gateway.modules.system.entity.User;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
/**
* 用户消息Service
*
* @author harry_yao
*/
public interface UserMessageService extends IService<UserMessage> {
Boolean createByAdmin(UserMessageDto dto);
UserMessageVo detail(Long messageId, Long userId);
Boolean insertInto(Long messageId, List<String> attachmentIds);
List<MessageSetting> getSetting();
IPage<UserMessageVo> page(Page<UserMessageVo> page, UserMessageQuery query);
Integer countUnread(UserDetailsImpl userDetails);
Integer markAsRead(UserDetailsImpl userDetails, List<Long> messageIds);
@Transactional
List<MessageSetting> saveSetting(List<MessageSetting> settings);
}

View File

@ -0,0 +1,18 @@
package com.zsc.edu.gateway.modules.notice.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.modules.notice.entity.BulletinAttachment;
import com.zsc.edu.gateway.modules.notice.repo.BulletinAttachmentRepository;
import com.zsc.edu.gateway.modules.notice.service.BulletinAttachmentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
/**
* @author zhuang
*/
@AllArgsConstructor
@Service
public class BulletinAttachmentServiceImpl extends ServiceImpl<BulletinAttachmentRepository, BulletinAttachment> implements BulletinAttachmentService {
}

View File

@ -0,0 +1,208 @@
package com.zsc.edu.gateway.modules.notice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.exception.EmptyIdsException;
import com.zsc.edu.gateway.exception.PublishFailedException;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.notice.dto.BulletinDto;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import com.zsc.edu.gateway.modules.notice.entity.BulletinAttachment;
import com.zsc.edu.gateway.modules.notice.query.BulletinQuery;
import com.zsc.edu.gateway.modules.notice.repo.BulletinRepository;
import com.zsc.edu.gateway.modules.notice.service.BulletinAttachmentService;
import com.zsc.edu.gateway.modules.notice.service.BulletinService;
import com.zsc.edu.gateway.modules.notice.vo.BulletinVo;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import static com.zsc.edu.gateway.modules.notice.entity.Bulletin.State.*;
/**
* 系统公告Service
*
* @author harry_yao
*/
@AllArgsConstructor
@Service
public class BulletinServiceImpl extends ServiceImpl<BulletinRepository, Bulletin> implements BulletinService {
private final BulletinRepository repo;
private final BulletinAttachmentService bulletinAttachmentService;
private final UserRepository userRepository;
/**
* 查询公告详情
*
* @param id ID
* @param state 公告状态
* @return 公告详情
*/
@Override
public List<BulletinVo> detail(UserDetailsImpl userDetails, Long id, Bulletin.State state) {
List<BulletinVo> bulletins = repo.selectByBulletinId(id);
if (bulletins.isEmpty()) {
return Collections.emptyList();
}
for (BulletinVo bulletin : bulletins) {
if (state != null) {
bulletin.getState().checkStatus(state);
}
bulletin.setEditUsername(userRepository.selectNameById(bulletin.getEditUserId()));
bulletin.setPublishUsername(userRepository.selectNameById(bulletin.getPublishUserId()));
bulletin.setCloseUsername(userRepository.selectNameById(bulletin.getCloseUserId()));
}
return bulletins;
}
/**
* 新建公告
*
* @param userDetails 操作用户
* @param dto 表单数据
* @return 新建的公告
*/
@Override
public Bulletin create(UserDetailsImpl userDetails, BulletinDto dto) {
boolean existsByName=count(new LambdaQueryWrapper<Bulletin>().eq(Bulletin::getTitle,dto.getTitle())) > 0;
if(existsByName){
throw new ConstraintException("title", dto.title, "标题已存在");
}
Bulletin bulletin=new Bulletin();
BeanUtils.copyProperties(dto,bulletin);
bulletin.setCreateTime(LocalDateTime.now());
bulletin.setCreateBy(userDetails.getName());
bulletin.setEditUserId(userDetails.getId());
save(bulletin);
return bulletin;
}
/**
* 修改公告只能修改"编辑中""已发布"的公告
*
* @param userDetails 操作用户
* @param dto 表单数据
* @return 已修改的公告
*/
@Override
public Boolean update(UserDetailsImpl userDetails,BulletinDto dto, Long id) {
Bulletin bulletin = getById(id);
bulletin.state.checkStatus(EnumSet.of(edit, publish));
BeanUtils.copyProperties(dto, bulletin);
bulletin.setCreateBy(userDetails.getName());
bulletin.setCreateTime(LocalDateTime.now());
bulletin.state = edit;
return updateById(bulletin);
}
/**
* 发布公告只能发布"编辑中"的公告
*
* @param userDetails 操作用户
* @param ids ids
* @return 已发布的公告
*/
@Override
public List<String> publish(UserDetailsImpl userDetails, List<Long> ids)throws PublishFailedException, EmptyIdsException {
List<String> results=new ArrayList<>();
if (ids == null || ids.isEmpty()) {
throw new EmptyIdsException("您输入的集合为空");
}
List<Bulletin> bulletins=getBulletinsByIds(ids);
for (Bulletin bulletin : bulletins) {
try {
bulletin.state.checkStatus(EnumSet.of(edit));
} catch (Exception e) {
throw new PublishFailedException("发布失败: " + e.getMessage());
}
}
for(Bulletin bulletin:bulletins){
try{
bulletin.state = publish;
bulletin.setPublishUserId(userDetails.getId());
bulletin.setPublishTime(LocalDateTime.now());
boolean result=updateById(bulletin);
if(result){
results.add("发布成功");
}else {
throw new PublishFailedException("发布失败");
}
}catch(Exception e){
throw new PublishFailedException("发布失败: " + e.getMessage());
}
}
return results;
}
/**
* 切换关闭状态只能关闭"已发布"的公告只能开启已关闭的公告
*
* @param userDetails 操作用户
* @param id ID
* @return 已关闭的公告
*/
@Override
public Boolean close(UserDetailsImpl userDetails, Long id) {
Bulletin bulletin = getById(id);
bulletin.top = false;
if(bulletin.state==close){
bulletin.state.checkStatus(close);
bulletin.state = edit;
return updateById(bulletin);
}
bulletin.state.checkStatus(publish);
bulletin.state = close;
bulletin.setCloseUserId(userDetails.getId());
bulletin.setCloseTime(LocalDateTime.now());
return updateById(bulletin);
}
/**
* 切换公告置顶状态
*
* @param id ID
* @return 被更新的公告
*/
@Override
public Boolean toggleTop(Long id) {
Bulletin bulletin = getById(id);
bulletin.top = !bulletin.top;
return updateById(bulletin);
}
/**
*为公告添加附件
*
* @param bulletinId bulletinId
* @param attachmentIds attachments
* @return true
*/
@Override
public Boolean insertInto(Long bulletinId, Set<String> attachmentIds) {
List<BulletinAttachment> bulletinAttachments = attachmentIds.stream()
.map(attachmentId -> new BulletinAttachment(bulletinId, attachmentId))
.collect(Collectors.toList());
return bulletinAttachmentService.saveBatch(bulletinAttachments);
}
private List<Bulletin> getBulletinsByIds(List<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<Bulletin> queryWrapper=new LambdaQueryWrapper<>();
queryWrapper.in(Bulletin::getId, ids);
return repo.selectList(queryWrapper);
}
@Override
public IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, BulletinQuery query) {
return baseMapper.selectPageByConditions(page, query);
}
}

View File

@ -0,0 +1,16 @@
package com.zsc.edu.gateway.modules.notice.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.modules.notice.entity.MessageAttachment;
import com.zsc.edu.gateway.modules.notice.repo.MessageAttachmentRepository;
import com.zsc.edu.gateway.modules.notice.service.MessageAttachmentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
/**
* @author zhuang
*/
@Service
@AllArgsConstructor
public class MessageAttachmentServiceImpl extends ServiceImpl<MessageAttachmentRepository, MessageAttachment> implements MessageAttachmentService {
}

View File

@ -0,0 +1,226 @@
package com.zsc.edu.gateway.modules.notice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.framework.message.email.EmailSender;
import com.zsc.edu.gateway.framework.message.sms.SmsSender;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.attachment.service.AttachmentService;
import com.zsc.edu.gateway.modules.notice.dto.UserMessageDto;
import com.zsc.edu.gateway.modules.notice.entity.*;
import com.zsc.edu.gateway.modules.notice.query.UserMessageQuery;
import com.zsc.edu.gateway.modules.notice.repo.MessageRepository;
import com.zsc.edu.gateway.modules.notice.repo.MessageSettingRepository;
import com.zsc.edu.gateway.modules.notice.repo.UserMessageRepository;
import com.zsc.edu.gateway.modules.notice.service.MessageAttachmentService;
import com.zsc.edu.gateway.modules.notice.service.UserMessageService;
import com.zsc.edu.gateway.modules.notice.vo.UserMessageVo;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
* 用户消息Service
*
* @author harry_yao
*/
@AllArgsConstructor
@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageRepository, UserMessage> implements UserMessageService {
private final MessageRepository messageRepo;
private final MessageSettingRepository messageSettingRepo;
private final UserService userService;
private final AttachmentService attachmentService;
private final EmailSender emailSender;
private final SmsSender smsSender;
private final UserMessageRepository userMessageRepository;
private final MessageAttachmentService messageAttachmentService;
/**
* 查询消息详情
*
* @param messageId 消息ID
* @param userId 用户ID
* @return 查询详情
*/
@Override
public UserMessageVo detail(Long messageId, Long userId) {
return userMessageRepository.selectByMessageIdAndUserId(messageId, userId);
}
/**
* 分页查询用户消息
*
* @param query 查询表单
* @param page 分页参数
* @return 页面数据
*/
@Override
public IPage<UserMessageVo> page(Page<UserMessageVo> page, UserMessageQuery query) {
return userMessageRepository.query(page, query);
}
/**
* 统计用户未读消息数量
*
* @param userDetails 操作用户
* @return 未读消息数量
*/
@Override
public Integer countUnread(UserDetailsImpl userDetails) {
QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", userDetails.getId()).eq("is_read", true);
return Math.toIntExact(userMessageRepository.selectCount(queryWrapper));
}
/**
* 设为已读
*
* @param userDetails 操作用户
* @param messageIds 消息ID集合如为空则将该用户的所有未读消息设为已读
* @return 修改记录数量
*/
@Override
public Integer markAsRead(UserDetailsImpl userDetails, List<Long> messageIds) {
if (CollectionUtils.isEmpty(messageIds)) {
throw new RuntimeException("messageIds is NULL!");
}
UpdateWrapper<UserMessage> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_id", userDetails.getId()).in("message_id", messageIds);
updateWrapper.set("is_read", false);
updateWrapper.set("read_time", LocalDateTime.now());
return userMessageRepository.update(updateWrapper);
}
/**
* 管理员手动创建用户消息并发送
*
* @param dto 表单数据
* @return 创建的用户消息列表
*/
@Transactional
@Override
public Boolean createByAdmin(UserMessageDto dto) {
Set<User> users = dto.userIds.stream()
.map(userService::getById)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (users.isEmpty()) {
throw new RuntimeException("No valid users found for the provided userIds.");
}
Message message = new Message(dto.type, false, dto.email, dto.sms, dto.html,
dto.title, dto.content, null);
messageRepo.insert(message);
Set<UserMessage> userMessages = users.stream()
.map(user -> new UserMessage(null, user.getId(), message.getId(), false, null))
.collect(Collectors.toSet());
send(users, message);
return saveBatch(userMessages);
}
/**
* 将附件关联信息插入数据库
*
* @param messageId 消息ID用于关联消息和附件
* @param attachmentIds 附件ID列表表示需要插入的附件
* @return 返回一个布尔值表示批量插入是否成功
*/
@Override
public Boolean insertInto(Long messageId, List<String> attachmentIds) {
List<MessageAttachment> messageAttachments = attachmentIds.stream()
.map(attachmentId -> new MessageAttachment(messageId, attachmentId))
.collect(Collectors.toList());
return messageAttachmentService.saveBatch(messageAttachments);
}
/**
* 获取所有消息推送方式
*
* @return 消息设置列表
*/
@Override
public List<MessageSetting> getSetting() {
return messageSettingRepo.findAll();
}
/**
* 设置消息推送方式
*
* @param settings 消息设置集合
* @return 消息设置列表
*/
@Transactional
@Override
public List<MessageSetting> saveSetting(List<MessageSetting> settings) {
if (CollectionUtils.isEmpty(settings)) {
throw new RuntimeException("settings is NULL!");
}
for (MessageSetting setting : settings) {
try {
messageSettingRepo.insert(setting);
} catch (Exception e) {
throw new RuntimeException("设置失败" + e.getMessage());
}
}
return settings;
}
/**
* 以邮件短信等形式发送消息只有非html格式的消息才能以短信方式发送
*
* @param users 接收者
* @param message 消息
*/
@Async
void send(Set<User> users, Message message) {
if (message.email) {
emailSender.send(users.stream().map(User::getEmail).collect(Collectors.toSet()), message);
}
if (message.sms && !message.html) {
smsSender.send(users.stream().map(User::getPhone).collect(Collectors.toSet()), message.content);
}
}
/**
* 系统自动创建用户消息并发送
*
* @param receivers 接收者
* @param payload 消息内容
*/
@Transactional
public Boolean createBySystem(Set<User> receivers, MessagePayload payload) {
AtomicBoolean email = new AtomicBoolean(false);
AtomicBoolean sms = new AtomicBoolean(false);
Optional.of(messageSettingRepo.selectById(payload.type)).ifPresent(messageSetting -> {
email.set(messageSetting.email);
sms.set(messageSetting.sms);
});
Message message = new Message(payload.type, true, email.get(), sms.get(),
payload.html, payload.type.name(), payload.content, null);
messageRepo.insert(message);
Set<UserMessage> userMessages = receivers.stream().map(user ->
new UserMessage(null, user.getId(), message.getId(), false, null)).collect(Collectors.toSet());
send(receivers, message);
return saveBatch(userMessages);
}
}

View File

@ -0,0 +1,45 @@
package com.zsc.edu.gateway.modules.notice.vo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.attachment.vo.AttachmentVo;
import com.zsc.edu.gateway.modules.notice.entity.Bulletin;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author zhuang
*/
@Data
public class BulletinVo {
private Long id;
private String title;
private Bulletin.State state = Bulletin.State.edit;
private Boolean top;
private Long editUserId;
private String editUsername;
private LocalDateTime editTime;
private Long publishUserId;
private String publishUsername;
private LocalDateTime publishTime;
private Long closeUserId;
private String closeUsername;
private LocalDateTime closeTime;
private String content;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private String updateBy;
List<AttachmentVo> attachmentVos;
}

View File

@ -0,0 +1,51 @@
package com.zsc.edu.gateway.modules.notice.vo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.notice.entity.Message;
import com.zsc.edu.gateway.modules.notice.entity.MessageType;
import com.zsc.edu.gateway.modules.system.entity.User;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author zhuang
*/
@Data
public class UserMessageVo {
private Long id;
public Long userId;
public User user;
public Long messageId;
public Message message;
public Boolean isRead;
public LocalDateTime readTime;
public String username;
public String name;
public String avatar;
public String address;
public MessageType type = MessageType.other;
public Boolean system;
public Boolean email;
public Boolean sms;
public Boolean html;
public String title;
public String content;
private String remark;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private String updateBy;
public List<Attachment> attachments;
}

View File

@ -0,0 +1,81 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.modules.system.dto.AuthorityDto;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.query.AuthorityQuery;
import com.zsc.edu.gateway.modules.system.service.AuthorityService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/**
* 权限Controller
*
* @author zhuang
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/authority")
public class AuthorityController {
private AuthorityService service;
/**
* 返回权限列表 hasAuthority('AUTHORITY_QUERY')
*
* @param query 查询表单
* @return 权限列表
*/
@GetMapping
@PreAuthorize("hasAuthority('AUTHORITY_QUERY')")
public Page<Authority> query(AuthorityQuery query, Page<Authority> page) {
return service.page(page, query.wrapper());
}
/**
* 新建权限 hasAuthority('AUTHORITY_CREATE')
*
* @param dto 表单数据
* @return Authority 新建的权限
*/
@PostMapping
@PreAuthorize("hasAuthority('AUTHORITY_CREATE')")
public Authority create(@RequestBody AuthorityDto dto) {
return service.create(dto);
}
/**
* 更新权限 hasAuthority('AUTHORITY_UPDATE')
*
* @param dto 表单数据
* @param id 权限ID
* @return Dept 更新后的权限信息
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_UPDATE')")
public Boolean update(@RequestBody AuthorityDto dto, @PathVariable("id") Long id) {
return service.update(dto, id);
}
/***
* 删除权限 hasAuthority('AUTHORITY_DELETE')
* @param id 权限ID
* @return Boolean 是否删除成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
/**
* 更新权限启用状态
* */
@PatchMapping("/toggle/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_TOGGLE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
}

View File

@ -0,0 +1,94 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.query.DeptQuery;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.zsc.edu.gateway.modules.system.service.UserService;
import com.zsc.edu.gateway.modules.system.vo.DeptTree;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 部门Controller
*
* @author pengzheng
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/dept")
public class DeptController {
private final DeptService service;
private final UserService userService;
/**
* 返回管理部门列表 hasAuthority('DEPT_QUERY')
*
* @return 部门列表
*/
@GetMapping()
public List<DeptTree> getDeptTree() {
return service.getDeptTree();
}
/**
* 新建管理部门 hasAuthority('DEPT_CREATE')
*
* @param dto 表单数据
* @return Dept 新建的管理部门
*/
@PostMapping
@PreAuthorize("hasAuthority('DEPT_CREATE')")
public Dept create(@RequestBody DeptDto dto) {
return service.create(dto);
}
/**
* 更新管理部门 hasAuthority('DEPT_UPDATE')
*
* @param dto 表单数据
* @param id 部门ID
* @return Dept 更新后的部门
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('DEPT_UPDATE')")
public Boolean update(@RequestBody DeptDto dto, @PathVariable("id") Long id) {
return service.edit(dto, id);
}
/***
* 删除管理部门 hasAuthority('DEPT_DELETE')
* @param id 部门ID
* @return Boolean 是否删除成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('DEPT_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
/**
* 是否存在用户绑定此部门
* */
boolean hasUser = userService.count(new LambdaQueryWrapper<User>().eq(User::getDeptId, id)) > 0;
if (hasUser) {
throw new ConstraintException("存在与本部门绑定的用户,请先删除用户");
}
return service.removeById(id);
}
/**
* 更新管理部门状态
* */
@PatchMapping("/toggle/{id}")
@PreAuthorize("hasAuthority('DEPT_TOGGLE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
}

View File

@ -0,0 +1,119 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.modules.system.dto.AuthorityCreateDto;
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthCreateDto;
import com.zsc.edu.gateway.modules.system.dto.RoleDto;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.query.RoleQuery;
import com.zsc.edu.gateway.modules.system.service.RoleAuthService;
import com.zsc.edu.gateway.modules.system.service.RoleService;
import com.zsc.edu.gateway.modules.system.vo.RoleVo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
/**
* 角色Controller
*
* @author harry yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/role")
public class RoleController {
private final RoleService service;
private final RoleAuthService roleAuthService;
/**
* 返回所有角色列表 hasAuthority('ROLE_QUERY')
*
* @return 所有角色列表
*/
@GetMapping
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public Page<Role> query(RoleQuery query, Page<Role> page) {
return service.page(page, query.wrapper());
}
/**
* 新建角色 hasAuthority('ROLE_CREATE')
*
* @param dto 表单数据
* @return Role 新建的角色
*/
@PostMapping
@PreAuthorize("hasAuthority('ROLE_CREATE')")
public Boolean create(@RequestBody RoleDto dto) {
Role role= service.create(dto);
return role != null;
}
/**
* 更新角色 hasAuthority('ROLE_UPDATE')
*
* @param dto 表单数据
* @param id ID
* @return Role 更新后的角色
*/
@PatchMapping("{id}")
@PreAuthorize("hasAuthority('ROLE_UPDATE')")
public Boolean update(@RequestBody RoleDto dto, @PathVariable("id") Long id) {
// Role role = roleMapper.toEntity(dto);
// role.setId(id);
return service.updateRole(dto, id);
}
/**
* 切换角色"启动/禁用"状态 hasAuthority('ROLE_UPDATE')
*
* @param id ID
* @return Role 更新后的角色
*/
@PatchMapping("{id}/toggle")
@PreAuthorize("hasAuthority('ROLE_UPDATE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
/**
* 查询角色详情 hasAuthority('ROLE_QUERY')
*
* @param id ID
* @return Role 角色详情
*/
@GetMapping("{id}")
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public RoleVo detail(@PathVariable Long id) {
return service.detail(id);
}
/**
* 删除角色 hasAuthority('ROLE_DELETE')
*
* @param id ID
* @return Role 更新后的角色
*/
@DeleteMapping("{id}")
@PreAuthorize("hasAuthority('ROLE_DELETE')")
public Boolean delete(@PathVariable Long id) {
return service.delete(id);
}
/**
* 为角色添加权限 hasAuthority('ROLE_AUTHED')
*
* @return RoleAuthority 新的角色权限
*/
@PostMapping("/saveAuth/{id}")
@PreAuthorize("hasAuthority('ROLE_AUTHED')")
public Boolean addAuthed(@PathVariable Long id, @RequestBody Set<AuthorityCreateDto> authorities) {
return service.saveRoleAuths(id,authorities);
}
}

View File

@ -0,0 +1,200 @@
package com.zsc.edu.gateway.modules.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import com.zsc.edu.gateway.modules.system.dto.UserCreateDto;
import com.zsc.edu.gateway.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.gateway.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.gateway.modules.system.dto.UserUpdateDto;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.query.UserQuery;
import com.zsc.edu.gateway.modules.system.service.*;
import com.zsc.edu.gateway.modules.system.vo.UserDetail;
import com.zsc.edu.gateway.modules.system.vo.UserVo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 用户Controller
*
* @author harry yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("api/rest/user")
public class UserController {
private final UserService service;
private final RoleService roleService;
private final DeptService deptService;
private final AuthorityService authorityService;
/**
* 登录前获取csrfToken信息
* 登录成功后获取principal和csrfToken信息
*
* @param principal 认证主体
* @param csrfToken csrf令牌
* @return 包含csrf令牌和登录用户的认证主体信息
*/
@GetMapping("me")
public Map<String, Object> me(@AuthenticationPrincipal Object principal, CsrfToken csrfToken) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("user", principal);
map.put("csrf", csrfToken);
return map;
}
/**
* 用户获取自己的信息
*
* @param userDetails 操作用户
* @return 用户信息
*/
@GetMapping("self")
public UserDetail selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails) {
UserDetail userDetail = new UserDetail();
User user = service.selfDetail(userDetails);
user.dept = deptService.getById(user.deptId);
Role role= roleService.getOne(new QueryWrapper<Role>().eq("id",user.roleId));
userDetail.setPermissions(role.getName());
Set<Authority> authorities = authorityService.selectAuthoritiesByRoleId(role.getId());
userDetail.setAuthorities(authorities.stream().toList());
userDetail.setUser(user);
return userDetail;
}
/**
* 用户更新自己的信息
*
* @param userDetails 操作用户
* @param dto 表单数据
* @return 更新后的用户信息
*/
@PatchMapping("self")
public Boolean selfUpdate(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody UserSelfUpdateDto dto) {
return service.selfUpdate(userDetails, dto);
}
/**
* 用户更新自己的密码
*
* @param userDetails 操作用户
* @param dto 表单数据
*/
@PatchMapping("self/update-password")
public Boolean selfUpdatePassword(
@AuthenticationPrincipal UserDetailsImpl userDetails,
@RequestBody UserSelfUpdatePasswordDto dto
) {
return service.selfUpdatePassword(userDetails, dto);
}
/**
* 分页查询用户信息 hasAuthority('USER_QUERY')
*
* @param query 查询表单
* @param page 分页
* @return 分页用户信息
*/
@GetMapping
@PreAuthorize("hasAuthority('USER_QUERY·')")
public Page<User> query(UserQuery query, Page<User> page) {
return service.page(page, query.wrapper());
}
/**
* 新建用户 hasAuthority('USER_CREATE')
*
* @param dto 表单数据
* @return 新建的用户信息
*/
@PostMapping
@PreAuthorize("hasAuthority('USER_CREATE')")
public Boolean create(@RequestBody UserCreateDto dto) {
return service.create(dto);
}
/**
* 更新用户 hasAuthority('USER_UPDATE')
*
* @param dto 表单数据
* @param id ID
* @return 更新后的用户
*/
@PatchMapping("{id}")
@PreAuthorize("hasAuthority('USER_UPDATE')")
public Boolean update(@RequestBody UserUpdateDto dto, @PathVariable("id") Long id) {
return service.update(dto, id);
}
/**
* 更新用户密码 hasAuthority('USER_UPDATE')
*
* @param id ID
* @param password 新密码
*/
@PatchMapping("{id}/update-password")
@PreAuthorize("hasAuthority('USER_UPDATE')")
public Boolean updatePassword(@PathVariable("id") Long id, @RequestParam String password) {
return service.updatePassword(password, id);
}
/**
* 切换用户"启动/禁用"状态 hasAuthority('USER_DELETE')
*
* @param id ID
* @return Dept 更新后的用户
*/
@PatchMapping("{id}/toggle")
@PreAuthorize("hasAuthority('USER_DELETE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
/**
* 删除用户 hasAuthority('USER_DELETE')
* */
@DeleteMapping("{id}")
@PreAuthorize("hasAuthority('USER_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
/**
* 根据部门ID查询用户
* */
@GetMapping("dept/{id}")
public Collection<User> listByDept(@PathVariable("id") Long id) {
return service.list(new QueryWrapper<User>().eq("dept_id", id));
}
/**
* 根据ID查询用户
* */
@GetMapping("{id}")
public User detail(@PathVariable("id") Long id) {
return service.getById(id);
}
/**
* 发送邮件
* */
@GetMapping("send-email")
public String sendEmail(@RequestParam String email) {
return service.sendEmail(email);
}
}

View File

@ -0,0 +1,18 @@
package com.zsc.edu.gateway.modules.system.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author zhuang
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthorityCreateDto {
/**
* 权限名
*/
private String name;
}

Some files were not shown because too many files have changed in this diff Show More