diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5f0536e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..4d2047e --- /dev/null +++ b/compose.yaml @@ -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' diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..66df285 --- /dev/null +++ b/mvnw @@ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/mvnw.cmd @@ -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% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..b5db99d --- /dev/null +++ b/pom.xml @@ -0,0 +1,144 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.1 + + + com.zsc.edu + bill + 0.0.1-SNAPSHOT + bill-backend + bill-backend + + 17 + 1.5.5.Final + 3.5.5 + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-docker-compose + runtime + true + + + com.mysql + mysql-connector-j + 8.2.0 + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.security + spring-security-test + test + + + org.mapstruct + mapstruct + ${mapstruct.version} + provided + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + provided + + + com.baomidou + mybatis-plus-spring-boot3-starter + ${mybatis-plus.version} + + + + org.apache.commons + commons-lang3 + + + + + + + org.asciidoctor + asciidoctor-maven-plugin + 2.2.1 + + + generate-docs + prepare-package + + process-asciidoc + + + html + book + + + + + + org.springframework.restdocs + spring-restdocs-asciidoctor + ${spring-restdocs.version} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/zsc/edu/bill/BillApplication.java b/src/main/java/com/zsc/edu/bill/BillApplication.java new file mode 100644 index 0000000..001ceb0 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/BillApplication.java @@ -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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/FirstTimeInitializer.java b/src/main/java/com/zsc/edu/bill/FirstTimeInitializer.java new file mode 100644 index 0000000..f4e9d55 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/FirstTimeInitializer.java @@ -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); + } + } +} diff --git a/src/main/java/com/zsc/edu/bill/common/enums/EnableState.java b/src/main/java/com/zsc/edu/bill/common/enums/EnableState.java new file mode 100644 index 0000000..0aeb5dd --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/common/enums/EnableState.java @@ -0,0 +1,19 @@ +package com.zsc.edu.bill.common.enums; + +import com.baomidou.mybatisplus.annotation.IEnum; + +public enum EnableState implements IEnum { + ENABLE(Boolean.TRUE), + DISAENABLE(Boolean.FALSE); + + private boolean value; + + EnableState(Boolean value) { + this.value = value; + } + + @Override + public Boolean getValue() { + return this.value; + } +} diff --git a/src/main/java/com/zsc/edu/bill/common/mapstruct/BaseMapper.java b/src/main/java/com/zsc/edu/bill/common/mapstruct/BaseMapper.java new file mode 100644 index 0000000..7bd483b --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/common/mapstruct/BaseMapper.java @@ -0,0 +1,10 @@ +package com.zsc.edu.bill.common.mapstruct; + +import java.util.List; + +public interface BaseMapper { + D toDto(E entity); + E toEntity(D dto); + List toDto(List entityList); + List toEntity(List dtoList); +} diff --git a/src/main/java/com/zsc/edu/bill/exception/ApiException.java b/src/main/java/com/zsc/edu/bill/exception/ApiException.java new file mode 100644 index 0000000..a1667af --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/ApiException.java @@ -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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/exception/ApiExceptionHandler.java b/src/main/java/com/zsc/edu/bill/exception/ApiExceptionHandler.java new file mode 100644 index 0000000..adaaf95 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/ApiExceptionHandler.java @@ -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 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 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 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 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 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 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 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 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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/exception/ConstraintException.java b/src/main/java/com/zsc/edu/bill/exception/ConstraintException.java new file mode 100644 index 0000000..86f7ff0 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/ConstraintException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/ExceptionResult.java b/src/main/java/com/zsc/edu/bill/exception/ExceptionResult.java new file mode 100644 index 0000000..39e8700 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/ExceptionResult.java @@ -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; + +} diff --git a/src/main/java/com/zsc/edu/bill/exception/JwtAuthenticationException.java b/src/main/java/com/zsc/edu/bill/exception/JwtAuthenticationException.java new file mode 100644 index 0000000..d0b71e8 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/JwtAuthenticationException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/NotExistException.java b/src/main/java/com/zsc/edu/bill/exception/NotExistException.java new file mode 100644 index 0000000..6e21abc --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/NotExistException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/OutlineException.java b/src/main/java/com/zsc/edu/bill/exception/OutlineException.java new file mode 100644 index 0000000..14f2e43 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/OutlineException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/StateException.java b/src/main/java/com/zsc/edu/bill/exception/StateException.java new file mode 100644 index 0000000..ee4a1be --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/StateException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/StorageException.java b/src/main/java/com/zsc/edu/bill/exception/StorageException.java new file mode 100644 index 0000000..b22546b --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/StorageException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/exception/UserHasNoIdentityException.java b/src/main/java/com/zsc/edu/bill/exception/UserHasNoIdentityException.java new file mode 100644 index 0000000..bac3a8a --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/UserHasNoIdentityException.java @@ -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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/exception/ValidateException.java b/src/main/java/com/zsc/edu/bill/exception/ValidateException.java new file mode 100644 index 0000000..d1c1328 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/exception/ValidateException.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/JsonExceptionUtil.java b/src/main/java/com/zsc/edu/bill/framework/JsonExceptionUtil.java new file mode 100644 index 0000000..03d54b4 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/JsonExceptionUtil.java @@ -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 jsonExceptionResult(HttpStatus code, String message, String path) { + Map exceptionMap = new LinkedHashMap<>(); + exceptionMap.put("timestamp", Calendar.getInstance().getTime()); + exceptionMap.put("message", message); + exceptionMap.put("path", path); + exceptionMap.put("code", code.value()); + return exceptionMap; + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/SpringBeanUtil.java b/src/main/java/com/zsc/edu/bill/framework/SpringBeanUtil.java new file mode 100644 index 0000000..4cf25bf --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/SpringBeanUtil.java @@ -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 getBean(Class 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; + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/WebMvcConfiguration.java b/src/main/java/com/zsc/edu/bill/framework/WebMvcConfiguration.java new file mode 100644 index 0000000..6d6830d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/WebMvcConfiguration.java @@ -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 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; + } + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/async/AsyncConfiguration.java b/src/main/java/com/zsc/edu/bill/framework/async/AsyncConfiguration.java new file mode 100644 index 0000000..97527f8 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/async/AsyncConfiguration.java @@ -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); + }; + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MyMetaObjectHandler.java b/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MyMetaObjectHandler.java new file mode 100644 index 0000000..2ba9c6f --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MyMetaObjectHandler.java @@ -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); + } + +} \ No newline at end of file diff --git a/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MybatisPlusConfig.java b/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MybatisPlusConfig.java new file mode 100644 index 0000000..0606b75 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/mybatisplus/MybatisPlusConfig.java @@ -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; + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/CustomAccessDeniedHandler.java b/src/main/java/com/zsc/edu/bill/framework/security/CustomAccessDeniedHandler.java new file mode 100644 index 0000000..a375f5d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/CustomAccessDeniedHandler.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationEntryPoint.java b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationEntryPoint.java new file mode 100644 index 0000000..25ee000 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationEntryPoint.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationFailureHandler.java b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000..529f140 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationFailureHandler.java @@ -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(); + } + +} + diff --git a/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationSuccessHandler.java b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationSuccessHandler.java new file mode 100644 index 0000000..ec9cc9f --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/CustomAuthenticationSuccessHandler.java @@ -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.登陆成功); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/CustomSessionInformationExpiredStrategy.java b/src/main/java/com/zsc/edu/bill/framework/security/CustomSessionInformationExpiredStrategy.java new file mode 100644 index 0000000..8be9beb --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/CustomSessionInformationExpiredStrategy.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/JpaUserDetailsServiceImpl.java b/src/main/java/com/zsc/edu/bill/framework/security/JpaUserDetailsServiceImpl.java new file mode 100644 index 0000000..bac18d7 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/JpaUserDetailsServiceImpl.java @@ -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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/JsonAuthenticationFilter.java b/src/main/java/com/zsc/edu/bill/framework/security/JsonAuthenticationFilter.java new file mode 100644 index 0000000..2f5976b --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/JsonAuthenticationFilter.java @@ -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); + } + + +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/SecurityBeanConfig.java b/src/main/java/com/zsc/edu/bill/framework/security/SecurityBeanConfig.java new file mode 100644 index 0000000..b4050ce --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/SecurityBeanConfig.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/SecurityUtil.java b/src/main/java/com/zsc/edu/bill/framework/security/SecurityUtil.java new file mode 100644 index 0000000..cb32314 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/SecurityUtil.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/SpringSecurityConfig.java b/src/main/java/com/zsc/edu/bill/framework/security/SpringSecurityConfig.java new file mode 100644 index 0000000..d545586 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/SpringSecurityConfig.java @@ -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(); + + } +} diff --git a/src/main/java/com/zsc/edu/bill/framework/security/UserDetailsImpl.java b/src/main/java/com/zsc/edu/bill/framework/security/UserDetailsImpl.java new file mode 100644 index 0000000..ba83852 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/framework/security/UserDetailsImpl.java @@ -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 authorities; + + public static UserDetailsImpl from(User user) { + Set authorities = user.role.authorities; + return new UserDetailsImpl( + user.id, + user.username, + user.password, + user.enabled, + user.dept, + user.role, + authorities + ); + } + + @Override + public Collection 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; + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/controller/DeptController.java b/src/main/java/com/zsc/edu/bill/modules/system/controller/DeptController.java new file mode 100644 index 0000000..65741ee --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/controller/DeptController.java @@ -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 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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/controller/RoleController.java b/src/main/java/com/zsc/edu/bill/modules/system/controller/RoleController.java new file mode 100644 index 0000000..546363d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/controller/RoleController.java @@ -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 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); + } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/controller/UserController.java b/src/main/java/com/zsc/edu/bill/modules/system/controller/UserController.java new file mode 100644 index 0000000..b822633 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/controller/UserController.java @@ -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 me(@AuthenticationPrincipal Object principal, CsrfToken csrfToken) { + Map 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 query(UserQuery query, PageDTO 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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/DeptDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/DeptDto.java new file mode 100644 index 0000000..f37fa80 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/DeptDto.java @@ -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 updateWrapper(Long id) { + LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); + return updateWrapper.eq(Dept::getId, id) + .set(Dept::getName, name) + .set(StringUtils.hasText(remark), Dept::getRemark, remark); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/RoleDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/RoleDto.java new file mode 100644 index 0000000..652aff6 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/RoleDto.java @@ -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 authorities; + + public LambdaUpdateWrapper updateWrapper(Long id) { + LambdaUpdateWrapper update = new LambdaUpdateWrapper<>(); + return update.eq(Role::getId, id) + .set(Role::getName, name) + .set(StringUtils.hasText(remark), Role::getRemark, remark); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/UserCreateDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserCreateDto.java new file mode 100644 index 0000000..7ab2fe3 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserCreateDto.java @@ -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 roleIds; + + /** + * 备注说明 + */ + public String remark; + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdateDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdateDto.java new file mode 100644 index 0000000..a0e72c9 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdateDto.java @@ -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; + + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdatePasswordDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdatePasswordDto.java new file mode 100644 index 0000000..a97e327 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserSelfUpdatePasswordDto.java @@ -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; + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/dto/UserUpdateDto.java b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserUpdateDto.java new file mode 100644 index 0000000..7ce912c --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/dto/UserUpdateDto.java @@ -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 roleIds; + + public String remark; + + public LambdaUpdateWrapper updateWrapper(Long id) { + LambdaUpdateWrapper 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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/Authority.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/Authority.java new file mode 100644 index 0000000..4ccbc90 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/Authority.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/BaseEntity.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/BaseEntity.java new file mode 100644 index 0000000..b5fcbe7 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/BaseEntity.java @@ -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(); + } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/Dept.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/Dept.java new file mode 100644 index 0000000..2981322 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/Dept.java @@ -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 children = new HashSet<>(0); + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/Role.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/Role.java new file mode 100644 index 0000000..08e8979 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/Role.java @@ -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 authorities; + +} + diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/RoleAuthority.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/RoleAuthority.java new file mode 100644 index 0000000..d9da9c2 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/RoleAuthority.java @@ -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; +} \ No newline at end of file diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/User.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/User.java new file mode 100644 index 0000000..ebb65d1 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/User.java @@ -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; + + +} + diff --git a/src/main/java/com/zsc/edu/bill/modules/system/entity/UserRole.java b/src/main/java/com/zsc/edu/bill/modules/system/entity/UserRole.java new file mode 100644 index 0000000..25453ee --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/entity/UserRole.java @@ -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; +} \ No newline at end of file diff --git a/src/main/java/com/zsc/edu/bill/modules/system/mapper/DeptMapper.java b/src/main/java/com/zsc/edu/bill/modules/system/mapper/DeptMapper.java new file mode 100644 index 0000000..14abdcf --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/mapper/DeptMapper.java @@ -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 { +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/mapper/RoleMapper.java b/src/main/java/com/zsc/edu/bill/modules/system/mapper/RoleMapper.java new file mode 100644 index 0000000..a9dcf12 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/mapper/RoleMapper.java @@ -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 { +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/mapper/UserMapper.java b/src/main/java/com/zsc/edu/bill/modules/system/mapper/UserMapper.java new file mode 100644 index 0000000..047a89d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/mapper/UserMapper.java @@ -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 { +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/query/DeptQuery.java b/src/main/java/com/zsc/edu/bill/modules/system/query/DeptQuery.java new file mode 100644 index 0000000..bbfa61d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/query/DeptQuery.java @@ -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 wrapper() { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(StringUtils.hasText(this.name), Dept::getName, this.name); + return queryWrapper; + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/query/UserQuery.java b/src/main/java/com/zsc/edu/bill/modules/system/query/UserQuery.java new file mode 100644 index 0000000..05b6cf6 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/query/UserQuery.java @@ -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 roleIds; + + /** + * 部门集合 + */ + public Set deptIds; + + public LambdaQueryWrapper wrapper() { + LambdaQueryWrapper 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; + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/repo/DeptRepository.java b/src/main/java/com/zsc/edu/bill/modules/system/repo/DeptRepository.java new file mode 100644 index 0000000..71e25c8 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/repo/DeptRepository.java @@ -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; + +/** + *

+ * 部门 Mapper 接口 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface DeptRepository extends BaseMapper { + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleAuthoritiesReposity.java b/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleAuthoritiesReposity.java new file mode 100644 index 0000000..e51df5d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleAuthoritiesReposity.java @@ -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 { +} \ No newline at end of file diff --git a/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleRepository.java b/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleRepository.java new file mode 100644 index 0000000..b2371ac --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/repo/RoleRepository.java @@ -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; + +/** + *

+ * 角色表 Mapper 接口 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface RoleRepository extends BaseMapper { +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRepository.java b/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRepository.java new file mode 100644 index 0000000..0b16033 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRepository.java @@ -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; + +/** + *

+ * Mapper 接口 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface UserRepository extends BaseMapper { + + @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 page(Page pageDTO, @Param("ew") QueryWrapper wrapper); + + @Select("select u.* from sys_user u where u.username = ${username}") + User findByUsername(String username); +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRolesReposity.java b/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRolesReposity.java new file mode 100644 index 0000000..445ce95 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/repo/UserRolesReposity.java @@ -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 { +} \ No newline at end of file diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/DeptService.java b/src/main/java/com/zsc/edu/bill/modules/system/service/DeptService.java new file mode 100644 index 0000000..330beb4 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/DeptService.java @@ -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; + +/** + *

+ * 部门 服务类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface DeptService extends IService { + + /** + * 创建部门 + * @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); +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/RoleAuthService.java b/src/main/java/com/zsc/edu/bill/modules/system/service/RoleAuthService.java new file mode 100644 index 0000000..743d63e --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/RoleAuthService.java @@ -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; + +/** + *

+ * 角色权限表 服务类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface RoleAuthService extends IService { + boolean removeByRoleId(Long id); +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/RoleService.java b/src/main/java/com/zsc/edu/bill/modules/system/service/RoleService.java new file mode 100644 index 0000000..1813b50 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/RoleService.java @@ -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; + +/** + *

+ * 角色表 服务类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface RoleService extends IService { + + Role create(RoleDto roleDto); + + Boolean edit(RoleDto roleDto, Long id); + + Role detail(Long id); + + Boolean toggle(Long id); + + Boolean delete(Long id); +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/UserService.java b/src/main/java/com/zsc/edu/bill/modules/system/service/UserService.java new file mode 100644 index 0000000..1538dc8 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/UserService.java @@ -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; + +/** + *

+ * 服务类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +public interface UserService extends IService { + + 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 page(UserQuery query, PageDTO pageDTO); +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/impl/DeptServiceImpl.java b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/DeptServiceImpl.java new file mode 100644 index 0000000..76150b5 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/DeptServiceImpl.java @@ -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; + +/** + *

+ * 部门 服务实现类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +@AllArgsConstructor +@Service +public class DeptServiceImpl extends ServiceImpl implements DeptService { + + private final DeptMapper mapper; + + @Override + public Dept create(DeptDto dto) { + boolean existsByName = count(new LambdaQueryWrapper().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().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 all = list(null); +// HashSet deptList = new HashSet<>(all); +// rootDept = DeptTreeUtil.initTree(deptList); +// if (deptId != null) { +// return rootDept.id.equals(deptId) ? rootDept : DeptTreeUtil.getChildNode(rootDept.children, deptId); +// } +// return rootDept; +// } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleAuthServiceImpl.java b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleAuthServiceImpl.java new file mode 100644 index 0000000..0f97633 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleAuthServiceImpl.java @@ -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 implements RoleAuthService { + @Override + public boolean removeByRoleId(Long roleId) { + return remove(new LambdaQueryWrapper().eq(RoleAuthority::getRoleId, roleId)); + } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleServiceImpl.java b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleServiceImpl.java new file mode 100644 index 0000000..9fb891d --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/RoleServiceImpl.java @@ -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; + +/** + *

+ * 角色表 服务实现类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +@AllArgsConstructor +@Service +public class RoleServiceImpl extends ServiceImpl 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().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().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().ne(Role::getId, id).eq(Role::getName, dto.getName())) > 0; + if (existsByName) { + throw new ConstraintException("name", dto.name, "同名角色已存在"); + } + roleAuthService.remove(new LambdaQueryWrapper().eq(RoleAuthority::getRoleId, id)); + saveRoleAuths(id, dto.getAuthorities()); + return update(dto.updateWrapper(id)); + } + + @Override + public Role detail(Long id) { + Role role = getById(id); + List roleAuthorities = roleAuthService.list(new LambdaQueryWrapper().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 authorities) { + // 保存角色关联权限 + List roleAuthorities = authorities.stream().map(authority -> new RoleAuthority(roleId, authority.getAuthority())).collect(Collectors.toList()); + return roleAuthService.saveBatch(roleAuthorities); + } +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/service/impl/UserServiceImpl.java b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..1d6501b --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/service/impl/UserServiceImpl.java @@ -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; + +/** + *

+ * 服务实现类 + *

+ * + * @author Yao + * @since 2023-04-06 + */ +@AllArgsConstructor +@Service +public class UserServiceImpl extends ServiceImpl 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().eq(User::getPhone, dto.getPhone())) > 0; + boolean existsByEmail = count(new LambdaQueryWrapper().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 page(UserQuery query, PageDTO pageDTO) { + //2.构造连表查询的动态SQL代码⽚段 + QueryWrapper 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().ne(User::getId, userDetails.getId()).eq(User::getPhone, dto.getPhone())) > 0; + boolean existsByEmail = count(new LambdaQueryWrapper().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); + } + +} diff --git a/src/main/java/com/zsc/edu/bill/modules/system/vo/UserVo.java b/src/main/java/com/zsc/edu/bill/modules/system/vo/UserVo.java new file mode 100644 index 0000000..2d1d051 --- /dev/null +++ b/src/main/java/com/zsc/edu/bill/modules/system/vo/UserVo.java @@ -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; +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..eb268b6 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -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 \ No newline at end of file diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..aee3324 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -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 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..6f638a7 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + profiles: + active: dev + docker: + compose: + enabled: false \ No newline at end of file diff --git a/src/main/resources/db/study.sql b/src/main/resources/db/study.sql new file mode 100644 index 0000000..6f6b6c9 --- /dev/null +++ b/src/main/resources/db/study.sql @@ -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; diff --git a/src/main/resources/mappers/DeptMapper.xml b/src/main/resources/mappers/DeptMapper.xml new file mode 100644 index 0000000..f1a3d6c --- /dev/null +++ b/src/main/resources/mappers/DeptMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/mappers/RoleAuthoritiesReposity.xml b/src/main/resources/mappers/RoleAuthoritiesReposity.xml new file mode 100644 index 0000000..600baa8 --- /dev/null +++ b/src/main/resources/mappers/RoleAuthoritiesReposity.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/main/resources/mappers/RoleMapper.xml b/src/main/resources/mappers/RoleMapper.xml new file mode 100644 index 0000000..de347da --- /dev/null +++ b/src/main/resources/mappers/RoleMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/mappers/UserMapper.xml b/src/main/resources/mappers/UserMapper.xml new file mode 100644 index 0000000..7e971f8 --- /dev/null +++ b/src/main/resources/mappers/UserMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/mappers/UserRolesReposity.xml b/src/main/resources/mappers/UserRolesReposity.xml new file mode 100644 index 0000000..e2c6d63 --- /dev/null +++ b/src/main/resources/mappers/UserRolesReposity.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/test/java/com/zsc/edu/bill/BaseServiceTest.java b/src/test/java/com/zsc/edu/bill/BaseServiceTest.java new file mode 100644 index 0000000..d3182cd --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/BaseServiceTest.java @@ -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; + } + } +} diff --git a/src/test/java/com/zsc/edu/bill/BillApplicationTests.java b/src/test/java/com/zsc/edu/bill/BillApplicationTests.java new file mode 100644 index 0000000..09bb497 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/BillApplicationTests.java @@ -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() { + } + +} diff --git a/src/test/java/com/zsc/edu/bill/MockMvcConfigBase.java b/src/test/java/com/zsc/edu/bill/MockMvcConfigBase.java new file mode 100644 index 0000000..d1b900c --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/MockMvcConfigBase.java @@ -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); + } +} diff --git a/src/test/java/com/zsc/edu/bill/domain/BaseEntityBuilder.java b/src/test/java/com/zsc/edu/bill/domain/BaseEntityBuilder.java new file mode 100644 index 0000000..80e3f34 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/domain/BaseEntityBuilder.java @@ -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(); + } + +} diff --git a/src/test/java/com/zsc/edu/bill/domain/DeptBuilder.java b/src/test/java/com/zsc/edu/bill/domain/DeptBuilder.java new file mode 100644 index 0000000..23b98f5 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/domain/DeptBuilder.java @@ -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 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 children) { + this.children = children; + return this; + } + + + public Dept build(){ + Dept dept = new Dept(); + dept.setName(name); + dept.setPid(pid); + dept.setChildren(children); + return dept; + } + + +} diff --git a/src/test/java/com/zsc/edu/bill/domain/RoleBuilder.java b/src/test/java/com/zsc/edu/bill/domain/RoleBuilder.java new file mode 100644 index 0000000..5bce43c --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/domain/RoleBuilder.java @@ -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 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 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; + } +} diff --git a/src/test/java/com/zsc/edu/bill/domain/UserBuilder.java b/src/test/java/com/zsc/edu/bill/domain/UserBuilder.java new file mode 100644 index 0000000..bfa25d8 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/domain/UserBuilder.java @@ -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; + } +} diff --git a/src/test/java/com/zsc/edu/bill/rest/DeptControllerTest.java b/src/test/java/com/zsc/edu/bill/rest/DeptControllerTest.java new file mode 100644 index 0000000..77d841e --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/rest/DeptControllerTest.java @@ -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 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()); +// } + +} diff --git a/src/test/java/com/zsc/edu/bill/rest/RoleControllerTest.java b/src/test/java/com/zsc/edu/bill/rest/RoleControllerTest.java new file mode 100644 index 0000000..0083641 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/rest/RoleControllerTest.java @@ -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 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()); +// } + +} diff --git a/src/test/java/com/zsc/edu/bill/service/DeptServiceTest.java b/src/test/java/com/zsc/edu/bill/service/DeptServiceTest.java new file mode 100644 index 0000000..f6e00c4 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/service/DeptServiceTest.java @@ -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 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().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 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); +// } + + +} diff --git a/src/test/java/com/zsc/edu/bill/service/RoleServiceTest.java b/src/test/java/com/zsc/edu/bill/service/RoleServiceTest.java new file mode 100644 index 0000000..987e647 --- /dev/null +++ b/src/test/java/com/zsc/edu/bill/service/RoleServiceTest.java @@ -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().like(Role::getName, "普通用户")).size()); + assertEquals(1, service.list(new LambdaQueryWrapper().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)); + } + + +}