first commit

This commit is contained in:
vertoryao 2023-12-28 16:02:07 +08:00
parent 6a8cf5ffa1
commit 9e250964b1
93 changed files with 4354 additions and 0 deletions

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

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

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar

10
compose.yaml Normal file
View File

@ -0,0 +1,10 @@
services:
mysql:
image: 'mysql:latest'
environment:
- 'MYSQL_DATABASE=mydatabase'
- 'MYSQL_PASSWORD=secret'
- 'MYSQL_ROOT_PASSWORD=verysecret'
- 'MYSQL_USER=myuser'
ports:
- '3306'

308
mvnw vendored Normal file
View File

@ -0,0 +1,308 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
exit 1
fi
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

205
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,205 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

144
pom.xml Normal file
View File

@ -0,0 +1,144 @@
<?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.2.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zsc.edu</groupId>
<artifactId>bill</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bill-backend</name>
<description>bill-backend</description>
<properties>
<java.version>17</java.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<mybatis-plus.version>3.5.5</mybatis-plus.version>
</properties>
<dependencies>
<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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
<scope>runtime</scope>
</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-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>
<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>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package com.zsc.edu.bill;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BillApplication {
public static void main(String[] args) {
SpringApplication.run(BillApplication.class, args);
}
}

View File

@ -0,0 +1,64 @@
package com.zsc.edu.bill;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.*;
import com.zsc.edu.bill.modules.system.repo.DeptRepository;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesReposity;
import com.zsc.edu.bill.modules.system.service.RoleService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Component
@Profile("!test")
public class FirstTimeInitializer implements CommandLineRunner {
private final DeptRepository deptRepo;
private final RoleRepository roleRepo;
private final RoleService roleService;
private final UserRolesReposity userRolesRepo;
private final UserRepository userRepo;
private final PasswordEncoder passwordEncoder;
@Override
public void run(String... args) throws Exception {
Dept dept1 = new Dept();
Role role = new Role();
if (deptRepo.selectCount(new QueryWrapper<>()) == 0) {
dept1.setName("管理部门");
deptRepo.insert(dept1);
}
if (roleRepo.selectCount(new QueryWrapper<>()) == 0) {
RoleDto dto = new RoleDto();
dto.setName("超级管理员");
dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
role = roleService.create(dto);
}
if (userRepo.selectCount(new QueryWrapper<>()) == 0) {
User user = new User();
user.setUsername("管理员");
user.setPassword(passwordEncoder.encode("123456"));
user.setEnabled(true);
user.setPhone("13827993921");
user.setEmail("123@qq.com");
user.setDeptId(dept1.getId());
user.setRoleId(role.getId());
userRepo.insert(user);
}
}
}

View File

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

View File

@ -0,0 +1,10 @@
package com.zsc.edu.bill.common.mapstruct;
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);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,27 @@
package com.zsc.edu.bill.framework.mybatisplus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
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) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
}
}

View File

@ -0,0 +1,23 @@
package com.zsc.edu.bill.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.bill.modules.*.repo")
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,47 @@
package com.zsc.edu.bill.framework.security;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
/**
* @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) {
// Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// String sessionId = request.getRequestedSessionId();
// String remoteAddr = request.getRemoteAddr();
// User user = userService.getOne(((UserDetailsImpl) principal).getId());
// String agent = request.getHeader("User-Agent");
// UserAgent userAgent = new UserAgent(agent);
// OnlineUser onlineUser = onlineUserService.create(
// sessionId,
// user.username,
// user.name,
// null,//user.identity.dept.name,
// remoteAddr,
// userAgent.getBrowser().getName(),
// userAgent.getOperatingSystem().getName(),
// LocalDateTime.now()
// );
// loginLogService.create(onlineUser.username, onlineUser.name, onlineUser.deptName,
// onlineUser.ip, onlineUser.browser, onlineUser.os,
// onlineUser.loginTime, LoginLog.Result.登陆成功);
}
}

View File

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

View File

@ -0,0 +1,32 @@
package com.zsc.edu.bill.framework.security;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author harry_yao
*/
@AllArgsConstructor
@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepo;
@Override
@Transactional(rollbackFor = Exception.class)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
// .orElseThrow(() ->
// new UsernameNotFoundException("用户 '" + username + "' 不存在!")
// );
// user.getIdentities().stream().filter(identity -> identity.role.enableState == EnableState.启用)
// .forEach(identity -> Hibernate.initialize(identity.role.authorities));
return UserDetailsImpl.from(user);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,92 @@
package com.zsc.edu.bill.framework.security;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
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 jakarta.annotation.Resource;
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;
@Resource
private final DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
// @Bean
// public JsonAuthenticationFilter jsonAuthenticationFilter(AuthenticationManager authenticationManager) throws Exception {
// JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
// filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
// filter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
// filter.setFilterProcessesUrl("/api/rest/user/login");
// filter.setAuthenticationManager(authenticationManager);
// return filter;
// }
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// 允许用户json登录
JsonAuthenticationFilter jsonAuthenticationFilter = new JsonAuthenticationFilter();
jsonAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
jsonAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
jsonAuthenticationFilter.setFilterProcessesUrl("/api/rest/user/login");
jsonAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/rest/user/me").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"))
.sessionManagement(session -> session
.maximumSessions(3)
.sessionRegistry(sessionRegistry)
.expiredSessionStrategy(new CustomSessionInformationExpiredStrategy()))
.build();
}
}

View File

@ -0,0 +1,74 @@
package com.zsc.edu.bill.framework.security;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
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 enabled;
public Dept dept;
public Role role;
public Set<Authority> authorities;
public static UserDetailsImpl from(User user) {
Set<Authority> authorities = user.role.authorities;
return new UserDetailsImpl(
user.id,
user.username,
user.password,
user.enabled,
user.dept,
user.role,
authorities
);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -0,0 +1,62 @@
package com.zsc.edu.bill.modules.system.controller;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.query.DeptQuery;
import com.zsc.edu.bill.modules.system.service.DeptService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
/**
* 部门Controller
*
* @author pengzheng
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/dept")
public class DeptController {
private final DeptService service;
/**
* 返回管理部门列表 hasAuthority('DEPT_QUERY')
*
* @param query 查询表单
* @return 部门列表
*/
@GetMapping
@PreAuthorize("hasAuthority('DEPT_QUERY')")
public Collection<Dept> list(DeptQuery query) {
return service.list(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);
}
}

View File

@ -0,0 +1,100 @@
package com.zsc.edu.bill.modules.system.controller;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.mapper.RoleMapper;
import com.zsc.edu.bill.modules.system.service.RoleService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
/**
* 角色Controller
*
* @author harry yao
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/role")
public class RoleController {
private final RoleMapper roleMapper;
private final RoleService service;
/**
* 返回所有角色列表 hasAuthority('ROLE_QUERY')
*
* @return 所有角色列表
*/
@GetMapping
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public Collection<Role> list() {
return service.list();
}
/**
* 新建角色 hasAuthority('ROLE_CREATE')
*
* @param dto 表单数据
* @return Role 新建的角色
*/
@PostMapping
@PreAuthorize("hasAuthority('ROLE_CREATE')")
public Boolean create(@RequestBody RoleDto dto) {
Role role = roleMapper.toEntity(dto);
return service.save(role);
}
/**
* 更新角色 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.updateById(role);
}
/**
* 切换角色"启动/禁用"状态 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 Role detail(@PathVariable Long id) {
return service.detail(id);
}
/**
* 查询角色详情 hasAuthority('ROLE_QUERY')
*
* @param id ID
* @return Role 更新后的角色
*/
@DeleteMapping("{id}")
public Boolean delete(@PathVariable Long id) {
return service.delete(id);
}
}

View File

@ -0,0 +1,158 @@
package com.zsc.edu.bill.modules.system.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.dto.UserCreateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.bill.modules.system.dto.UserUpdateDto;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.query.UserQuery;
import com.zsc.edu.bill.modules.system.service.DeptService;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.zsc.edu.bill.modules.system.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zsc.edu.bill.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.LinkedHashMap;
import java.util.Map;
/**
* 用户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;
/**
* 登录前获取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 User selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails) {
User user = service.selfDetail(userDetails);
user.dept = deptService.getById(user.deptId);
return user;
}
/**
* 用户更新自己的信息
*
* @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<UserVo> query(UserQuery query, PageDTO<User> page) {
return service.page(query, page);
}
/**
* 新建用户 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 void updatePassword(@PathVariable("id") Long id, @RequestParam String password) {
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);
}
}

View File

@ -0,0 +1,53 @@
package com.zsc.edu.bill.modules.system.dto;
import com.zsc.edu.bill.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);
}
}

View File

@ -0,0 +1,47 @@
package com.zsc.edu.bill.modules.system.dto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.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);
}
}

View File

@ -0,0 +1,67 @@
package com.zsc.edu.bill.modules.system.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.validation.constraints.*;
import java.util.Set;
/**
* 用户新建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 Set<Long> roleIds;
/**
* 备注说明
*/
public String remark;
}

View File

@ -0,0 +1,33 @@
package com.zsc.edu.bill.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;
}

View File

@ -0,0 +1,31 @@
package com.zsc.edu.bill.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;
}

View File

@ -0,0 +1,69 @@
package com.zsc.edu.bill.modules.system.dto;
import com.zsc.edu.bill.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;
import java.util.Set;
/**
* 用户更新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;
/**
* 用户身份集合
*/
@NotEmpty(message = "角色不能为空")
public Set<Long> roleIds;
public String remark;
public LambdaUpdateWrapper<User> updateWrapper(Long id) {
LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
return updateWrapper.eq(User::getId, id)
.set(User::getPhone, phone)
.set(StringUtils.hasText(email), User::getEmail, email)
.set(User::getEnabled, enable)
.set(User::getDeptId, deptId)
.set(User::getPhone, phone)
.set(StringUtils.hasText(remark), User::getRemark, remark);
}
}

View File

@ -0,0 +1,39 @@
package com.zsc.edu.bill.modules.system.entity;
import org.springframework.security.core.GrantedAuthority;
/**
* 操作权限
*
* @author harry yao
*/
public enum Authority implements GrantedAuthority {
/**
* 部门管理
*/
DEPT_QUERY,
DEPT_CREATE,
DEPT_UPDATE,
DEPT_DELETE,
/**
* 角色管理
*/
ROLE_CREATE,
ROLE_QUERY,
ROLE_UPDATE,
/**
* 用户管理
*/
USER_QUERY,
USER_CREATE,
USER_UPDATE,
USER_DELETE;
@Override
public String getAuthority() {
return name();
}
}

View File

@ -0,0 +1,59 @@
package com.zsc.edu.bill.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 = "update_time", fill = FieldFill.INSERT_UPDATE)
public LocalDateTime updateTime;
@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();
}
}

View File

@ -0,0 +1,50 @@
package com.zsc.edu.bill.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);
}

View File

@ -0,0 +1,39 @@
package com.zsc.edu.bill.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;
}

View File

@ -0,0 +1,22 @@
package com.zsc.edu.bill.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
/**
* sys_role_authorities
* @author
*/
@AllArgsConstructor
@Data
@TableName("sys_role_authorities")
public class RoleAuthority implements Serializable {
private Long roleId;
private String authority;
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,75 @@
package com.zsc.edu.bill.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import java.util.Set;
/**
* 用户
*
* @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 enabled = true;
/**
* 所属部门ID
*/
public Long deptId;
/**
* 角色ID
*/
public Long roleId;
/**
* 所属部门
*/
@TableField(exist = false)
public Dept dept;
/**
* 拥有的角色
*/
@TableField(exist = false)
public Role role;
}

View File

@ -0,0 +1,26 @@
package com.zsc.edu.bill.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* sys_users_roles
* @author
*/
@Data
@TableName("sys_users_roles")
public class UserRole implements Serializable {
/**
* 用户ID
*/
private Long userId;
/**
* 角色ID
*/
private Long roleId;
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,15 @@
package com.zsc.edu.bill.modules.system.mapper;
import com.zsc.edu.bill.common.mapstruct.BaseMapper;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.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> {
}

View File

@ -0,0 +1,14 @@
package com.zsc.edu.bill.modules.system.mapper;
import com.zsc.edu.bill.common.mapstruct.BaseMapper;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.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> {
}

View File

@ -0,0 +1,14 @@
package com.zsc.edu.bill.modules.system.mapper;
import com.zsc.edu.bill.common.mapstruct.BaseMapper;
import com.zsc.edu.bill.modules.system.dto.UserCreateDto;
import com.zsc.edu.bill.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> {
}

View File

@ -0,0 +1,37 @@
package com.zsc.edu.bill.modules.system.query;
import com.zsc.edu.bill.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.eq(StringUtils.hasText(this.name), Dept::getName, this.name);
return queryWrapper;
}
}

View File

@ -0,0 +1,62 @@
package com.zsc.edu.bill.modules.system.query;
import com.zsc.edu.bill.modules.system.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;
import java.util.Objects;
import java.util.Set;
/**
* 用户Query
*
* @author harry yao
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserQuery {
/**
* 用户名
*/
public String username;
/**
* 手机号码
*/
public String phone;
/**
* 电子邮件
*/
public String email;
/**
* 启用状态
*/
public Boolean enable;
/**
* 角色集合
*/
public Set<Long> roleIds;
/**
* 部门集合
*/
public Set<Long> deptIds;
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::getEnabled, this.enable);
return queryWrapper;
}
}

View File

@ -0,0 +1,16 @@
package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.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> {
}

View File

@ -0,0 +1,7 @@
package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface RoleAuthoritiesReposity extends BaseMapper<RoleAuthority> {
}

View File

@ -0,0 +1,15 @@
package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 角色表 Mapper 接口
* </p>
*
* @author Yao
* @since 2023-04-06
*/
public interface RoleRepository extends BaseMapper<Role> {
}

View File

@ -0,0 +1,29 @@
package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.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.bill.modules.system.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Yao
* @since 2023-04-06
*/
public interface UserRepository extends BaseMapper<User> {
@Select("select u.*, d.name as deptName, GROUP_CONCAT(r.name SEPARATOR ', ') as roleNames from sys_user as u " +
"left join sys_dept as d on u.dept_id=d.id " +
"left join sys_users_roles as sur on u.id = sur.user_id " +
"join sys_role r on r.id = sur.role_id ${ew.customSqlSegment}")
Page<UserVo> page(Page pageDTO, @Param("ew") QueryWrapper<User> wrapper);
@Select("select u.* from sys_user u where u.username = ${username}")
User findByUsername(String username);
}

View File

@ -0,0 +1,7 @@
package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.UserRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserRolesReposity extends BaseMapper<UserRole> {
}

View File

@ -0,0 +1,38 @@
package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.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
* @return
*/
Dept create(DeptDto dto);
/**
* 更新部门
* @param dto
* @param id
* @return
*/
Boolean edit(DeptDto dto, Long id);
/**
* 生成部门树结构
* @param id
* @return
*/
// Dept listTree(Long id);
}

View File

@ -0,0 +1,16 @@
package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.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);
}

View File

@ -0,0 +1,27 @@
package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 角色表 服务类
* </p>
*
* @author Yao
* @since 2023-04-06
*/
public interface RoleService extends IService<Role> {
Role create(RoleDto roleDto);
Boolean edit(RoleDto roleDto, Long id);
Role detail(Long id);
Boolean toggle(Long id);
Boolean delete(Long id);
}

View File

@ -0,0 +1,41 @@
package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.dto.UserCreateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.bill.modules.system.dto.UserUpdateDto;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.query.UserQuery;
import com.zsc.edu.bill.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);
Page<UserVo> page(UserQuery query, PageDTO pageDTO);
}

View File

@ -0,0 +1,59 @@
package com.zsc.edu.bill.modules.system.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.bill.exception.ConstraintException;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.mapper.DeptMapper;
import com.zsc.edu.bill.modules.system.repo.DeptRepository;
import com.zsc.edu.bill.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 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;
// }
}

View File

@ -0,0 +1,16 @@
package com.zsc.edu.bill.modules.system.service.impl;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.zsc.edu.bill.modules.system.repo.RoleAuthoritiesReposity;
import com.zsc.edu.bill.modules.system.service.RoleAuthService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthoritiesReposity, RoleAuthority> implements RoleAuthService {
@Override
public boolean removeByRoleId(Long roleId) {
return remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, roleId));
}
}

View File

@ -0,0 +1,97 @@
package com.zsc.edu.bill.modules.system.service.impl;
import com.zsc.edu.bill.exception.ConstraintException;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.zsc.edu.bill.modules.system.entity.UserRole;
import com.zsc.edu.bill.modules.system.mapper.RoleMapper;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesReposity;
import com.zsc.edu.bill.modules.system.service.RoleAuthService;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
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 UserRolesReposity urRepo;
private final RoleAuthService roleAuthService;
@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 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 Role detail(Long id) {
Role role = getById(id);
List<RoleAuthority> roleAuthorities = roleAuthService.list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, role.id));
role.authorities = roleAuthorities.stream()
.map(roleAuthority -> Authority.valueOf(roleAuthority.getAuthority()))
.collect(Collectors.toSet());
return role;
}
private boolean saveRoleAuths(Long roleId, Set<Authority> authorities) {
// 保存角色关联权限
List<RoleAuthority> roleAuthorities = authorities.stream().map(authority -> new RoleAuthority(roleId, authority.getAuthority())).collect(Collectors.toList());
return roleAuthService.saveBatch(roleAuthorities);
}
}

View File

@ -0,0 +1,116 @@
package com.zsc.edu.bill.modules.system.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.bill.exception.ConstraintException;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.dto.UserCreateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.bill.modules.system.dto.UserUpdateDto;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.query.UserQuery;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import com.zsc.edu.bill.modules.system.service.UserService;
import com.zsc.edu.bill.modules.system.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 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;
@Override
public Boolean create(UserCreateDto dto) {
User user = new User();
BeanUtils.copyProperties(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.setEnabled(!user.getEnabled());
return updateById(user);
}
@Override
public Page<UserVo> page(UserQuery query, PageDTO pageDTO) {
//2.构造连表查询的动态SQL代码
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like(!query.getUsername().isBlank(), "u.username", query.getUsername())
.in(query.deptIds != null && !query.deptIds.isEmpty(), "d.id", query.getDeptIds())
.in(query.roleIds != null && !query.roleIds.isEmpty(), "r.id", query.getRoleIds());
//3.Mapper层连表查询SQL语句并把动态查询的代码段传递给Mapper接
return this.baseMapper.page(pageDTO, wrapper);
}
@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;
boolean existsByEmail = count(new LambdaQueryWrapper<User>().ne(User::getId, userDetails.getId()).eq(User::getEmail, dto.getEmail())) > 0;
if (existsByPhone) {
throw new ConstraintException("phone", dto.phone, "手机号已存在");
}
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);
}
}

View File

@ -0,0 +1,15 @@
package com.zsc.edu.bill.modules.system.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class UserVo {
String username;
String phone;
String email;
Boolean enabled;
LocalDateTime createTime;
LocalDateTime updateTime;
}

View File

@ -0,0 +1,15 @@
server:
port: 8080
mybatis-plus:
type-aliases-package: com.zsc.edu.bill.modules.*.entity
mapper-locations: classpath:mappers/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
spring:
datasource:
url: jdbc:mysql://localhost:3306/study?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&characterEncoding=utf8&serverTimezone=Hongkong
username: root
password: 123123
driver-class-name: com.mysql.cj.jdbc.Driver

View File

@ -0,0 +1,15 @@
server:
port: 8080
mybatis-plus:
type-aliases-package: cn.edu.zsc.study.entity
mapper-locations: classpath:mappers/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
spring:
datasource:
url: jdbc:mysql://localhost:3306/study?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&characterEncoding=utf8&serverTimezone=Hongkong
username: root
password: 123123
driver-class-name: com.mysql.cj.jdbc.Driver

View File

@ -0,0 +1,6 @@
spring:
profiles:
active: dev
docker:
compose:
enabled: false

View File

@ -0,0 +1,117 @@
/*
Navicat Premium Data Transfer
Source Server : localhost-root
Source Server Type : MySQL
Source Server Version : 50642
Source Host : localhost:3306
Source Schema : study
Target Server Type : MySQL
Target Server Version : 50642
File Encoding : 65001
Date: 14/04/2023 17:33:03
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_dept
-- ----------------------------
DROP TABLE IF EXISTS `sys_dept`;
CREATE TABLE `sys_dept` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`pid` bigint(20) NULL DEFAULT NULL COMMENT '上级部门',
`sub_count` int(5) NULL DEFAULT 0 COMMENT '子部门数目',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '名称',
`dept_sort` int(5) NULL DEFAULT 999 COMMENT '排序',
`enabled` bit(1) NULL DEFAULT NULL COMMENT '状态',
`create_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新者',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建日期',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `inx_pid`(`pid`) USING BTREE,
INDEX `inx_enabled`(`enabled`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 172 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '部门' ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '名称',
`level` int(255) NULL DEFAULT NULL COMMENT '角色级别',
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
`data_scope` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '数据权限',
`create_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新者',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建日期',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
`enabled` bit(1) NULL DEFAULT NULL COMMENT '状态',
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uniq_name`(`name`) USING BTREE,
INDEX `role_name_index`(`name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '角色表' ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for sys_role_authorities
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_authorities`;
CREATE TABLE `sys_role_authorities` (
`role_id` bigint(20) NOT NULL,
`authority` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
INDEX `FKbyfnfkpgrf4jmo3nf97arsphd`(`role_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for sys_roles_depts
-- ----------------------------
DROP TABLE IF EXISTS `sys_roles_depts`;
CREATE TABLE `sys_roles_depts` (
`role_id` bigint(20) NOT NULL,
`dept_id` bigint(20) NOT NULL,
PRIMARY KEY (`role_id`, `dept_id`) USING BTREE,
INDEX `FK7qg6itn5ajdoa9h9o78v9ksur`(`dept_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '角色部门关联' ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`dept_id` bigint(20) NULL DEFAULT NULL COMMENT '部门id',
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号码',
`email` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电子邮箱',
`nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称',
`gender` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别',
`is_admin` bit(1) NULL DEFAULT b'0' COMMENT '是否为admin账号',
`create_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新者',
`create_time` datetime(0) NULL DEFAULT NULL,
`update_time` datetime(0) NULL DEFAULT NULL,
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`enabled` bit(1) NULL DEFAULT NULL COMMENT '状态',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for sys_users_roles
-- ----------------------------
DROP TABLE IF EXISTS `sys_users_roles`;
CREATE TABLE `sys_users_roles` (
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
PRIMARY KEY (`user_id`, `role_id`) USING BTREE,
INDEX `FKq4eq273l04bpu4efj0jd0jb98`(`role_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户角色关联' ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.zsc.study.repository.DeptRepository">
</mapper>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.zsc.study.repository.RoleAuthoritiesReposity">
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.zsc.study.repository.RoleRepository">
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.zsc.study.repository.UserRepository">
</mapper>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.zsc.study.repository.UserRolesReposity">
</mapper>

View File

@ -0,0 +1,94 @@
package com.zsc.edu.bill;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.bill.domain.DeptBuilder;
import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.domain.UserBuilder;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.repo.DeptRepository;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.zsc.edu.bill.modules.system.service.UserService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Set;
/**
* @author pengzheng
*/
//@ActiveProfiles("test")
@SpringBootTest
abstract public class BaseServiceTest {
protected static UserDetailsImpl userDetails;
protected static User user1;
protected static User user2;
private static boolean dataInit;
private static UserRepository userRepoStatic;
private static DeptRepository deptRepoStatic;
private static RoleRepository roleRepoStatic;
private static RoleService roleServiceStatic;
@Autowired
private UserService service;
@Autowired
private UserRepository userRepo;
@Autowired
private DeptRepository deptRepo;
@Autowired
private RoleRepository roleRepo;
@Autowired
private RoleService roleService;
@Autowired
private PasswordEncoder passwordEncoder;
@AfterAll
static void afterAll() {
userRepoStatic.delete(new QueryWrapper<>());
roleRepoStatic.delete(new QueryWrapper<>());
deptRepoStatic.delete(new QueryWrapper<>());
dataInit = false;
}
@BeforeEach
public void baseSetUp() {
if (!dataInit) {
Dept dept1 = DeptBuilder.aDept().name("神湾分局").build();
deptRepo.insert(dept1);
Role role1 = RoleBuilder.aRole().name("超级管理员").build();
roleRepo.insert(role1);
user1 = UserBuilder.anUser()
.username("admin")
.email("123@qq.com")
.phone("13412334452")
.dept(dept1)
.role(role1)
.password(passwordEncoder.encode("admin"))
.build();
userRepo.insert(user1);
user2 = UserBuilder.anUser()
.username("13412334452")
.email("13412334452@zsc.edu.cn")
.phone("13412334452")
.password(passwordEncoder.encode("user1"))
.build();
userRepo.insert(user2);
userDetails = UserDetailsImpl.from(user1);
dataInit = true;
deptRepoStatic = deptRepo;
roleRepoStatic = roleRepo;
userRepoStatic = userRepo;
roleServiceStatic = roleService;
}
}
}

View File

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

View File

@ -0,0 +1,63 @@
package com.zsc.edu.bill;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.bill.domain.DeptBuilder;
import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.domain.UserBuilder;
import com.zsc.edu.bill.framework.security.CustomAccessDeniedHandler;
import com.zsc.edu.bill.framework.security.CustomAuthenticationFailureHandler;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.mapper.RoleMapper;
import com.zsc.edu.bill.modules.system.mapper.UserMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author pengzheng
*/
@ExtendWith(SpringExtension.class)
//@AutoConfigureRestDocs
//@ActiveProfiles("test")
abstract public class MockMvcConfigBase {
protected static UserDetailsImpl userDetails;
protected static User user;
@MockBean
protected DataSource dataSource;
@MockBean
protected SessionRegistry sessionRegistry;
@MockBean
protected UserMapper userMapper;
@MockBean
protected RoleMapper roleMapper;
@MockBean
protected CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@MockBean
protected CustomAccessDeniedHandler customAccessDeniedHandler;
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@BeforeAll
public static void setup() {
Dept dept = DeptBuilder.aDept().name("Platform").build();
Role role = RoleBuilder.aRole().authorities(new HashSet<>(Arrays.asList(Authority.values()))).build();
user = UserBuilder.anUser().username("admin").dept(dept).role(role).build();
userDetails = UserDetailsImpl.from(user);
}
}

View File

@ -0,0 +1,22 @@
package com.zsc.edu.bill.domain;
import java.time.LocalDateTime;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
/**
* @author pengzheng
*/
public class BaseEntityBuilder {
public Long id = -1L;
public String remark;
public LocalDateTime createAt;
public LocalDateTime updateAt;
public BaseEntityBuilder() {
remark = randomAlphabetic(5);
createAt = LocalDateTime.now();
updateAt = LocalDateTime.now();
}
}

View File

@ -0,0 +1,51 @@
package com.zsc.edu.bill.domain;
import com.zsc.edu.bill.modules.system.entity.Dept;
import java.util.HashSet;
public class DeptBuilder extends BaseEntityBuilder {
public String name;
public Dept parent;
public Long pid;
public HashSet<Dept> children;
public static DeptBuilder aDept(){
return new DeptBuilder();
}
public DeptBuilder name(String name){
this.name = name;
return this;
}
public DeptBuilder parent(Dept parent) {
this.parent = parent;
return this;
}
public DeptBuilder pid(Long pid) {
this.pid = pid;
return this;
}
public DeptBuilder children(HashSet<Dept> children) {
this.children = children;
return this;
}
public Dept build(){
Dept dept = new Dept();
dept.setName(name);
dept.setPid(pid);
dept.setChildren(children);
return dept;
}
}

View File

@ -0,0 +1,54 @@
package com.zsc.edu.bill.domain;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Role;
import java.util.HashSet;
import java.util.Set;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
/**
* @author pengzheng
*/
public final class RoleBuilder extends BaseEntityBuilder {
public String name;
public boolean enable;
public Set<Authority> authorities;
private RoleBuilder() {
this.name = randomAlphabetic(5);
this.enable = true;
this.authorities = new HashSet<>();
}
public static RoleBuilder aRole() {
return new RoleBuilder();
}
public RoleBuilder name(String name) {
this.name = name;
return this;
}
public RoleBuilder enable(boolean enable) {
this.enable = enable;
return this;
}
public RoleBuilder authorities(Set<Authority> authorities) {
this.authorities = authorities;
return this;
}
public Role build() {
Role role = new Role();
role.setRemark(remark);
role.setCreateTime(createAt);
role.setUpdateTime(updateAt);
role.setName(name);
role.setEnabled(enable);
role.setAuthorities(authorities);
return role;
}
}

View File

@ -0,0 +1,86 @@
package com.zsc.edu.bill.domain;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.User;
import java.util.HashSet;
import java.util.Set;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
/**
* @author pengzheng
*/
public final class UserBuilder extends BaseEntityBuilder {
public String username;
public String password;
public String phone;
public String email;
public boolean enable;
public Dept dept;
public Role role;
private UserBuilder() {
this.username = randomAlphabetic(5);
this.password = randomAlphabetic(5);
this.phone = "139" + randomAlphanumeric(8);
this.email = randomAlphanumeric(8) + "@" + randomAlphanumeric(6) + ".com";
this.enable = true;
}
public static UserBuilder anUser() {
return new UserBuilder();
}
public UserBuilder username(String username) {
this.username = username;
return this;
}
public UserBuilder password(String password) {
this.password = password;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder email(String email) {
this.email = email;
return this;
}
public UserBuilder enable(boolean enable) {
this.enable = enable;
return this;
}
public UserBuilder dept(Dept dept) {
this.dept = dept;
return this;
}
public UserBuilder role(Role role) {
this.role = role;
return this;
}
public User build() {
User user = new User();
user.setRemark(remark);
user.setCreateTime(createAt);
user.setUpdateTime(updateAt);
user.setUsername(username);
user.setPassword(password);
user.setPhone(phone);
user.setEmail(email);
user.setEnabled(enable);
user.setDept(dept);
user.setRole(role);
return user;
}
}

View File

@ -0,0 +1,127 @@
package com.zsc.edu.bill.rest;
import com.zsc.edu.bill.MockMvcConfigBase;
import com.zsc.edu.bill.domain.DeptBuilder;
import com.zsc.edu.bill.modules.system.controller.DeptController;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.mapper.DeptMapper;
import com.zsc.edu.bill.modules.system.service.DeptService;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Spy;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(DeptController.class)
public class DeptControllerTest extends MockMvcConfigBase {
@Spy
private static Dept dept1;
private static Dept dept2;
@MockBean
protected DeptMapper deptMapper;
@MockBean
private DeptService service;
@BeforeAll
static void beforeAll() {
dept1 = DeptBuilder.aDept().name("测试部门1").build();
dept1.setId(1L);
dept2 = DeptBuilder.aDept().name("测试部门2").pid(dept1.id).build();
}
@Test
void create() throws Exception{
DeptDto dto = new DeptDto();
dto.name = dept1.getName();
when(service.create(any())).thenReturn(dept1);
mockMvc.perform(post("/api/rest/dept")
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
).andExpect(status().isOk()).andDo(print());
verify(service).create(any());
}
@Test
void list() throws Exception {
List<Dept> depts = Lists.newArrayList(dept1, dept2);
when(service.list()).thenReturn(depts);
mockMvc.perform(get("/api/rest/dept").with(user(userDetails)))
.andExpect(status().isOk())
.andDo(print());
verify(service).list();
}
@Test
void update() throws Exception {
DeptDto dto = new DeptDto();
dto.name = dept1.getName();
when(service.edit(any(), any())).thenReturn(true);
mockMvc.perform(patch("/api/rest/dept/1")
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
)
.andExpect(status().isOk()).andDo(print());
verify(service).edit(any(), any());
}
//
// @Test
// void remove() throws Exception {
// when(service.deleteById(anyLong())).thenReturn(lampGroup1);
// mockMvc.perform(delete("/api/rest/lamp-group/{id}", lampGroup1.id)
// .with(csrf().asHeader())
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/delete"));
// verify(service).deleteById(anyLong());
// }
//
// @Test
// void detail() throws Exception {
// when(service.detail(anyLong())).thenReturn(lampGroup1);
// mockMvc.perform(get("/api/rest/lamp-group/{id}", lampGroup1.id)
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/detail"));
// verify(service).detail(anyLong());
// }
//
// @Test
// void batchDelete() throws Exception {
// Long[] ids = new Long[]{1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l, 10l, 11l, 12l};
// when(service.batchDelete(any())).thenReturn(ids);
// mockMvc.perform(post("/api/rest/lamp-group/batchRemove")
// .contentType(MediaType.APPLICATION_JSON)
// .content(objectMapper.writeValueAsString(ids))
// .with(csrf().asHeader())
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/batchRemove"));
// verify(service).batchDelete(any());
// }
}

View File

@ -0,0 +1,122 @@
package com.zsc.edu.bill.rest;
import com.zsc.edu.bill.MockMvcConfigBase;
import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.modules.system.controller.RoleController;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.service.RoleService;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(RoleController.class)
public class RoleControllerTest extends MockMvcConfigBase {
private static Role Role1;
private static Role Role2;
@MockBean
private RoleService service;
@BeforeAll
static void beforeAll() {
Role1 = RoleBuilder.aRole().name("管理员").build();
Role2 = RoleBuilder.aRole().name("普通用户").build();
}
@Test
void create() throws Exception{
RoleDto dto = new RoleDto();
dto.name = Role1.getName();
when(service.save(any())).thenReturn(true);
mockMvc.perform(post("/api/rest/role")
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
).andExpect(status().isOk()).andDo(print());
verify(service).save(any());
}
@Test
void list() throws Exception {
List<Role> Roles = Lists.newArrayList(Role1, Role2);
when(service.list()).thenReturn(Roles);
mockMvc.perform(get("/api/rest/Role").with(user(userDetails)))
.andExpect(status().isOk())
.andDo(print());
verify(service).list();
}
@Test
void update() throws Exception {
RoleDto dto = new RoleDto();
dto.name = Role1.getName();
when(service.update(any(), any())).thenReturn(true);
mockMvc.perform(patch("/api/rest/Role/{id}", Role1.id)
.with(csrf().asHeader())
.with(user(userDetails))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto))
)
.andExpect(status().isOk()).andDo(print());
verify(service).update(any(), any());
}
//
// @Test
// void remove() throws Exception {
// when(service.deleteById(anyLong())).thenReturn(lampGroup1);
// mockMvc.perform(delete("/api/rest/lamp-group/{id}", lampGroup1.id)
// .with(csrf().asHeader())
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/delete"));
// verify(service).deleteById(anyLong());
// }
//
// @Test
// void detail() throws Exception {
// when(service.detail(anyLong())).thenReturn(lampGroup1);
// mockMvc.perform(get("/api/rest/lamp-group/{id}", lampGroup1.id)
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/detail"));
// verify(service).detail(anyLong());
// }
//
// @Test
// void batchDelete() throws Exception {
// Long[] ids = new Long[]{1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l, 10l, 11l, 12l};
// when(service.batchDelete(any())).thenReturn(ids);
// mockMvc.perform(post("/api/rest/lamp-group/batchRemove")
// .contentType(MediaType.APPLICATION_JSON)
// .content(objectMapper.writeValueAsString(ids))
// .with(csrf().asHeader())
// .with(user(userDetails))
// )
// .andExpect(status().isOk())
// .andDo(document("lamp-group/batchRemove"));
// verify(service).batchDelete(any());
// }
}

View File

@ -0,0 +1,139 @@
package com.zsc.edu.bill.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.bill.domain.DeptBuilder;
import com.zsc.edu.bill.exception.ConstraintException;
import com.zsc.edu.bill.modules.system.dto.DeptDto;
import com.zsc.edu.bill.modules.system.entity.Dept;
import com.zsc.edu.bill.modules.system.repo.DeptRepository;
import com.zsc.edu.bill.modules.system.service.DeptService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DuplicateKeyException;
import jakarta.annotation.Resource;
import java.util.HashSet;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author pengzheng
*/
//@ActiveProfiles("test")
@SpringBootTest
class DeptServiceTest {
@Autowired
private DeptService service;
@Resource
private DeptRepository repo;
private Dept dept1;
private Dept dept2;
private Dept dept3;
private Dept dept4;
@BeforeEach
void setUp() {
dept1 = DeptBuilder.aDept().name("测试部门1").build();
repo.insert(dept1);
dept2 = DeptBuilder.aDept().name("测试部门2").pid(dept1.id).build();
repo.insert(dept2);
dept3 = DeptBuilder.aDept().name("测试部门3").pid(dept1.id).build();
repo.insert(dept3);
dept4 = DeptBuilder.aDept().name("测试部门4").pid(dept3.id).build();
repo.insert(dept4);
}
@AfterEach
void tearDown() {
repo.delete(new QueryWrapper<>());
}
@Test
void list() {
LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
assertEquals(4, service.list(queryWrapper.like(Dept::getName, "测试部门")).size());
assertEquals(1, service.list(queryWrapper.eq(Dept::getName, dept1.getName())).size());
assertEquals(4, service.list().size());
}
// @Test
// void listTree() {
// Dept result = service.listTree(dept1.id);
// int count = result.children.size();
// assertEquals(2, count);
// }
@Test
void createAdmin() {
Dept dept = new Dept();
dept.setName("东菱经销商3");
dept.setRemark("remark...");
dept.setPid(dept1.id);
service.save(dept);
assertEquals(5, service.list().size());
// 不能创建其他已存在的同名同代码部门
assertThrows(DuplicateKeyException.class, () -> service.save(dept1));
}
@Test
void create() {
// Dept dept = new Dept();
// dept.setName("东菱经销商5");
// dept.setRemark("remark...");
// dept.setPid(dept1.id);
DeptDto dto = new DeptDto();
dto.setName("东菱经销商5");
dto.setRemark("remark...");
dto.setPid(dept1.id);
DeptDto dto2 = new DeptDto();
dto2.setName(dept2.getName());
dto2.setRemark("remark...");
dto2.setPid(dept1.id);
Dept dept = service.create(dto);
assertNotNull(dept.getId());
assertEquals(5, service.list().size());
// 不能创建其他已存在的同名同代码部门
assertThrows(ConstraintException.class, () -> service.create(dto2));
}
@Test
void updateAdmin() {
DeptDto dto = new DeptDto();
dto.setName("东菱经销商5");
dto.setRemark("remark...");
assertTrue(service.edit(dto, dept2.id));
Dept tmp = service.getOne(new LambdaQueryWrapper<Dept>().eq(Dept::getName, dto.getName()));
assertEquals(tmp.getName(), dto.getName());
assertEquals(tmp.getId(), dept2.id);
// 不能改为其他已存在的同名同代码部门
assertThrows(ConstraintException.class,
() -> service.edit(new DeptDto(dept3.getName(), "remark",null), dept2.id));
}
// @Test
// void tree() {
// Dept result = service.listTree(dept3.id);
// HashSet<Long> deptPath = DeptTreeUtil.getDeptPath(result);
// System.out.println(deptPath);
// assertEquals(2, deptPath.size());
// }
// @Test
// void findTreeChild() {
// Dept result = service.listTree(dept1.id);
// Dept childNode = DeptTreeUtil.getChildNode(result.children, dept2.id);
// System.out.println(childNode.id);
// assertEquals(dept2.id, childNode.id);
// }
}

View File

@ -0,0 +1,90 @@
package com.zsc.edu.bill.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.service.RoleService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author harry yao
*/
//@ActiveProfiles("test")
@SpringBootTest
class RoleServiceTest {
@Autowired
private RoleService service;
@Resource
private RoleRepository repo;
private Role role1;
private Role role2;
private Role Role3;
private Role Role4;
@BeforeEach
void setUp() {
role1 = RoleBuilder.aRole().name("超级管理员").build();
repo.insert(role1);
role2 = RoleBuilder.aRole().name("普通用户").build();
repo.insert(role2);
}
@AfterEach
void tearDown() {
repo.delete(new QueryWrapper<>());
}
@Test
void list() {
assertEquals(2, service.list().size());
assertEquals(1, service.list(new LambdaQueryWrapper<Role>().like(Role::getName, "普通用户")).size());
assertEquals(1, service.list(new LambdaQueryWrapper<Role>().eq(Role::getName, role1.getName())).size());
}
@Test
void create() {
// Role Role = new Role();
// Role.setName("东菱经销商5");
// Role.setRemark("remark...");
// Role.setPid(Role1.id);
RoleDto dto = new RoleDto();
dto.setName("东菱经销商5");
dto.setRemark("remark...");
dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
Role Role = service.create(dto);
assertNotNull(Role.getId());
assertEquals(3, service.list().size());
// 不能创建其他已存在的同名同代码部门
// assertThrows(ConstraintException.class, () -> service.create(dto2));
}
@Test
void update() {
RoleDto dto = new RoleDto();
dto.setName("超级管理员2");
dto.setRemark("remark...");
dto.setAuthorities(Set.of(Authority.ROLE_UPDATE, Authority.DEPT_UPDATE));
assertTrue(service.edit(dto, role2.id));
}
}