first update
This commit is contained in:
parent
1d65900c4e
commit
2cebdf5895
2
.gitattributes
vendored
Normal file
2
.gitattributes
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/mvnw text eol=lf
|
||||
*.cmd text eol=crlf
|
19
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
19
.mvn/wrapper/maven-wrapper.properties
vendored
Normal 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
21
compose.yaml
Normal 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
259
mvnw
vendored
Normal 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
149
mvnw.cmd
vendored
Normal 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
200
pom.xml
Normal 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>
|
13
src/main/java/com/zsc/edu/gateway/IotGatewayApplication.java
Normal file
13
src/main/java/com/zsc/edu/gateway/IotGatewayApplication.java
Normal file
@ -0,0 +1,13 @@
|
||||
package com.zsc.edu.gateway;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class IotGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(IotGatewayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
@ -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);
|
||||
};
|
||||
}
|
||||
}
|
@ -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)));
|
||||
}
|
||||
}
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -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.MYSQL));
|
||||
// // 添加数据权限插件
|
||||
// MyDataPermissionInterceptor dataPermissionInterceptor = new MyDataPermissionInterceptor();
|
||||
// // 添加自定义的数据权限处理器
|
||||
// dataPermissionInterceptor.setDataPermissionHandler(new MyDataPermissionHandler());
|
||||
// interceptor.addInnerInterceptor(dataPermissionInterceptor);
|
||||
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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.登陆成功);
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.zsc.edu.gateway.framework.security;
|
||||
|
||||
import com.zsc.edu.gateway.exception.StateException;
|
||||
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
|
||||
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.RoleAuthoritiesRepository;
|
||||
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;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class JpaUserDetailsServiceImpl implements UserDetailsService {
|
||||
|
||||
private final UserRepository userRepo;
|
||||
private final RoleAuthoritiesRepository roleAuthoritiesRepository;
|
||||
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 + "' 已被禁用!请联系管理员");
|
||||
}
|
||||
|
||||
List<RoleAuthority> roleAuthorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
|
||||
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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
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.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 附件
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName(value ="attach_file")
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -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>{
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
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.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author fantianzhi
|
||||
* @description 针对表【attach_file(票据附件表)】的数据库操作Service
|
||||
* @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;
|
||||
|
||||
Attachment.Wrapper loadAsWrapper(String id);
|
||||
}
|
@ -0,0 +1,202 @@
|
||||
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);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -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/auth")
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
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 lombok.AllArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* 部门Controller
|
||||
*
|
||||
* @author pengzheng
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/rest/dept")
|
||||
public class DeptController {
|
||||
|
||||
private final DeptService service;
|
||||
private final UserService userService;
|
||||
|
||||
/**
|
||||
* 返回管理部门列表 hasAuthority('DEPT_QUERY')
|
||||
*
|
||||
* @param query 查询表单
|
||||
* @return 部门列表
|
||||
*/
|
||||
@GetMapping
|
||||
@PreAuthorize("hasAuthority('DEPT_QUERY')")
|
||||
public Page<Dept> query(DeptQuery query, Page<Dept> page) {
|
||||
return service.page(page, query.wrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建管理部门 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,201 @@
|
||||
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 RoleAuthService roleAuthService;
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 权限Dto
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AuthorityDto {
|
||||
/**
|
||||
* 权限名
|
||||
*/
|
||||
@NotBlank(message = "名字不能为空")
|
||||
public String name;
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
private Boolean enabled = true;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
public LambdaUpdateWrapper<Authority> updateWrapper(Long id) {
|
||||
LambdaUpdateWrapper<Authority> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
return updateWrapper.eq(Authority::getId, id)
|
||||
.set(Authority::getName, name)
|
||||
.set(StringUtils.hasText(remark), Authority::getRemark, remark);
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Dept;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* 部门Dto
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class DeptDto {
|
||||
|
||||
/**
|
||||
* 编码
|
||||
*/
|
||||
// @NotBlank(message = "编码不能为空")
|
||||
// public String code;
|
||||
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
@NotBlank(message = "名字不能为空")
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
public String remark;
|
||||
|
||||
/**
|
||||
* 父部门ID
|
||||
*/
|
||||
@NotNull(message = "上级公司不能为空")
|
||||
public Long pid;
|
||||
|
||||
public LambdaUpdateWrapper<Dept> updateWrapper(Long id) {
|
||||
LambdaUpdateWrapper<Dept> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
return updateWrapper.eq(Dept::getId, id)
|
||||
.set(Dept::getName, name)
|
||||
.set(StringUtils.hasText(remark), Dept::getRemark, remark);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,22 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class RoleAuthCreateDto {
|
||||
/**
|
||||
* 角色名
|
||||
*/
|
||||
private String roleName;
|
||||
/**
|
||||
* 权限名
|
||||
*/
|
||||
private String authName;
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class RoleAuthorityDto {
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
private Long roleId;
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private Long authorityId;
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Role;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 角色Dto
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class RoleDto {
|
||||
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
@NotBlank(message = "名称不能为空")
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
public String remark;
|
||||
|
||||
/**
|
||||
* 权限列表
|
||||
*/
|
||||
public Set<Authority> authorities;
|
||||
|
||||
public LambdaUpdateWrapper<Role> updateWrapper(Long id) {
|
||||
LambdaUpdateWrapper<Role> update = new LambdaUpdateWrapper<>();
|
||||
return update.eq(Role::getId, id)
|
||||
.set(Role::getName, name)
|
||||
.set(StringUtils.hasText(remark), Role::getRemark, remark);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.*;
|
||||
|
||||
/**
|
||||
* 用户新建Dto
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserCreateDto {
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
@NotBlank(message = "用户名不能为空")
|
||||
public String username;
|
||||
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
@NotBlank(message = "密码不能为空")
|
||||
public String password;
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
@Pattern(regexp = "^1[34578]\\d{9}$", message = "手机号格式不对")
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 邮箱
|
||||
*/
|
||||
@Email(message = "电子邮箱格式不对")
|
||||
public String email;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
public Boolean enable;
|
||||
|
||||
/**
|
||||
* 部门ID
|
||||
*/
|
||||
@NotNull(message = "部门不能为空")
|
||||
public Long deptId;
|
||||
|
||||
/**
|
||||
* 用户身份集合
|
||||
*/
|
||||
//@NotEmpty(message = "角色不能为空")
|
||||
public Long roleId;
|
||||
/**
|
||||
* 昵称
|
||||
* */
|
||||
public String nickName;
|
||||
/**
|
||||
* 头像
|
||||
* */
|
||||
public String avatar;
|
||||
/**
|
||||
* 地址
|
||||
* */
|
||||
public String address;
|
||||
|
||||
/**
|
||||
* 备注说明
|
||||
*/
|
||||
public String remark;
|
||||
/**
|
||||
* 验证码
|
||||
*/
|
||||
public Integer code;
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 用户更新自己信息Dto
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserSelfUpdateDto {
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
@Pattern(regexp = "^1[34578]\\d{9}$", message = "手机号格式不对")
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 邮箱
|
||||
*/
|
||||
@Email(message = "电子邮箱格式不对")
|
||||
public String email;
|
||||
/**
|
||||
* 昵称
|
||||
* */
|
||||
public String nickName;
|
||||
/**
|
||||
* 头像
|
||||
* */
|
||||
public String avatar;
|
||||
/**
|
||||
* 地址
|
||||
* */
|
||||
public String address;
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* 用户更新自己密码Dto
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserSelfUpdatePasswordDto {
|
||||
|
||||
/**
|
||||
* 旧密码
|
||||
*/
|
||||
@NotBlank(message = "旧密码不能为空")
|
||||
public String oldPassword;
|
||||
|
||||
/**
|
||||
* 新密码
|
||||
*/
|
||||
@NotBlank(message = "新密码不能为空")
|
||||
public String password;
|
||||
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
package com.zsc.edu.gateway.modules.system.dto;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.User;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 用户更新Dto
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserUpdateDto {
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
@Pattern(regexp = "^1[34578]\\d{9}$", message = "手机号格式不对")
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 邮箱
|
||||
*/
|
||||
@Email(message = "电子邮箱格式不对")
|
||||
public String email;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
public Boolean enable;
|
||||
|
||||
/**
|
||||
* 部门ID
|
||||
*/
|
||||
@NotNull(message = "部门不能为空")
|
||||
public Long deptId;
|
||||
/**
|
||||
* 昵称
|
||||
* */
|
||||
public String nickName;
|
||||
/**
|
||||
* 头像
|
||||
* */
|
||||
public String avatar;
|
||||
/**
|
||||
* 地址
|
||||
* */
|
||||
public String address;
|
||||
|
||||
/**
|
||||
* 用户身份集合
|
||||
*/
|
||||
@NotEmpty(message = "角色不能为空")
|
||||
public Long roleId;
|
||||
|
||||
public String remark;
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 操作权限
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_authority")
|
||||
public class Authority extends BaseEntity {
|
||||
/**
|
||||
* 权限名
|
||||
*/
|
||||
public String name;
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
private Boolean enabled = true;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author harry yao
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class BaseEntity implements Serializable {
|
||||
|
||||
/**
|
||||
* 自增主键
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
public Long id;
|
||||
|
||||
/**
|
||||
* 备注说明
|
||||
*/
|
||||
public String remark;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
public LocalDateTime createTime;
|
||||
/*
|
||||
* 创建人
|
||||
* */
|
||||
@TableField(value = "create_by", fill = FieldFill.INSERT)
|
||||
public String createBy;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
public LocalDateTime updateTime;
|
||||
/*
|
||||
* 更新人
|
||||
*
|
||||
* */
|
||||
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
|
||||
public String updateBy;
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
BaseEntity that = (BaseEntity) o;
|
||||
return id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().getName().hashCode() + id.hashCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 部门
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("sys_dept")
|
||||
public class Dept extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 上级部门
|
||||
*/
|
||||
private Long pid;
|
||||
|
||||
/**
|
||||
* 子部门数目
|
||||
*/
|
||||
private Integer subCount;
|
||||
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
private Integer deptSort;
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
private Boolean enabled = true;
|
||||
|
||||
@TableField(exist = false)
|
||||
public Set<Dept> children = new HashSet<>(0);
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 角色
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_role")
|
||||
public class Role extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 名称,唯一
|
||||
*/
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
private Boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 权限集合
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public Set<Authority> authorities;
|
||||
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,29 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* sys_role_authorities
|
||||
* @author zhuang
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("sys_role_authorities")
|
||||
public class RoleAuthority implements Serializable {
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
private Long roleId;
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
private Long authorityId;
|
||||
|
||||
// @TableField(exist = false)
|
||||
// private Set<Authority> authorities;
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.zsc.edu.gateway.common.enums.EnableState;
|
||||
import lombok.*;
|
||||
|
||||
/**
|
||||
* 用户
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Setter
|
||||
@Getter
|
||||
@JsonIgnoreProperties({"password"})
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName(value = "sys_user")
|
||||
public class User extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public String username;
|
||||
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
public String password;
|
||||
|
||||
/**
|
||||
* 手机号码
|
||||
*/
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 电子邮件
|
||||
*/
|
||||
public String email;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
public Boolean enableState = true;
|
||||
/**
|
||||
*
|
||||
*昵称
|
||||
* */
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 所属部门ID
|
||||
*/
|
||||
public Long deptId;
|
||||
|
||||
/**
|
||||
* 所属部门
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public Dept dept;
|
||||
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
public Long roleId;
|
||||
|
||||
/**
|
||||
* 拥有的角色
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public Role role;
|
||||
/**
|
||||
* 头像
|
||||
*/
|
||||
public String avatar;
|
||||
/**
|
||||
* 地址
|
||||
*/
|
||||
public String address;
|
||||
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,26 @@
|
||||
package com.zsc.edu.gateway.modules.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* sys_users_roles
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@TableName("sys_users_roles")
|
||||
public class UserRole implements Serializable {
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
private Long roleId;
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.gateway.modules.system.mapper;
|
||||
|
||||
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.dto.AuthorityDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface AuthorityMapper extends BaseMapper<AuthorityDto,Authority> {
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.gateway.modules.system.mapper;
|
||||
|
||||
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Dept;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingConstants;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface DeptMapper extends BaseMapper<DeptDto, Dept> {
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.gateway.modules.system.mapper;
|
||||
|
||||
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.dto.RoleAuthorityDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface RoleAuthorityMapper extends BaseMapper<RoleAuthorityDto,RoleAuthority> {
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.gateway.modules.system.mapper;
|
||||
|
||||
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.dto.RoleDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Role;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface RoleMapper extends BaseMapper<RoleDto, Role> {
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.gateway.modules.system.mapper;
|
||||
|
||||
import com.zsc.edu.gateway.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.dto.UserCreateDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.User;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface UserMapper extends BaseMapper<UserCreateDto, User> {
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.zsc.edu.gateway.modules.system.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AuthorityQuery {
|
||||
/**
|
||||
* 编码,前缀匹配
|
||||
*/
|
||||
public String code;
|
||||
|
||||
/**
|
||||
* 名称,模糊查询
|
||||
*/
|
||||
public String name;
|
||||
|
||||
public LambdaQueryWrapper<Authority> wrapper() {
|
||||
LambdaQueryWrapper<Authority> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.like(StringUtils.hasText(this.name), Authority::getName, this.name);
|
||||
return queryWrapper;
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.zsc.edu.gateway.modules.system.query;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Dept;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* 部门Query
|
||||
*
|
||||
* @author Yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class DeptQuery {
|
||||
|
||||
/**
|
||||
* 编码,前缀匹配
|
||||
*/
|
||||
public String code;
|
||||
|
||||
/**
|
||||
* 名称,模糊查询
|
||||
*/
|
||||
public String name;
|
||||
|
||||
public LambdaQueryWrapper<Dept> wrapper() {
|
||||
LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.like(StringUtils.hasText(this.name), Dept::getName, this.name);
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.zsc.edu.gateway.modules.system.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Role;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author ftz
|
||||
* 创建时间:2024/4/8 8:06
|
||||
* 描述: 角色查询参数
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class RoleQuery {
|
||||
/**
|
||||
* 名称,唯一
|
||||
*/
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
private Boolean enabled ;
|
||||
public LambdaQueryWrapper<Role> wrapper() {
|
||||
LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(this.enabled != null, Role::getEnabled, this.enabled);
|
||||
queryWrapper.like(this.name != null, Role::getName, this.name);
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.zsc.edu.gateway.modules.system.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.User;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 用户Query
|
||||
*
|
||||
* @author harry yao
|
||||
*/
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserQuery {
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public String username;
|
||||
|
||||
/**
|
||||
* 手机号码
|
||||
*/
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 电子邮件
|
||||
*/
|
||||
public String email;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
public Boolean enable;
|
||||
|
||||
/**
|
||||
* 角色集合
|
||||
*/
|
||||
public Long roleId;
|
||||
|
||||
/**
|
||||
* 部门集合
|
||||
*/
|
||||
public Long deptId;
|
||||
|
||||
|
||||
public LambdaQueryWrapper<User> wrapper() {
|
||||
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(StringUtils.hasText(this.username), User::getUsername, this.username);
|
||||
queryWrapper.eq(StringUtils.hasText(this.phone), User::getPhone, this.phone);
|
||||
queryWrapper.eq(StringUtils.hasText(this.email), User::getEmail, this.email);
|
||||
queryWrapper.eq(Objects.nonNull(this.enable), User::getEnableState, this.enable);
|
||||
queryWrapper.eq(Objects.nonNull(this.deptId),User::getDeptId,this.deptId);
|
||||
queryWrapper.eq(Objects.nonNull(this.roleId),User::getRoleId,this.roleId);
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
public interface AuthorityRepository extends BaseMapper<Authority> {
|
||||
|
||||
Set<Authority> selectAuthoritiesByRoleId (@Param("roleId") Long roleId);
|
||||
|
||||
Long getAuthorityIdByName(@Param("authName")String authName);
|
||||
}
|
||||
|
@ -0,0 +1,16 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Dept;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 部门 Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface DeptRepository extends BaseMapper<Dept> {
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
public interface RoleAuthoritiesRepository extends BaseMapper<RoleAuthority> {
|
||||
|
||||
@Select("select * from sys_role_authorities where role_id=#{roleId}")
|
||||
List<RoleAuthority> selectByRoleId(Long roleId);
|
||||
|
||||
// List<RoleAuthority> selectAuthorityByRoleId(@Param("roleId") Long roleId);
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Role;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.zsc.edu.gateway.modules.system.vo.RoleVo;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 角色表 Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface RoleRepository extends BaseMapper<Role> {
|
||||
|
||||
RoleVo selectRoleById(@Param("roleId") Long roleId);
|
||||
|
||||
Long getRoleIdByName(@Param("roleName") String roleName);
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.gateway.modules.system.entity.User;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.gateway.modules.system.vo.UserVo;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface UserRepository extends BaseMapper<User> {
|
||||
|
||||
// @Select("select u.*, sr.*, sra.* from sys_user u " +
|
||||
// "left join sys_role sr on u.role_id = sr.id " +
|
||||
// "left join sys_role_authorities sra on u.role_id = sra.role_id " +
|
||||
// "where u.username = #{username}")
|
||||
// User findByUsername(String username);
|
||||
User selectByUsername(String username);
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.zsc.edu.gateway.modules.system.repo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.UserRole;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
public interface UserRolesRepository extends BaseMapper<UserRole> {
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.zsc.edu.gateway.modules.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.zsc.edu.gateway.modules.system.dto.AuthorityDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
public interface AuthorityService extends IService<Authority> {
|
||||
|
||||
Authority create(AuthorityDto authorityDto);
|
||||
|
||||
Boolean update(AuthorityDto authorityDto,Long id);
|
||||
|
||||
Boolean toggle(Long id);
|
||||
|
||||
Set<Authority> selectAuthoritiesByRoleId(Long roleId);
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.zsc.edu.gateway.modules.system.service;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Dept;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 部门 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface DeptService extends IService<Dept> {
|
||||
|
||||
/**
|
||||
* 创建部门
|
||||
* @param dto
|
||||
*/
|
||||
Dept create(DeptDto dto);
|
||||
|
||||
/**
|
||||
* 更新部门
|
||||
* @param dto
|
||||
* @param id
|
||||
*/
|
||||
Boolean edit(DeptDto dto, Long id);
|
||||
|
||||
Boolean toggle(Long id);
|
||||
|
||||
/**
|
||||
* 生成部门树结构
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
// Dept listTree(Long id);
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.zsc.edu.gateway.modules.system.service;
|
||||
|
||||
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthCreateDto;
|
||||
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthorityDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 角色权限表 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface RoleAuthService extends IService<RoleAuthority> {
|
||||
|
||||
boolean removeByRoleId(Long id);
|
||||
|
||||
// boolean addRoleAuthority(RoleAuthCreateDto dto);
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.zsc.edu.gateway.modules.system.service;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.dto.AuthorityCreateDto;
|
||||
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.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.zsc.edu.gateway.modules.system.vo.RoleVo;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 角色表 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface RoleService extends IService<Role> {
|
||||
|
||||
Role create(RoleDto roleDto);
|
||||
|
||||
Boolean edit(RoleDto roleDto, Long id);
|
||||
|
||||
RoleVo detail(Long id);
|
||||
|
||||
Boolean toggle(Long id);
|
||||
|
||||
Boolean delete(Long id);
|
||||
|
||||
Boolean updateRole(RoleDto dto, Long id);
|
||||
|
||||
Boolean saveRoleAuths(Long roleId, Set<AuthorityCreateDto> authorities);
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.zsc.edu.gateway.modules.system.service;
|
||||
|
||||
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.gateway.modules.system.dto.*;
|
||||
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.vo.UserVo;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
public interface UserService extends IService<User> {
|
||||
|
||||
User selfDetail(UserDetailsImpl userDetails);
|
||||
|
||||
Boolean selfUpdate(UserDetailsImpl userDetails, UserSelfUpdateDto dto);
|
||||
|
||||
Boolean selfUpdatePassword(UserDetailsImpl userDetails, UserSelfUpdatePasswordDto dto);
|
||||
|
||||
Boolean create(UserCreateDto dto);
|
||||
|
||||
Boolean update(UserUpdateDto dto, Long id);
|
||||
|
||||
Boolean updatePassword(String password, Long id);
|
||||
|
||||
Boolean toggle(Long id);
|
||||
|
||||
String sendEmail(String email);
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package com.zsc.edu.gateway.modules.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.gateway.exception.ConstraintException;
|
||||
import com.zsc.edu.gateway.modules.system.dto.AuthorityDto;
|
||||
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthorityDto;
|
||||
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.mapper.AuthorityMapper;
|
||||
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
|
||||
import com.zsc.edu.gateway.modules.system.service.AuthorityService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class AuthorityServiceImpl extends ServiceImpl<AuthorityRepository, Authority> implements AuthorityService {
|
||||
private AuthorityMapper mapper;
|
||||
private AuthorityRepository repo;
|
||||
|
||||
@Override
|
||||
public Authority create(AuthorityDto authorityDto) {
|
||||
boolean existsByName = count(new LambdaQueryWrapper<Authority>().eq(Authority::getName, authorityDto.getName())) > 0;
|
||||
if (existsByName) {
|
||||
throw new ConstraintException("name", authorityDto.name, "权限已存在");
|
||||
}
|
||||
Authority authority = mapper.toEntity(authorityDto);
|
||||
save(authority);
|
||||
return authority;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean update(AuthorityDto authorityDto, Long id) {
|
||||
boolean isExists = count(new LambdaQueryWrapper<Authority>().ne(Authority::getId, id).eq(Authority::getName, authorityDto.getName())) > 0;
|
||||
if (isExists) {
|
||||
throw new ConstraintException("name", authorityDto.name, "同名权限已存在");
|
||||
}
|
||||
return update(authorityDto.updateWrapper(id));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Boolean toggle(Long id) {
|
||||
Authority authority = getById(id);
|
||||
authority.setEnabled(!authority.getEnabled());
|
||||
return updateById(authority);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Authority> selectAuthoritiesByRoleId(Long roleId){
|
||||
return baseMapper.selectAuthoritiesByRoleId(roleId);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package com.zsc.edu.gateway.modules.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
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.mapper.DeptMapper;
|
||||
import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
|
||||
import com.zsc.edu.gateway.modules.system.service.DeptService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 部门 服务实现类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class DeptServiceImpl extends ServiceImpl<DeptRepository, Dept> implements DeptService {
|
||||
|
||||
private final DeptMapper mapper;
|
||||
|
||||
@Override
|
||||
public Dept create(DeptDto dto) {
|
||||
boolean existsByName = count(new LambdaQueryWrapper<Dept>().eq(Dept::getName, dto.getName())) > 0;
|
||||
if (existsByName) {
|
||||
throw new ConstraintException("name", dto.name, "部门已存在");
|
||||
}
|
||||
Dept dept = mapper.toEntity(dto);
|
||||
save(dept);
|
||||
return dept;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean edit(DeptDto dto, Long id) {
|
||||
boolean isExists = count(new LambdaQueryWrapper<Dept>().ne(Dept::getId, id).eq(Dept::getName, dto.getName())) > 0;
|
||||
if (isExists) {
|
||||
throw new ConstraintException("name", dto.name, "同名部门已存在");
|
||||
}
|
||||
return update(dto.updateWrapper(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean toggle(Long id) {
|
||||
Dept dept = getById(id);
|
||||
dept.setEnabled(!dept.getEnabled());
|
||||
return updateById(dept);
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public Dept listTree(Long deptId) {
|
||||
// Dept rootDept;
|
||||
// List<Dept> all = list(null);
|
||||
// HashSet<Dept> deptList = new HashSet<>(all);
|
||||
// rootDept = DeptTreeUtil.initTree(deptList);
|
||||
// if (deptId != null) {
|
||||
// return rootDept.id.equals(deptId) ? rootDept : DeptTreeUtil.getChildNode(rootDept.children, deptId);
|
||||
// }
|
||||
// return rootDept;
|
||||
// }
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.zsc.edu.gateway.modules.system.service.impl;
|
||||
|
||||
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthCreateDto;
|
||||
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthorityDto;
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
|
||||
//import com.zsc.edu.gateway.modules.system.mapper.RoleAuthorityMapper;
|
||||
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
|
||||
import com.zsc.edu.gateway.modules.system.repo.RoleAuthoritiesRepository;
|
||||
import com.zsc.edu.gateway.modules.system.repo.RoleRepository;
|
||||
import com.zsc.edu.gateway.modules.system.service.RoleAuthService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthoritiesRepository, RoleAuthority> implements RoleAuthService {
|
||||
// private RoleAuthorityMapper mapper;
|
||||
private AuthorityRepository repo;
|
||||
private RoleRepository roleRepository;
|
||||
|
||||
@Override
|
||||
public boolean removeByRoleId(Long roleId) {
|
||||
return remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, roleId));
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public boolean addRoleAuthority(RoleAuthCreateDto dto){
|
||||
// Long authId=repo.getAuthorityIdByName(dto.getAuthName());
|
||||
// Long roleId=roleRepository.getRoleIdByName(dto.getRoleName());
|
||||
// RoleAuthorityDto dto1=new RoleAuthorityDto();
|
||||
// dto1.setAuthorityId(authId);
|
||||
// dto1.setRoleId(roleId);
|
||||
// RoleAuthority roleAuthority = mapper.toEntity(dto1);
|
||||
// return save(roleAuthority);
|
||||
// }
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
package com.zsc.edu.gateway.modules.system.service.impl;
|
||||
|
||||
import com.zsc.edu.gateway.exception.ConstraintException;
|
||||
import com.zsc.edu.gateway.modules.system.dto.AuthorityCreateDto;
|
||||
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.entity.RoleAuthority;
|
||||
import com.zsc.edu.gateway.modules.system.entity.UserRole;
|
||||
import com.zsc.edu.gateway.modules.system.mapper.RoleMapper;
|
||||
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
|
||||
import com.zsc.edu.gateway.modules.system.repo.RoleRepository;
|
||||
import com.zsc.edu.gateway.modules.system.repo.UserRolesRepository;
|
||||
import com.zsc.edu.gateway.modules.system.service.RoleAuthService;
|
||||
import com.zsc.edu.gateway.modules.system.service.RoleService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.gateway.modules.system.vo.RoleVo;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 角色表 服务实现类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class RoleServiceImpl extends ServiceImpl<RoleRepository, Role> implements RoleService {
|
||||
|
||||
private final RoleMapper mapper;
|
||||
private final UserRolesRepository urRepo;
|
||||
|
||||
private final RoleAuthService roleAuthService;
|
||||
private final AuthorityRepository authorityRepository;
|
||||
private final RoleRepository roleRepository;
|
||||
|
||||
@Override
|
||||
public Role create(RoleDto dto) {
|
||||
boolean existsByName = count(new LambdaQueryWrapper<Role>().eq(Role::getName, dto.getName())) > 0;
|
||||
if (existsByName) {
|
||||
throw new ConstraintException("name", dto.name, "角色已存在");
|
||||
}
|
||||
Role role = mapper.toEntity(dto);
|
||||
save(role);
|
||||
// saveRoleAuths(role.getId(), role.getAuthorities());
|
||||
return role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean toggle(Long id) {
|
||||
Role role = getById(id);
|
||||
role.setEnabled(!role.getEnabled());
|
||||
return updateById(role);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean delete(Long id) {
|
||||
boolean hasUser = urRepo.selectCount(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, id)) > 0;
|
||||
if (hasUser) {
|
||||
throw new ConstraintException("存在与本角色绑定的用户,请先删除用户");
|
||||
}
|
||||
|
||||
// 删除角色权限关联关系
|
||||
roleAuthService.removeByRoleId(id);
|
||||
return removeById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateRole(RoleDto dto, Long id) {
|
||||
Role role =mapper.toEntity(dto);
|
||||
role.setId(id);
|
||||
if (dto.getAuthorities() != null && !dto.getAuthorities().isEmpty()) {
|
||||
roleAuthService.remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id));
|
||||
Set<Authority> authorities = new HashSet<>(dto.getAuthorities());
|
||||
// roleAuthService.saveBatch(authorities.stream().map(authority -> new RoleAuthority(id, authority.getId())).collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
return updateById(role);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean edit(RoleDto dto, Long id) {
|
||||
boolean existsByName = count(new LambdaQueryWrapper<Role>().ne(Role::getId, id).eq(Role::getName, dto.getName())) > 0;
|
||||
if (existsByName) {
|
||||
throw new ConstraintException("name", dto.name, "同名角色已存在");
|
||||
}
|
||||
roleAuthService.remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id));
|
||||
// saveRoleAuths(id, dto.getAuthorities());
|
||||
return update(dto.updateWrapper(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RoleVo detail(Long id) {
|
||||
// Role role = getById(id);
|
||||
// // TODO 联表查询
|
||||
// // List<RoleAuthority> roleAuthorities = roleAuthService.list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, role.id));
|
||||
// role.authorities = authorityRepository.selectAuthoritiesByRoleId(role.id);
|
||||
return roleRepository.selectRoleById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean saveRoleAuths(Long roleId, Set<AuthorityCreateDto> authorities) {
|
||||
// 保存角色关联权限
|
||||
List<RoleAuthority> roleAuthorities = authorities.stream().map(authority -> new RoleAuthority(roleId, authorityRepository.getAuthorityIdByName(authority.getName()))).collect(Collectors.toList());
|
||||
return roleAuthService.saveBatch(roleAuthorities);
|
||||
}
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
package com.zsc.edu.gateway.modules.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.gateway.exception.ConstraintException;
|
||||
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.Dept;
|
||||
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.mapper.UserMapper;
|
||||
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
|
||||
import com.zsc.edu.gateway.modules.system.service.UserService;
|
||||
import com.zsc.edu.gateway.modules.system.utils.sendMail;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务实现类
|
||||
* </p>
|
||||
*
|
||||
* @author Yao
|
||||
* @since 2023-04-06
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class UserServiceImpl extends ServiceImpl<UserRepository, User> implements UserService {
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final RoleServiceImpl roleService;
|
||||
private final DeptServiceImpl deptService;
|
||||
private final sendMail send;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public Boolean create(UserCreateDto dto) {
|
||||
User user = new User();
|
||||
userMapper.convert(dto, user);
|
||||
return save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean update(UserUpdateDto dto, Long id) {
|
||||
User user = getById(id);
|
||||
boolean existsByPhone = count(new LambdaQueryWrapper<User>().eq(User::getPhone, dto.getPhone())) > 0;
|
||||
boolean existsByEmail = count(new LambdaQueryWrapper<User>().eq(User::getEmail, dto.getEmail())) > 0;
|
||||
if (user.getPhone().equals(dto.getPhone()) && existsByPhone) {
|
||||
throw new ConstraintException("phone", dto.phone, "手机号已存在");
|
||||
}
|
||||
if (user.getEmail().equals(dto.getEmail()) && existsByEmail) {
|
||||
throw new ConstraintException("email", dto.email, "邮箱地址已存在");
|
||||
}
|
||||
BeanUtils.copyProperties(dto, user);
|
||||
return updateById(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updatePassword(String password, Long id) {
|
||||
User user = getById(id);
|
||||
user.setPassword(passwordEncoder.encode(password));
|
||||
return save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean toggle(Long id) {
|
||||
User user = getById(id);
|
||||
user.setEnableState(!user.getEnableState());
|
||||
return updateById(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String sendEmail(String email) {
|
||||
send.sendEmailMessage(email);
|
||||
return "发送成功";
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public User selfDetail(UserDetailsImpl userDetails) {
|
||||
return getById(userDetails.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean selfUpdate(UserDetailsImpl userDetails, UserSelfUpdateDto dto) {
|
||||
User user = getById(userDetails.getId());
|
||||
boolean existsByPhone = count(new LambdaQueryWrapper<User>().ne(User::getId, userDetails.getId()).eq(User::getPhone, dto.getPhone())) > 0;
|
||||
if (existsByPhone) {
|
||||
throw new ConstraintException("phone", dto.phone, "手机号已存在");
|
||||
}
|
||||
boolean existsByEmail = count(new LambdaQueryWrapper<User>().ne(User::getId, userDetails.getId()).eq(User::getEmail, dto.getEmail())) > 0;
|
||||
if (existsByEmail) {
|
||||
throw new ConstraintException("email", dto.email, "邮箱地址已存在");
|
||||
}
|
||||
BeanUtils.copyProperties(dto, user);
|
||||
|
||||
return updateById(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean selfUpdatePassword(UserDetailsImpl userDetails, UserSelfUpdatePasswordDto dto) {
|
||||
User user = getById(userDetails.getId());
|
||||
if (!passwordEncoder.matches(dto.oldPassword, user.password)) {
|
||||
throw new ConstraintException("旧密码不对");
|
||||
}
|
||||
user.setPassword(passwordEncoder.encode(dto.password));
|
||||
return updateById(user);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package com.zsc.edu.gateway.modules.system.utils;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import lombok.Getter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.text.MessageFormat;
|
||||
|
||||
/**
|
||||
* @author ftz
|
||||
* 创建时间:2024/4/5 17:24
|
||||
* 描述: 根据邮箱发送验证码
|
||||
*/
|
||||
@Component
|
||||
public class sendMail {
|
||||
@jakarta.annotation.Resource
|
||||
JavaMailSenderImpl mailSender;
|
||||
@Getter
|
||||
private int randomCode;
|
||||
|
||||
@Value("${spring.mail.username}")
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 读取邮件模板
|
||||
* 替换模板中的信息
|
||||
*
|
||||
* @param title 内容
|
||||
* @return
|
||||
*/
|
||||
public String buildContent(String title) {
|
||||
//加载邮件html模板
|
||||
Resource resource = new ClassPathResource("mailTemplate/mailtemplate.ftl");
|
||||
InputStream inputStream = null;
|
||||
BufferedReader fileReader = null;
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
String line = "";
|
||||
try {
|
||||
inputStream = resource.getInputStream();
|
||||
fileReader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
while ((line = fileReader.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (fileReader != null) {
|
||||
try {
|
||||
fileReader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
//替换html模板中的参数
|
||||
return MessageFormat.format(buffer.toString(), title);
|
||||
}
|
||||
public void sendEmailMessage(String email) {
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
try {
|
||||
randomCode = (int) ((Math.random() * 9 + 1) * 100000);
|
||||
// RandomStringUtils
|
||||
//邮箱发送内容组成
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
helper.setSubject("主题");
|
||||
|
||||
helper.setText(buildContent(randomCode + ""), true);
|
||||
helper.setTo(email);
|
||||
helper.setFrom("发件人名字" + '<' + username + '>');
|
||||
mailSender.send(message);
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package com.zsc.edu.gateway.modules.system.vo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author lenovo
|
||||
*/
|
||||
@Data
|
||||
public class RoleVo {
|
||||
/**
|
||||
* 自增主键
|
||||
*/
|
||||
public Long id;
|
||||
/**
|
||||
* 角色名
|
||||
*/
|
||||
private String name;
|
||||
/**
|
||||
*级别
|
||||
*/
|
||||
private Integer level;
|
||||
/**
|
||||
* 描述
|
||||
*/
|
||||
private String description;
|
||||
/**
|
||||
* 数据权限
|
||||
*/
|
||||
private String dataScope;
|
||||
/**
|
||||
* 创建人
|
||||
*/
|
||||
private String createBy;
|
||||
/**
|
||||
* 更新人
|
||||
*/
|
||||
private String updateBy;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private Date updateTime;
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
private Boolean enabled;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
private List<Authority> authorities;
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.zsc.edu.gateway.modules.system.vo;
|
||||
|
||||
import com.zsc.edu.gateway.modules.system.entity.Authority;
|
||||
import com.zsc.edu.gateway.modules.system.entity.User;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author ftz
|
||||
* 创建时间:16/2/2024 下午6:20
|
||||
* 描述: TODO
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class UserDetail {
|
||||
private User user;
|
||||
private List<Authority> authorities;
|
||||
private String permissions;
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.zsc.edu.gateway.modules.system.vo;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class UserVo {
|
||||
/**
|
||||
* 自增主键
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
public Long id;
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public String username;
|
||||
|
||||
/**
|
||||
* 手机号码
|
||||
*/
|
||||
public String phone;
|
||||
|
||||
/**
|
||||
* 电子邮件
|
||||
*/
|
||||
public String email;
|
||||
|
||||
/**
|
||||
* 启用状态
|
||||
*/
|
||||
public Boolean enabled;
|
||||
/**
|
||||
*
|
||||
*昵称
|
||||
* */
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 所属部门ID
|
||||
*/
|
||||
public Long deptId;
|
||||
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
public Long roleId;
|
||||
/**
|
||||
* 头像
|
||||
*/
|
||||
public String avatar;
|
||||
/**
|
||||
* 地址
|
||||
*/
|
||||
public String address;
|
||||
|
||||
LocalDateTime createTime;
|
||||
LocalDateTime updateTime;
|
||||
|
||||
}
|
41
src/main/resources/application-dev.yml
Normal file
41
src/main/resources/application-dev.yml
Normal file
@ -0,0 +1,41 @@
|
||||
server:
|
||||
port: 8081
|
||||
|
||||
mybatis-plus:
|
||||
type-aliases-package: com.zsc.edu.gateway.modules.*.entity
|
||||
mapper-locations: classpath:mappers/*.xml
|
||||
configuration:
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://localhost:5432/gateway?ssl=false&TimeZone=Asia/Shanghai
|
||||
username: root
|
||||
password: 123123
|
||||
driver-class-name: org.postgresql.Driver
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 40MB
|
||||
max-request-size: 40MB
|
||||
mail:
|
||||
# 配置 SMTP 服务器地址
|
||||
host: smtp.qq.com
|
||||
# 发送者邮箱
|
||||
username: 2179732328@qq.com
|
||||
# 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
|
||||
password: mabpnbtqqezjdjde
|
||||
# 端口号465或587
|
||||
port: 587
|
||||
# 默认的邮件编码为UTF-8
|
||||
default-encoding: UTF-8
|
||||
# 配置SSL 加密工厂
|
||||
properties:
|
||||
mail:
|
||||
smtp:
|
||||
socketFactoryClass: javax.net.ssl.SSLSocketFactory
|
||||
#表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
|
||||
debug: true
|
||||
|
||||
storage:
|
||||
attachment: ./storage/attachment
|
||||
temp: ./storage/temp
|
41
src/main/resources/application-prod.yml
Normal file
41
src/main/resources/application-prod.yml
Normal file
@ -0,0 +1,41 @@
|
||||
server:
|
||||
port: 8081
|
||||
|
||||
mybatis-plus:
|
||||
type-aliases-package: com.zsc.edu.gateway.modules.*.entity
|
||||
mapper-locations: classpath:mappers/*.xml
|
||||
type-handlers-package: com.zsc.edu.gateway.framework.mybatisplus
|
||||
configuration:
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://${MYSQL_HOST:mysql}:${MYSQL_PORT:3306}/study?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&characterEncoding=utf8&serverTimezone=Hongkong
|
||||
username: root
|
||||
password: 123123
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 40MB
|
||||
max-request-size: 40MB
|
||||
mail:
|
||||
# 配置 SMTP 服务器地址
|
||||
host: smtp.qq.com
|
||||
# 发送者邮箱
|
||||
username: 2179732328@qq.com
|
||||
# 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
|
||||
password: mabpnbtqqezjdjde
|
||||
# 端口号465或587
|
||||
port: 587
|
||||
# 默认的邮件编码为UTF-8
|
||||
default-encoding: UTF-8
|
||||
# 配置SSL 加密工厂
|
||||
properties:
|
||||
mail:
|
||||
smtp:
|
||||
socketFactoryClass: javax.net.ssl.SSLSocketFactory
|
||||
#表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
|
||||
debug: true
|
||||
storage:
|
||||
attachment: ./storage/attachment
|
||||
temp: ./storage/temp
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user