成功运行

master
gyc 2024-04-20 12:30:37 +08:00
commit 2fc82ed0f9
140 changed files with 12236 additions and 0 deletions

31
.gitignore vendored 100644
View File

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

View File

@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed 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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored 100644

Binary file not shown.

View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

310
mvnw vendored 100644
View File

@ -0,0 +1,310 @@
#!/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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# 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 /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
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -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 "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; 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="`which 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
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# 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/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# 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.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
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 "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -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
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mvnw.cmd vendored 100644
View File

@ -0,0 +1,182 @@
@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 Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@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 "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\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 DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_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 DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_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('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@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 "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\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%
exit /B %ERROR_CODE%

224
pom.xml 100644
View File

@ -0,0 +1,224 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.eleadmin</groupId>
<artifactId>ele-admin-api</artifactId>
<version>1.5.0</version>
<name>ele-admin-api</name>
<description>EleAdminApi project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- spring-boot-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring-boot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-boot-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.3</version>
</dependency>
<!-- mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.7.11</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-extra</artifactId>
<version>5.7.11</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.7.11</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>5.7.11</version>
</dependency>
<!-- easy poi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<!-- tika, 用于FileServer获取content-type -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>2.1.0</version>
</dependency>
<!-- open office, 用于文档转pdf实现在线预览 -->
<dependency>
<groupId>com.github.livesense</groupId>
<artifactId>jodconverter-core</artifactId>
<version>1.0.5</version>
</dependency>
<!-- spring-boot-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 模板引擎, 用于邮件、代码生成等 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.6.1.RELEASE</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
</dependency>
<!-- 图形验证码 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*Mapper.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliYunMaven</id>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
</project>

View File

@ -0,0 +1,26 @@
package com.eleadmin;
import com.eleadmin.common.core.config.ConfigProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
* Created by EleAdmin on 2018-02-22 11:29:03
*/
@EnableAsync
@EnableTransactionManagement
@MapperScan("com.eleadmin.**.mapper")
@EnableConfigurationProperties(ConfigProperties.class)
@SpringBootApplication
public class EleAdminApplication {
public static void main(String[] args) {
SpringApplication.run(EleAdminApplication.class, args);
}
}

View File

@ -0,0 +1,93 @@
package com.eleadmin.common.core;
/**
*
* Created by EleAdmin on 2019-10-29 15:55
*/
public class Constants {
/**
*
*/
public static final int RESULT_OK_CODE = 0;
/**
*
*/
public static final int RESULT_ERROR_CODE = 1;
/**
*
*/
public static final String RESULT_OK_MSG = "操作成功";
/**
*
*/
public static final String RESULT_ERROR_MSG = "操作失败";
/**
*
*/
public static final int UNAUTHORIZED_CODE = 403;
/**
*
*/
public static final String UNAUTHORIZED_MSG = "没有访问权限";
/**
*
*/
public static final int UNAUTHENTICATED_CODE = 401;
/**
*
*/
public static final String UNAUTHENTICATED_MSG = "请先登录";
/**
*
*/
public static final int TOKEN_EXPIRED_CODE = 401;
/**
*
*/
public static final String TOKEN_EXPIRED_MSG = "登录已过期";
/**
* token
*/
public static final int BAD_CREDENTIALS_CODE = 401;
/**
* token
*/
public static final String BAD_CREDENTIALS_MSG = "请退出重新登录";
/**
*
*/
public static final String ORDER_ASC_VALUE = "asc";
/**
*
*/
public static final String ORDER_DESC_VALUE = "desc";
/**
* tokenheader
*/
public static final String TOKEN_HEADER_NAME = "Authorization";
/**
* token
*/
public static final String TOKEN_PARAM_NAME = "access_token";
/**
* token
*/
public static final String TOKEN_TYPE = "Bearer";
}

View File

@ -0,0 +1,41 @@
package com.eleadmin.common.core.annotation;
import java.lang.annotation.*;
/**
*
*
* @author EleAdmin
* @since 2020-03-21 17:03:08
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLog {
/**
*
*/
String value() default "";
/**
*
*/
String module() default "";
/**
*
*/
String comments() default "";
/**
*
*/
boolean param() default true;
/**
*
*/
boolean result() default true;
}

View File

@ -0,0 +1,21 @@
package com.eleadmin.common.core.annotation;
import java.lang.annotation.*;
/**
*
*
* @author EleAdmin
* @since 2021-09-01 20:48:16
*/
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationModule {
/**
*
*/
String value();
}

View File

@ -0,0 +1,22 @@
package com.eleadmin.common.core.annotation;
import java.lang.annotation.*;
/**
*
*
* @author EleAdmin
* @since 2021-09-01 20:48:16
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface QueryField {
// 字段名称
String value() default "";
// 查询方式
QueryType type() default QueryType.LIKE;
}

View File

@ -0,0 +1,42 @@
package com.eleadmin.common.core.annotation;
/**
*
*
* @author EleAdmin
* @since 2021-09-01 20:48:16
*/
public enum QueryType {
// 等于
EQ,
// 不等于
NE,
// 大于
GT,
// 大于等于
GE,
// 小于
LT,
// 小于等于
LE,
// 包含
LIKE,
// 不包含
NOT_LIKE,
// 结尾等于
LIKE_LEFT,
// 开头等于
LIKE_RIGHT,
// 为NULL
IS_NULL,
// 不为空
IS_NOT_NULL,
// IN
IN,
// NOT IN
NOT_IN,
// IN条件解析逗号分割
IN_STR,
// NOT IN条件解析逗号分割
NOT_IN_STR
}

View File

@ -0,0 +1,210 @@
package com.eleadmin.common.core.aspect;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.annotation.OperationModule;
import com.eleadmin.common.core.utils.JSONUtil;
import com.eleadmin.common.system.entity.OperationRecord;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.service.OperationRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
/**
*
*
* @author EleAdmin
* @since 2020-03-21 16:58:16:05
*/
@Aspect
@Component
public class OperationLogAspect {
@Resource
private OperationRecordService operationRecordService;
// 参数、返回结果、错误信息等最大保存长度
private static final int MAX_LENGTH = 1000;
// 用于记录请求耗时
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("@annotation(com.eleadmin.common.core.annotation.OperationLog)")
public void operationLog() {
}
@Before("operationLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
}
@AfterReturning(pointcut = "operationLog()", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Object result) {
saveLog(joinPoint, result, null);
}
@AfterThrowing(value = "operationLog()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
saveLog(joinPoint, null, e);
}
/**
*
*/
private void saveLog(JoinPoint joinPoint, Object result, Exception e) {
OperationRecord record = new OperationRecord();
// 记录操作耗时
if (startTime.get() != null) {
record.setSpendTime(System.currentTimeMillis() - startTime.get());
}
// 记录当前登录用户id、租户id
User user = getLoginUser();
if (user != null) {
record.setUserId(user.getUserId());
record.setTenantId(user.getTenantId());
}
// 记录请求地址、请求方式、ip
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (attributes == null ? null : attributes.getRequest());
if (request != null) {
record.setUrl(request.getRequestURI());
record.setRequestMethod(request.getMethod());
UserAgent ua = UserAgentUtil.parse(ServletUtil.getHeaderIgnoreCase(request, "User-Agent"));
record.setOs(ua.getPlatform().toString());
record.setDevice(ua.getOs().toString());
record.setBrowser(ua.getBrowser().toString());
record.setIp(ServletUtil.getClientIP(request));
}
// 记录异常信息
if (e != null) {
record.setStatus(1);
record.setError(StrUtil.sub(e.toString(), 0, MAX_LENGTH));
}
// 记录模块名、操作功能、请求方法、请求参数、返回结果
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
record.setMethod(joinPoint.getTarget().getClass().getName() + "." + signature.getName());
Method method = signature.getMethod();
if (method != null) {
OperationLog ol = method.getAnnotation(OperationLog.class);
if (ol != null) {
// 记录操作功能
record.setDescription(getDescription(method, ol));
// 记录操作模块
record.setModule(getModule(joinPoint, ol));
// 记录备注
if (StrUtil.isNotEmpty(ol.comments())) {
record.setComments(ol.comments());
}
// 记录请求参数
if (ol.param() && request != null) {
record.setParams(StrUtil.sub(getParams(joinPoint, request), 0, MAX_LENGTH));
}
// 记录请求结果
if (ol.result() && result != null) {
record.setResult(StrUtil.sub(JSONUtil.toJSONString(result), 0, MAX_LENGTH));
}
}
}
operationRecordService.saveAsync(record);
}
/**
*
*/
private User getLoginUser() {
Authentication subject = SecurityContextHolder.getContext().getAuthentication();
if (subject != null) {
Object object = subject.getPrincipal();
if (object instanceof User) {
return (User) object;
}
}
return null;
}
/**
*
*
* @param joinPoint JoinPoint
* @param request HttpServletRequest
* @return String
*/
private String getParams(JoinPoint joinPoint, HttpServletRequest request) {
String params;
Map<String, String> paramsMap = ServletUtil.getParamMap(request);
if (paramsMap.keySet().size() > 0) {
params = JSONUtil.toJSONString(paramsMap);
} else {
StringBuilder sb = new StringBuilder();
for (Object arg : joinPoint.getArgs()) {
if (ObjectUtil.isNull(arg)
|| arg instanceof MultipartFile
|| arg instanceof HttpServletRequest
|| arg instanceof HttpServletResponse) {
continue;
}
sb.append(JSONUtil.toJSONString(arg)).append(" ");
}
params = sb.toString();
}
return params;
}
/**
*
*
* @param joinPoint JoinPoint
* @param ol OperationLog
* @return String
*/
private String getModule(JoinPoint joinPoint, OperationLog ol) {
if (StrUtil.isNotEmpty(ol.module())) {
return ol.module();
}
OperationModule om = joinPoint.getTarget().getClass().getAnnotation(OperationModule.class);
if (om != null && StrUtil.isNotEmpty(om.value())) {
return om.value();
}
Api api = joinPoint.getTarget().getClass().getAnnotation(Api.class);
if (api != null && api.tags() != null) {
return ArrayUtil.join(api.tags(), ",");
}
return null;
}
/**
*
*
* @param method Method
* @param ol OperationLog
* @return String
*/
private String getDescription(Method method, OperationLog ol) {
if (StrUtil.isNotEmpty(ol.value())) {
return ol.value();
}
ApiOperation ao = method.getAnnotation(ApiOperation.class);
if (ao != null && StrUtil.isNotEmpty(ao.value())) {
return ao.value();
}
return null;
}
}

View File

@ -0,0 +1,75 @@
package com.eleadmin.common.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
*
*
* @author EleAdmin
* @since 2021-08-30 17:58:16
*/
@Data
@ConfigurationProperties(prefix = "config")
public class ConfigProperties {
/**
*
*/
private Integer uploadLocation = 0;
/**
* 使uuid
*/
private Boolean uploadUuidName = false;
/**
* (kb)
*/
private Integer thumbnailSize = 60;
/**
* OpenOffice
*/
private String openOfficeHome;
/**
* swagger
*/
private String swaggerBasePackage;
/**
* swagger
*/
private String swaggerTitle;
/**
* swagger
*/
private String swaggerDescription;
/**
* swagger
*/
private String swaggerVersion;
/**
* swagger
*/
private String swaggerHost;
/**
* token,
*/
private Long tokenExpireTime = 60 * 60 * 24L;
/**
* token,
*/
private int tokenRefreshTime = 30;
/**
* tokenKeybase64
*/
private String tokenKey;
}

View File

@ -0,0 +1,77 @@
package com.eleadmin.common.core.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.eleadmin.common.system.entity.User;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Arrays;
/**
* MybatisPlus
*
* @author EleAdmin
* @since 2018-02-22 11:29:28
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 多租户插件配置
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
@Override
public Expression getTenantId() {
return getLoginUserTenantId();
}
@Override
public boolean ignoreTable(String tableName) {
return Arrays.asList(
"sys_tenant",
"sys_dictionary",
"sys_dictionary_data"
).contains(tableName);
}
};
TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
// 分页插件配置
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
/**
* id
*
* @return Integer
*/
public Expression getLoginUserTenantId() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
return new LongValue(((User) object).getTenantId());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new NullValue();
}
}

View File

@ -0,0 +1,72 @@
package com.eleadmin.common.core.config;
import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
/**
* Swagger
*
* @author EleAdmin
* @since 2018-02-22 11:29:05
*/
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Resource
private ConfigProperties config;
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.OAS_30);
if (StrUtil.isNotBlank(config.getSwaggerHost())) {
docket.host(config.getSwaggerHost());
}
return docket
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(config.getSwaggerBasePackage()))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(config.getSwaggerTitle())
.description(config.getSwaggerDescription())
.version(config.getSwaggerVersion())
.termsOfServiceUrl("")
.build();
}
private List<SecurityScheme> securitySchemes() {
return Collections.singletonList(
new ApiKey("Authorization", "Authorization", "header")
);
}
private List<SecurityContext> securityContexts() {
AuthorizationScope[] scopes = {new AuthorizationScope("global", "accessEverything")};
List<SecurityReference> references = Collections.singletonList(
new SecurityReference("Authorization", scopes)
);
return Collections.singletonList(SecurityContext.builder()
.securityReferences(references)
.build());
}
}

View File

@ -0,0 +1,31 @@
package com.eleadmin.common.core.config;
import com.eleadmin.common.core.Constants;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc,
*
* @author EleAdmin
* @since 2019-06-12 10:11:16
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 访
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders("*")
.exposedHeaders(Constants.TOKEN_HEADER_NAME)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
.allowCredentials(true)
.maxAge(3600);
}
}

View File

@ -0,0 +1,48 @@
package com.eleadmin.common.core.exception;
import com.eleadmin.common.core.Constants;
/**
*
*
* @author EleAdmin
* @since 2018-02-22 11:29:28
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
public BusinessException() {
this(Constants.RESULT_ERROR_MSG);
}
public BusinessException(String message) {
this(Constants.RESULT_ERROR_CODE, message);
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}

View File

@ -0,0 +1,56 @@
package com.eleadmin.common.core.exception;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
/**
*
*
* @author EleAdmin
* @since 2018-02-22 11:29:30
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
@ResponseBody
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ApiResult<?> methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e,
HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.RESULT_ERROR_CODE, "请求方式不正确").setError(e.toString());
}
@ResponseBody
@ExceptionHandler(AccessDeniedException.class)
public ApiResult<?> accessDeniedExceptionHandler(AccessDeniedException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG).setError(e.toString());
}
@ResponseBody
@ExceptionHandler(BusinessException.class)
public ApiResult<?> businessExceptionHandler(BusinessException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(e.getCode(), e.getMessage());
}
@ResponseBody
@ExceptionHandler(Throwable.class)
public ApiResult<?> exceptionHandler(Throwable e, HttpServletResponse response) {
logger.error(e.getMessage(), e);
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG).setError(e.toString());
}
}

View File

@ -0,0 +1,29 @@
package com.eleadmin.common.core.security;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.utils.CommonUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 访
*
* @author EleAdmin
* @since 2020-03-25 00:35:03
*/
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
throws IOException, ServletException {
CommonUtil.responseError(response, Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG, e.getMessage());
}
}

View File

@ -0,0 +1,30 @@
package com.eleadmin.common.core.security;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.utils.CommonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
*
* @author EleAdmin
* @since 2020-03-25 00:35:03
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException, ServletException {
CommonUtil.responseError(response, Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG,
e.getMessage());
}
}

View File

@ -0,0 +1,85 @@
package com.eleadmin.common.core.security;
import cn.hutool.core.util.StrUtil;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.config.ConfigProperties;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.system.entity.LoginRecord;
import com.eleadmin.common.system.entity.Menu;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.service.LoginRecordService;
import com.eleadmin.common.system.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* token
*
* @author EleAdmin
* @since 2020-03-30 20:48:05
*/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Resource
private ConfigProperties configProperties;
@Resource
private UserService userService;
@Resource
private LoginRecordService loginRecordService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String access_token = JwtUtil.getAccessToken(request);
if (StrUtil.isNotBlank(access_token)) {
try {
// 解析token
Claims claims = JwtUtil.parseToken(access_token, configProperties.getTokenKey());
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
if (user == null) {
throw new UsernameNotFoundException("Username not found");
}
List<Menu> authorities = user.getAuthorities().stream()
.filter(m -> StrUtil.isNotBlank(m.getAuthority())).collect(Collectors.toList());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
user, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
// token将要过期签发新token, 防止突然退出登录
long expiration = (claims.getExpiration().getTime() - new Date().getTime()) / 1000 / 60;
if (expiration < configProperties.getTokenRefreshTime()) {
String token = JwtUtil.buildToken(jwtSubject, configProperties.getTokenExpireTime(),
configProperties.getTokenKey());
response.addHeader(Constants.TOKEN_HEADER_NAME, token);
loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_REFRESH, null,
user.getTenantId(), request);
}
} catch (ExpiredJwtException e) {
CommonUtil.responseError(response, Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG,
e.getMessage());
return;
} catch (Exception e) {
CommonUtil.responseError(response, Constants.BAD_CREDENTIALS_CODE, Constants.BAD_CREDENTIALS_MSG,
e.toString());
return;
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,31 @@
package com.eleadmin.common.core.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* Jwt
*
* @author EleAdmin
* @since 2021-09-03 00:11:12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtSubject implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private String username;
/**
* id
*/
private Integer tenantId;
}

View File

@ -0,0 +1,141 @@
package com.eleadmin.common.core.security;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.utils.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Date;
/**
* JWT
*
* @author EleAdmin
* @since 2018-01-21 16:30:59
*/
public class JwtUtil {
/**
* access_token
*
* @param request HttpServletRequest
* @return String
*/
public static String getAccessToken(HttpServletRequest request) {
String access_token = ServletUtil.getHeaderIgnoreCase(request, Constants.TOKEN_HEADER_NAME);
if (StrUtil.isNotBlank(access_token)) {
if (access_token.startsWith(Constants.TOKEN_TYPE)) {
access_token = StrUtil.removePrefix(access_token, Constants.TOKEN_TYPE).trim();
}
} else {
access_token = request.getParameter(Constants.TOKEN_PARAM_NAME);
}
return access_token;
}
/**
* token
*
* @param subject
* @param expire
* @param base64EncodedKey base64Key
* @return token
*/
public static String buildToken(JwtSubject subject, Long expire, String base64EncodedKey) {
return buildToken(JSONUtil.toJSONString(subject), expire, decodeKey(base64EncodedKey));
}
/**
* token
*
* @param subject
* @param expire
* @param key
* @return token
*/
public static String buildToken(String subject, Long expire, Key key) {
Date expireDate = new Date(new Date().getTime() + 1000 * expire);
return Jwts.builder()
.setSubject(subject)
.setExpiration(expireDate)
.setIssuedAt(new Date())
.signWith(key)
.compact();
}
/**
* token
*
* @param token token
* @param base64EncodedKey base64Key
* @return Claims
*/
public static Claims parseToken(String token, String base64EncodedKey) {
return parseToken(token, decodeKey(base64EncodedKey));
}
/**
* token
*
* @param token token
* @param key
* @return Claims
*/
public static Claims parseToken(String token, Key key) {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
}
/**
* JwtSubject
*
* @param claims Claims
* @return JwtSubject
*/
public static JwtSubject getJwtSubject(Claims claims) {
return JSONUtil.parseObject(claims.getSubject(), JwtSubject.class);
}
/**
* Key
*
* @return Key
*/
public static Key randomKey() {
return Keys.secretKeyFor(SignatureAlgorithm.HS256);
}
/**
* base64key
*
* @return String
*/
public static String encodeKey(Key key) {
return Encoders.BASE64.encode(key.getEncoded());
}
/**
* base64Key
*
* @param base64EncodedKey base64key
* @return Key
*/
public static Key decodeKey(String base64EncodedKey) {
if (StrUtil.isBlank(base64EncodedKey)) {
return null;
}
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(base64EncodedKey));
}
}

View File

@ -0,0 +1,79 @@
package com.eleadmin.common.core.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;
/**
* Spring Security
*
* @author EleAdmin
* @since 2020-03-23 18:04:52
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
@Resource
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Resource
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/file/**", "/api/captcha", "/")
.permitAll()
.antMatchers(
"/api/login",
"/druid/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/webjars/**",
"/v2/api-docs",
"/v3/api-docs",
"/swagger-ui/**"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.cors()
.and()
.logout()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.exceptionHandling()
.accessDeniedHandler(jwtAccessDeniedHandler)
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,174 @@
package com.eleadmin.common.core.utils;
import cn.hutool.core.util.ObjectUtil;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.web.ApiResult;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
/**
*
*
* @author EleAdmin
* @since 2017-06-10 10:10:22
*/
public class CommonUtil {
// 生成uuid的字符
private static final String[] chars = new String[]{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
};
/**
* 8uuid
*
* @return String
*/
public static String randomUUID8() {
StringBuilder sb = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
sb.append(chars[x % 0x3E]);
}
return sb.toString();
}
/**
* 16uuid
*
* @return String
*/
public static String randomUUID16() {
StringBuilder sb = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 16; i++) {
String str = uuid.substring(i * 2, i * 2 + 2);
int x = Integer.parseInt(str, 16);
sb.append(chars[x % 0x3E]);
}
return sb.toString();
}
/**
* List
*
* @param list List
* @param mapper Function
* @param <T>
* @param <R>
* @return boolean
*/
public static <T, R> boolean checkRepeat(List<T> list, Function<? super T, ? extends R> mapper) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (i != j && mapper.apply(list.get(i)).equals(mapper.apply(list.get(j)))) {
return true;
}
}
}
return false;
}
/**
* List
*
* @param data List
* @param parentId parentId
* @param parentIdMapper parentIdFunction
* @param idMapper idFunction
* @param consumer childrenConsumer
* @param <T>
* @param <R> parentId
* @return List<T>
*/
public static <T, R> List<T> toTreeData(List<T> data, R parentId,
Function<? super T, ? extends R> parentIdMapper,
Function<? super T, ? extends R> idMapper,
BiConsumer<T, List<T>> consumer) {
List<T> result = new ArrayList<>();
for (T d : data) {
R dParentId = parentIdMapper.apply(d);
if (ObjectUtil.equals(parentId, dParentId)) {
R dId = idMapper.apply(d);
List<T> children = toTreeData(data, dId, parentIdMapper, idMapper, consumer);
consumer.accept(d, children);
result.add(d);
}
}
return result;
}
/**
*
*
* @param data List
* @param consumer
* @param mapper childrenFunction
* @param <T>
*/
public static <T> void eachTreeData(List<T> data, Consumer<T> consumer, Function<T, List<T>> mapper) {
for (T d : data) {
consumer.accept(d);
List<T> children = mapper.apply(d);
if (children != null && children.size() > 0) {
eachTreeData(children, consumer, mapper);
}
}
}
/**
*
*
* @param records
* @return
*/
public static <T> T listGetOne(List<T> records) {
return records == null || records.size() == 0 ? null : records.get(0);
}
/**
*
*
* @param response HttpServletResponse
*/
public static void addCrossHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Expose-Headers", Constants.TOKEN_HEADER_NAME);
}
/**
*
*
* @param response HttpServletResponse
* @param code
* @param message
* @param error
*/
public static void responseError(HttpServletResponse response, Integer code, String message, String error) {
response.setContentType("application/json;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.write(JSONUtil.toJSONString(new ApiResult<>(code, message, null, error)));
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,378 @@
package com.eleadmin.common.core.utils;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
*
*
* @author EleAdmin
* @since 2018-12-14 08:38:53
*/
public class FileServerUtil {
// 除 text/* 外也需要设置输出编码的 content-type
private final static List<String> SET_CHARSET_CONTENT_TYPES = Arrays.asList(
"application/json",
"application/javascript"
);
/**
*
*
* @param file MultipartFile
* @param directory
* @param uuidName uuid
* @return File
*/
public static File upload(MultipartFile file, String directory, boolean uuidName)
throws IOException, IllegalStateException {
File outFile = getUploadFile(file.getOriginalFilename(), directory, uuidName);
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
throw new RuntimeException("make directory fail");
}
}
file.transferTo(outFile);
return outFile;
}
/**
* base64
*
* @param base64 base64
* @param fileName , 使uuid
* @param directory
* @return File
*/
public static File upload(String base64, String fileName, String directory)
throws FileNotFoundException, IORuntimeException {
if (StrUtil.isBlank(base64) || !base64.startsWith("data:image/") || !base64.contains(";base64,")) {
throw new RuntimeException("base64 data error");
}
String suffix = "." + base64.substring(11, base64.indexOf(";")); // 获取文件后缀
boolean uuidName = StrUtil.isBlank(fileName);
File outFile = getUploadFile(uuidName ? suffix : fileName, directory, uuidName);
byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
IoUtil.write(new FileOutputStream(outFile), true, bytes);
return outFile;
}
/**
*
*
* @param name
* @param directory
* @param uuidName 使uuid
* @return File
*/
public static File getUploadFile(String name, String directory, boolean uuidName) {
// 当前日期作为上传子目录
String dir = new SimpleDateFormat("yyyyMMdd/").format(new Date());
// 获取文件后缀
String suffix = (name == null || !name.contains(".")) ? "" : name.substring(name.lastIndexOf("."));
// 使用uuid命名
if (uuidName || name == null) {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return new File(directory, dir + uuid + suffix);
}
// 使用原名称, 存在相同则加(1)
File file = new File(directory, dir + name);
String prefix = StrUtil.removeSuffix(name, suffix);
int sameSize = 2;
while (file.exists()) {
file = new File(directory, dir + prefix + "(" + sameSize + ")" + suffix);
sameSize++;
}
return file;
}
/**
* ,
*
* @param file
* @param pdfDir officepdf
* @param officeHome openOffice
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void preview(File file, String pdfDir, String officeHome,
HttpServletResponse response, HttpServletRequest request) {
preview(file, false, pdfDir, officeHome, response, request);
}
/**
* ,
*
* @param file
* @param forceDownload
* @param pdfDir officepdf
* @param officeHome openOffice
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void preview(File file, boolean forceDownload, String pdfDir, String officeHome,
HttpServletResponse response, HttpServletRequest request) {
CommonUtil.addCrossHeaders(response);
if (file == null || !file.exists()) {
outNotFund(response);
return;
}
if (forceDownload) {
setDownloadHeader(response, file.getName());
} else {
// office转pdf预览
if (OpenOfficeUtil.canConverter(file.getName())) {
File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath(), pdfDir, officeHome);
if (pdfFile != null) {
file = pdfFile;
}
}
// 获取文件类型
String contentType = getContentType(file);
if (contentType != null) {
response.setContentType(contentType);
// 设置编码
if (contentType.startsWith("text/") || SET_CHARSET_CONTENT_TYPES.contains(contentType)) {
try {
String charset = JChardetFacadeUtil.detectCodepage(file.toURI().toURL());
if (charset != null) {
response.setCharacterEncoding(charset);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
} else {
setDownloadHeader(response, file.getName());
}
}
response.setHeader("Cache-Control", "public");
output(file, response, request);
}
/**
*
*
* @param file
* @param thumbnail
* @param size (kb)
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void previewThumbnail(File file, File thumbnail, Integer size,
HttpServletResponse response, HttpServletRequest request) {
// 如果是图片并且缩略图不存在则生成
if (!thumbnail.exists() && isImage(file)) {
long fileSize = file.length();
if ((fileSize / 1024) > size) {
try {
if (thumbnail.getParentFile().mkdirs()) {
ImgUtil.scale(file, thumbnail, 100f / (fileSize / 1024f));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
preview(file, null, null, response, request);
return;
}
}
preview(thumbnail, null, null, response, request);
}
/**
* ,
*
* @param file
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void output(File file, HttpServletResponse response, HttpServletRequest request) {
long length = file.length(); // 文件总大小
long start = 0, to = length - 1; // 开始读取位置, 结束读取位置
long lastModified = file.lastModified(); // 文件修改时间
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("ETag", "\"" + length + "-" + lastModified + "\"");
response.setHeader("Last-Modified", new Date(lastModified).toString());
String range = request.getHeader("Range");
if (range != null) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String[] ranges = range.replace("bytes=", "").split("-");
start = Long.parseLong(ranges[0].trim());
if (ranges.length > 1) {
to = Long.parseLong(ranges[1].trim());
}
response.setHeader("Content-Range", "bytes " + start + "-" + to + "/" + length);
}
response.setHeader("Content-Length", String.valueOf(to - start + 1));
try {
output(file, response.getOutputStream(), 2048, start, to);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*
* @param file
* @param os
*/
public static void output(File file, OutputStream os) {
output(file, os, null);
}
/**
*
*
* @param file
* @param os
* @param size
*/
public static void output(File file, OutputStream os, Integer size) {
output(file, os, size, null, null);
}
/**
* ,
*
* @param file
* @param os
* @param size
* @param start
* @param to
*/
public static void output(File file, OutputStream os, Integer size, Long start, Long to) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
if (start != null) {
long skip = is.skip(start);
if (skip < start) {
System.out.println("ERROR: skip fail[ skipped=" + skip + ", start= " + start + " ]");
}
to = to - start + 1;
}
byte[] bytes = new byte[size == null ? 2048 : size];
int len;
if (to == null) {
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
} else {
while (to > 0 && (len = is.read(bytes)) != -1) {
os.write(bytes, 0, to < len ? (int) ((long) to) : len);
to -= len;
}
}
os.flush();
} catch (IOException ignored) {
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
/**
*
*
* @param file
* @return String
*/
public static String getContentType(File file) {
String contentType = null;
try {
contentType = new Tika().detect(file);
} catch (IOException e) {
e.printStackTrace();
}
return contentType;
}
/**
*
*
* @param file
* @return boolean
*/
public static boolean isImage(File file) {
String contentType = getContentType(file);
return contentType != null && contentType.startsWith("image/");
}
/**
* header
*
* @param response HttpServletResponse
* @param fileName
*/
public static void setDownloadHeader(HttpServletResponse response, String fileName) {
response.setContentType("application/force-download");
try {
fileName = URLEncoder.encode(fileName, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
}
/**
* 404
*
* @param response HttpServletResponse
*/
public static void outNotFund(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
outMessage("404 Not Found", null, response);
}
/**
*
*
* @param title
* @param message
* @param response HttpServletResponse
*/
public static void outMessage(String title, String message, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter writer = response.getWriter();
writer.write("<!doctype html>");
writer.write("<title>" + title + "</title>");
writer.write("<h1 style=\"text-align: center\">" + title + "</h1>");
if (message != null) {
writer.write(message);
}
writer.write("<hr/><p style=\"text-align: center\">EleAdmin File Server</p>");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,69 @@
package com.eleadmin.common.core.utils;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
/**
* JSON
*
* @author EleAdmin
* @since 2017-06-10 10:10:39
*/
public class JSONUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
/**
* json
*
* @param value
* @return String
*/
public static String toJSONString(Object value) {
return toJSONString(value, false);
}
/**
* json
*
* @param value
* @param pretty
* @return String
*/
public static String toJSONString(Object value, boolean pretty) {
if (value != null) {
if (value instanceof String) {
return (String) value;
}
try {
if (pretty) {
return objectWriter.writeValueAsString(value);
}
return objectMapper.writeValueAsString(value);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* json
*
* @param json String
* @param clazz Class
* @return T
*/
public static <T> T parseObject(String json, Class<T> clazz) {
if (StrUtil.isNotBlank(json) && clazz != null) {
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@ -0,0 +1,124 @@
package com.eleadmin.common.core.utils;
import cn.hutool.core.util.StrUtil;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import java.io.File;
import java.util.Arrays;
import java.util.Base64;
/**
* OpenOfficeUtil
*
* @author EleAdmin
* @since 2018-12-14 08:38:19
*/
public class OpenOfficeUtil {
// 支持转换pdf的文件后缀列表
private static final String[] CAN_CONVERTER_FILES = new String[]{
"doc", "docx", "xls", "xlsx", "ppt", "pptx"
};
/**
* pdf
*
* @param filePath
* @param outDir
* @param officeHome OpenOffice
* @return File
*/
public static File converterToPDF(String filePath, String outDir, String officeHome) {
return converterToPDF(filePath, outDir, officeHome, true);
}
/**
* pdf
*
* @param filePath
* @param outDir
* @param officeHome OpenOffice
* @param cache 使
* @return File
*/
public static File converterToPDF(String filePath, String outDir, String officeHome, boolean cache) {
if (StrUtil.isBlank(filePath)) {
return null;
}
File srcFile = new File(filePath);
if (!srcFile.exists()) {
return null;
}
// 是否转换过
String outPath = Base64.getEncoder().encodeToString(filePath.getBytes())
.replace("/", "-").replace("+", "-");
File outFile = new File(outDir, outPath + ".pdf");
if (cache && outFile.exists()) {
return outFile;
}
// 转换
OfficeManager officeManager = null;
try {
officeManager = getOfficeManager(officeHome);
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
return converterFile(srcFile, outFile, converter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (officeManager != null) {
officeManager.stop();
}
}
return null;
}
/**
*
*
* @param inFile
* @param outFile
* @param converter OfficeDocumentConverter
* @return File
*/
public static File converterFile(File inFile, File outFile, OfficeDocumentConverter converter) {
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
return outFile;
}
}
converter.convert(inFile, outFile);
return outFile;
}
/**
* pdf
*
* @param path
* @return boolean
*/
public static boolean canConverter(String path) {
try {
String suffix = path.substring(path.lastIndexOf(".") + 1);
return Arrays.asList(CAN_CONVERTER_FILES).contains(suffix);
} catch (Exception e) {
return false;
}
}
/**
* OpenOffice
*
* @param officeHome OpenOffice
* @return OfficeManager
*/
public static OfficeManager getOfficeManager(String officeHome) {
if (officeHome == null || officeHome.trim().isEmpty()) return null;
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
config.setOfficeHome(officeHome); // 设置OpenOffice安装目录
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start(); // 启动OpenOffice服务
return officeManager;
}
}

View File

@ -0,0 +1,88 @@
package com.eleadmin.common.core.web;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2017-06-10 10:10:50
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "状态信息")
private String message;
@ApiModelProperty(value = "返回数据")
private T data;
@ApiModelProperty(value = "错误信息")
private String error;
public ApiResult() {
}
public ApiResult(Integer code) {
this(code, null);
}
public ApiResult(Integer code, String message) {
this(code, message, null);
}
public ApiResult(Integer code, String message, T data) {
this(code, message, data, null);
}
public ApiResult(Integer code, String message, T data, String error) {
setCode(code);
setMessage(message);
setData(data);
setError(error);
}
public Integer getCode() {
return this.code;
}
public ApiResult<T> setCode(Integer code) {
this.code = code;
return this;
}
public String getMessage() {
return this.message;
}
public ApiResult<T> setMessage(String message) {
this.message = message;
return this;
}
public T getData() {
return this.data;
}
public ApiResult<T> setData(T data) {
this.data = data;
return this;
}
public String getError() {
return this.error;
}
public ApiResult<T> setError(String error) {
this.error = error;
return this;
}
}

View File

@ -0,0 +1,160 @@
package com.eleadmin.common.core.web;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.system.entity.User;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.util.List;
/**
* Controller
*
* @author EleAdmin
* @since 2017-06-10 10:10:19
*/
public class BaseController {
/**
* user
*
* @return User
*/
public User getLoginUser() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
return (User) object;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
/**
* userId
*
* @return userId
*/
public Integer getLoginUserId() {
User loginUser = getLoginUser();
return loginUser == null ? null : loginUser.getUserId();
}
/**
*
*
* @return ApiResult
*/
public ApiResult<?> success() {
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG);
}
/**
*
*
* @param message
* @return ApiResult
*/
public ApiResult<?> success(String message) {
return success().setMessage(message);
}
/**
*
*
* @param data
* @return ApiResult
*/
public <T> ApiResult<T> success(T data) {
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG, data);
}
/**
*
*
* @param message
* @return ApiResult
*/
public <T> ApiResult<T> success(String message, T data) {
return success(data).setMessage(message);
}
/**
*
*
* @param list
* @param count
* @return ApiResult
*/
public <T> ApiResult<PageResult<T>> success(List<T> list, Long count) {
return success(new PageResult<>(list, count));
}
/**
*
*
* @param iPage IPage
* @return ApiResult
*/
public <T> ApiResult<PageResult<T>> success(IPage<T> iPage) {
return success(iPage.getRecords(), iPage.getTotal());
}
/**
*
*
* @return ApiResult
*/
public ApiResult<?> fail() {
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG);
}
/**
*
*
* @param message
* @return ApiResult
*/
public ApiResult<?> fail(String message) {
return fail().setMessage(message);
}
/**
*
*
* @param data
* @return ApiResult
*/
public <T> ApiResult<T> fail(T data) {
return fail(Constants.RESULT_ERROR_MSG, data);
}
/**
*
*
* @param message
* @param data
* @return ApiResult
*/
public <T> ApiResult<T> fail(String message, T data) {
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message, data);
}
/**
* null
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
}

View File

@ -0,0 +1,59 @@
package com.eleadmin.common.core.web;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.utils.CommonUtil;
import lombok.Data;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2021-08-26 22:14:43
*/
@Data
public class BaseParam implements Serializable {
private static final long serialVersionUID = 1L;
@TableField(exist = false)
@ApiModelProperty("分页查询页码")
private Long page;
@TableField(exist = false)
@ApiModelProperty("分页查询每页数量")
private Long limit;
@TableField(exist = false)
@ApiModelProperty(value = "排序字段", notes = "排序字段或sql, 如果是sql则order字段无用, 如: `id asc, name desc`")
private String sort;
@TableField(exist = false)
@ApiModelProperty(value = "排序方式", notes = "sort是字段名称时对应的排序方式, asc升序, desc降序")
private String order;
@QueryField(value = "create_time", type = QueryType.GE)
@TableField(exist = false)
@ApiModelProperty("创建时间起始值")
private String createTimeStart;
@QueryField(value = "create_time", type = QueryType.LE)
@TableField(exist = false)
@ApiModelProperty("创建时间结束值")
private String createTimeEnd;
/**
*
*
* @param records
* @return
*/
public <T> T getOne(List<T> records) {
return CommonUtil.listGetOne(records);
}
}

View File

@ -0,0 +1,57 @@
package com.eleadmin.common.core.web;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2020-03-13 00:11:06
*/
@Data
public class BatchParam<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "需要修改的数据id集合")
private List<Serializable> ids;
@ApiModelProperty(value = "需要修改的字段和值")
private T data;
/**
*
*
* @param service IService
* @param idField id
* @return boolean
*/
public boolean update(IService<T> service, String idField) {
if (this.data == null) {
return false;
}
return service.update(this.data, new UpdateWrapper<T>().in(idField, this.ids));
}
/**
*
*
* @param service IService
* @param idField id
* @return boolean
*/
public boolean update(IService<T> service, SFunction<T, ?> idField) {
if (this.data == null) {
return false;
}
return service.update(this.data, new LambdaUpdateWrapper<T>().in(idField, this.ids));
}
}

View File

@ -0,0 +1,96 @@
package com.eleadmin.common.core.web;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2021-09-07 22:24:39
*/
@Data
public class ExistenceParam<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "检查的字段")
private String field;
@ApiModelProperty(value = "字段的值")
private String value;
@ApiModelProperty(value = "修改时的主键")
private Integer id;
/**
*
*
* @param service IService
* @param idField
* @return boolean
*/
public boolean isExistence(IService<T> service, String idField) {
return isExistence(service, idField, true);
}
/**
*
*
* @param service IService
* @param idField
* @param isToUnderlineCase field线
* @return boolean
*/
public boolean isExistence(IService<T> service, String idField, boolean isToUnderlineCase) {
if (StrUtil.hasBlank(this.field, this.value)) {
return false;
}
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
QueryWrapper<T> wrapper = new QueryWrapper<>();
wrapper.eq(fieldName, value);
if (id != null) {
wrapper.ne(idField, id);
}
return service.count(wrapper) > 0;
}
/**
*
*
* @param service IService
* @param idField
* @return boolean
*/
public boolean isExistence(IService<T> service, SFunction<T, ?> idField) {
return isExistence(service, idField, true);
}
/**
*
*
* @param service IService
* @param idField
* @param isToUnderlineCase field线
* @return boolean
*/
public boolean isExistence(IService<T> service, SFunction<T, ?> idField, boolean isToUnderlineCase) {
if (StrUtil.hasBlank(this.field, this.value)) {
return false;
}
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
wrapper.apply(fieldName + " = {0}", value);
if (id != null) {
wrapper.ne(idField, id);
}
return service.count(wrapper) > 0;
}
}

View File

@ -0,0 +1,343 @@
package com.eleadmin.common.core.web;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eleadmin.common.core.Constants;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.utils.CommonUtil;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
*
*
* @author EleAdmin
* @since 2019-04-26 10:34:35
*/
public class PageParam<T, U extends BaseParam> extends Page<T> {
private static final long serialVersionUID = 1L;
/**
* id
*/
private static final String TENANT_ID_FIELD = "tenantId";
/**
*
*/
private final U where;
/**
* 线
*/
private final boolean isToUnderlineCase;
public PageParam() {
this(null);
}
public PageParam(U where) {
this(where, true);
}
public PageParam(U where, boolean isToUnderlineCase) {
super();
this.where = where;
this.isToUnderlineCase = isToUnderlineCase;
if (where != null) {
// 获取分页页码
if (where.getPage() != null) {
setCurrent(where.getPage());
}
// 获取分页每页数量
if (where.getLimit() != null) {
setSize(where.getLimit());
}
// 获取排序方式
if (where.getSort() != null) {
if (sortIsSQL(where.getSort())) {
setOrders(parseOrderSQL(where.getSort()));
} else {
List<OrderItem> orderItems = new ArrayList<>();
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(where.getSort()) : where.getSort();
boolean asc = !Constants.ORDER_DESC_VALUE.equals(where.getOrder());
orderItems.add(new OrderItem(column, asc));
setOrders(orderItems);
}
}
}
}
/**
* sql
*/
private boolean sortIsSQL(String sort) {
return sort != null && (sort.contains(",") || sort.trim().contains(" "));
}
/**
* sql
*/
private List<OrderItem> parseOrderSQL(String orderSQL) {
List<OrderItem> orders = new ArrayList<>();
if (StrUtil.isNotBlank(orderSQL)) {
for (String item : orderSQL.split(",")) {
String[] temp = item.trim().split(" ");
if (!temp[0].isEmpty()) {
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(temp[0]) : temp[0];
boolean asc = temp.length == 1 || !temp[temp.length - 1].equals(Constants.ORDER_DESC_VALUE);
orders.add(new OrderItem(column, asc));
}
}
}
return orders;
}
/**
*
*
* @param orderItems
* @return PageParam
*/
public PageParam<T, U> setDefaultOrder(List<OrderItem> orderItems) {
if (orders() == null || orders().size() == 0) {
setOrders(orderItems);
}
return this;
}
/**
*
*
* @param orderSQL
* @return PageParam
*/
public PageParam<T, U> setDefaultOrder(String orderSQL) {
setDefaultOrder(parseOrderSQL(orderSQL));
return this;
}
/**
*
*
* @param excludes
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapper(String... excludes) {
return buildWrapper(null, Arrays.asList(excludes));
}
/**
*
*
* @param columns
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapperWith(String... columns) {
return buildWrapper(Arrays.asList(columns), null);
}
/**
* QueryWrapper
*
* @param columns
* @param excludes
* @return QueryWrapper
*/
private QueryWrapper<T> buildWrapper(List<String> columns, List<String> excludes) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = BeanUtil.beanToMap(where, false, true);
for (String fieldName : map.keySet()) {
Object fieldValue = map.get(fieldName);
Field field = ReflectUtil.getField(where.getClass(), fieldName);
// 过滤不包含的字段
if (columns != null && !columns.contains(fieldName)) {
continue;
}
// 过滤排除的字段
if (excludes != null && excludes.contains(fieldName)) {
continue;
}
// 过滤逻辑删除字段
if (field.getAnnotation(TableLogic.class) != null) {
continue;
}
// 过滤租户id字段
if (fieldName.equals(TENANT_ID_FIELD)) {
continue;
}
// 获取注解指定的查询字段及查询方式
QueryType queryType = QueryType.LIKE;
QueryField queryField = field.getAnnotation(QueryField.class);
if (queryField != null) {
if (StrUtil.isNotEmpty(queryField.value())) {
fieldName = queryField.value();
}
if (queryField.type() != null) {
queryType = queryField.type();
}
} else {
// 过滤非本表的字段
TableField tableField = field.getAnnotation(TableField.class);
if (tableField != null && !tableField.exist()) {
continue;
}
}
// 字段名驼峰转下划线
if (this.isToUnderlineCase) {
fieldName = StrUtil.toUnderlineCase(fieldName);
}
//
switch (queryType) {
case EQ:
queryWrapper.eq(fieldName, fieldValue);
break;
case NE:
queryWrapper.ne(fieldName, fieldValue);
break;
case GT:
queryWrapper.gt(fieldName, fieldValue);
break;
case GE:
queryWrapper.ge(fieldName, fieldValue);
break;
case LT:
queryWrapper.lt(fieldName, fieldValue);
break;
case LE:
queryWrapper.le(fieldName, fieldValue);
break;
case LIKE:
queryWrapper.like(fieldName, fieldValue);
break;
case NOT_LIKE:
queryWrapper.notLike(fieldName, fieldValue);
break;
case LIKE_LEFT:
queryWrapper.likeLeft(fieldName, fieldValue);
break;
case LIKE_RIGHT:
queryWrapper.likeRight(fieldName, fieldValue);
break;
case IS_NULL:
queryWrapper.isNull(fieldName);
break;
case IS_NOT_NULL:
queryWrapper.isNotNull(fieldName);
break;
case IN:
queryWrapper.in(fieldName, fieldValue);
break;
case NOT_IN:
queryWrapper.notIn(fieldName, fieldValue);
break;
case IN_STR:
if (fieldValue instanceof String) {
queryWrapper.in(fieldName, Arrays.asList(((String) fieldValue).split(",")));
}
break;
case NOT_IN_STR:
if (fieldValue instanceof String) {
queryWrapper.notIn(fieldName, Arrays.asList(((String) fieldValue).split(",")));
}
break;
}
}
return queryWrapper;
}
/**
*
*
* @return QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper() {
return getOrderWrapper(getWrapper());
}
/**
*
*
* @param queryWrapper QueryWrapper
* @return QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper(QueryWrapper<T> queryWrapper) {
if (queryWrapper == null) {
queryWrapper = new QueryWrapper<>();
}
for (OrderItem orderItem : orders()) {
if (orderItem.isAsc()) {
queryWrapper.orderByAsc(orderItem.getColumn());
} else {
queryWrapper.orderByDesc(orderItem.getColumn());
}
}
return queryWrapper;
}
/**
*
*
* @param records
* @return
*/
public T getOne(List<T> records) {
return CommonUtil.listGetOne(records);
}
/**
*
*
* @param records
* @return
*/
public List<T> sortRecords(List<T> records) {
List<OrderItem> orderItems = orders();
if (records == null || records.size() < 2 || orderItems == null || orderItems.size() == 0) {
return records;
}
Comparator<T> comparator = null;
for (OrderItem item : orderItems) {
if (item.getColumn() == null) {
continue;
}
String field = this.isToUnderlineCase ? StrUtil.toCamelCase(item.getColumn()) : item.getColumn();
Function keyExtractor = t -> ReflectUtil.getFieldValue(t, field);
if (comparator == null) {
if (item.isAsc()) {
comparator = Comparator.comparing(keyExtractor);
} else {
comparator = Comparator.comparing(keyExtractor, Comparator.reverseOrder());
}
} else {
if (item.isAsc()) {
comparator.thenComparing(keyExtractor);
} else {
comparator.thenComparing(keyExtractor, Comparator.reverseOrder());
}
}
}
if (comparator != null) {
return records.stream().sorted(comparator).collect(Collectors.toList());
}
return records;
}
}

View File

@ -0,0 +1,51 @@
package com.eleadmin.common.core.web;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2017-06-10 10:10:02
*/
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "当前页数据")
private List<T> list;
@ApiModelProperty(value = "总数量")
private Long count;
public PageResult() {
}
public PageResult(List<T> list) {
this(list, null);
}
public PageResult(List<T> list, Long count) {
setList(list);
setCount(count);
}
public List<T> getList() {
return this.list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getCount() {
return this.count;
}
public void setCount(Long count) {
this.count = count;
}
}

View File

@ -0,0 +1,152 @@
package com.eleadmin.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.*;
import com.eleadmin.common.system.entity.Dictionary;
import com.eleadmin.common.system.param.DictionaryParam;
import com.eleadmin.common.system.service.DictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:03
*/
@Api(tags = "字典管理")
@RestController
@RequestMapping("/api/system/dictionary")
public class DictionaryController extends BaseController {
@Resource
private DictionaryService dictionaryService;
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("分页查询字典")
@GetMapping("/page")
public ApiResult<PageResult<Dictionary>> page(DictionaryParam param) {
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictionaryService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("查询全部字典")
@GetMapping()
public ApiResult<List<Dictionary>> list(DictionaryParam param) {
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictionaryService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("根据id查询字典")
@GetMapping("/{id}")
public ApiResult<Dictionary> get(@PathVariable("id") Integer id) {
return success(dictionaryService.getById(id));
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@ApiOperation("添加字典")
@PostMapping()
public ApiResult<?> add(@RequestBody Dictionary dictionary) {
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictCode, dictionary.getDictCode())) > 0) {
return fail("字典标识已存在");
}
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictName, dictionary.getDictName())) > 0) {
return fail("字典名称已存在");
}
if (dictionaryService.save(dictionary)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:update')")
@OperationLog
@ApiOperation("修改字典")
@PutMapping()
public ApiResult<?> update(@RequestBody Dictionary dictionary) {
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictCode, dictionary.getDictCode())
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
return fail("字典标识已存在");
}
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictName, dictionary.getDictName())
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
return fail("字典名称已存在");
}
if (dictionaryService.updateById(dictionary)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@OperationLog
@ApiOperation("删除字典")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictionaryService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@OperationLog
@ApiOperation("批量添加字典")
@PostMapping("/batch")
public ApiResult<List<String>> saveBatch(@RequestBody List<Dictionary> list) {
if (CommonUtil.checkRepeat(list, Dictionary::getDictCode)) {
return fail("字典标识不能重复", null);
}
if (CommonUtil.checkRepeat(list, Dictionary::getDictName)) {
return fail("字典名称不能重复", null);
}
List<Dictionary> codeExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
.in(Dictionary::getDictCode, list.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())));
if (codeExists.size() > 0) {
return fail("字典标识已存在", codeExists.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())).setCode(2);
}
List<Dictionary> nameExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
.in(Dictionary::getDictName, list.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())));
if (nameExists.size() > 0) {
return fail("字典名称已存在", nameExists.stream().map(Dictionary::getDictName)
.collect(Collectors.toList())).setCode(3);
}
if (dictionaryService.saveBatch(list)) {
return success("添加成功", null);
}
return fail("添加失败", null);
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@OperationLog
@ApiOperation("批量删除字典")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@ -0,0 +1,131 @@
package com.eleadmin.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.*;
import com.eleadmin.common.system.entity.DictionaryData;
import com.eleadmin.common.system.param.DictionaryDataParam;
import com.eleadmin.common.system.service.DictionaryDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
@Api(tags = "字典数据管理")
@RestController
@RequestMapping("/api/system/dictionary-data")
public class DictionaryDataController extends BaseController {
@Resource
private DictionaryDataService dictionaryDataService;
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("分页查询字典数据")
@GetMapping("/page")
public ApiResult<PageResult<DictionaryData>> page(DictionaryDataParam param) {
return success(dictionaryDataService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("查询全部字典数据")
@GetMapping()
public ApiResult<List<DictionaryData>> list(DictionaryDataParam param) {
return success(dictionaryDataService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@OperationLog
@ApiOperation("根据id查询字典数据")
@GetMapping("/{id}")
public ApiResult<DictionaryData> get(@PathVariable("id") Integer id) {
return success(dictionaryDataService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@OperationLog
@ApiOperation("添加字典数据")
@PostMapping()
public ApiResult<?> add(@RequestBody DictionaryData dictionaryData) {
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())) > 0) {
return fail("字典数据名称已存在");
}
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())) > 0) {
return fail("字典数据标识已存在");
}
if (dictionaryDataService.save(dictionaryData)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:update')")
@OperationLog
@ApiOperation("修改字典数据")
@PutMapping()
public ApiResult<?> update(@RequestBody DictionaryData dictionaryData) {
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
return fail("字典数据名称已存在");
}
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
return fail("字典数据标识已存在");
}
if (dictionaryDataService.updateById(dictionaryData)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@OperationLog
@ApiOperation("删除字典数据")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictionaryDataService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@OperationLog
@ApiOperation("批量添加字典数据")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<DictionaryData> dictDataList) {
if (dictionaryDataService.saveBatch(dictDataList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@OperationLog
@ApiOperation("批量删除字典数据")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryDataService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@ -0,0 +1,49 @@
package com.eleadmin.common.system.controller;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.system.entity.EmailRecord;
import com.eleadmin.common.system.service.EmailRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.mail.MessagingException;
/**
*
*
* @author EleAdmin
* @since 2020-03-21 00:37:11
*/
@Api(tags = "邮件功能")
@RestController
@RequestMapping("/api/system/email")
public class EmailController extends BaseController {
@Resource
private EmailRecordService emailRecordService;
@PreAuthorize("hasAuthority('sys:email:send')")
@OperationLog
@ApiOperation("发送邮件")
@PostMapping()
public ApiResult<?> send(@RequestBody EmailRecord emailRecord) {
try {
emailRecordService.sendFullTextEmail(emailRecord.getTitle(), emailRecord.getContent(),
emailRecord.getReceiver().split(","));
emailRecord.setCreateUserId(getLoginUserId());
emailRecordService.save(emailRecord);
return success("发送成功");
} catch (MessagingException e) {
e.printStackTrace();
}
return fail("发送失败");
}
}

View File

@ -0,0 +1,200 @@
package com.eleadmin.common.system.controller;
import cn.hutool.core.util.StrUtil;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.config.ConfigProperties;
import com.eleadmin.common.core.utils.FileServerUtil;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.common.system.entity.FileRecord;
import com.eleadmin.common.system.param.FileRecordParam;
import com.eleadmin.common.system.service.FileRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:24
*/
@Api(tags = "文件上传下载")
@RestController
@RequestMapping("/api/file")
public class FileController extends BaseController {
@Resource
private ConfigProperties config;
@Resource
private FileRecordService fileRecordService;
@PreAuthorize("hasAuthority('sys:file:upload')")
@OperationLog
@ApiOperation("上传文件")
@PostMapping("/upload")
public ApiResult<FileRecord> upload(@RequestParam MultipartFile file, HttpServletRequest request) {
FileRecord result = null;
try {
String dir = getUploadDir();
File upload = FileServerUtil.upload(file, dir, config.getUploadUuidName());
String path = upload.getAbsolutePath()
.replace("\\", "/")
.substring(dir.length() - 1)
.replace("\\", "/");
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/upload");
String originalName = file.getOriginalFilename();
result = new FileRecord();
result.setCreateUserId(getLoginUserId());
result.setName(StrUtil.isBlank(originalName) ? upload.getName() : originalName);
result.setLength(upload.length());
result.setPath(path);
result.setUrl(requestURL + "/" + path);
result.setThumbnail(FileServerUtil.isImage(upload) ? (requestURL + "/thumbnail/" + path) : null);
fileRecordService.save(result);
return success(result);
} catch (Exception e) {
e.printStackTrace();
return fail("上传失败", result).setError(e.toString());
}
}
@PreAuthorize("hasAuthority('sys:file:upload')")
@OperationLog
@ApiOperation("上传base64文件")
@ApiImplicitParams({
@ApiImplicitParam(name = "base64", value = "base64", required = true, dataType = "string"),
@ApiImplicitParam(name = "fileName", value = "文件名称", dataType = "string")
})
@PostMapping("/upload/base64")
public ApiResult<FileRecord> uploadBase64(String base64, String fileName, HttpServletRequest request) {
FileRecord result = null;
try {
String dir = getUploadDir();
File upload = FileServerUtil.upload(base64, fileName, getUploadDir());
String path = upload.getAbsolutePath().substring(dir.length()).replace("\\", "/");
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/upload/base64");
result = new FileRecord();
result.setCreateUserId(getLoginUserId());
result.setName(StrUtil.isBlank(fileName) ? upload.getName() : fileName);
result.setLength(upload.length());
result.setPath(path);
result.setUrl(requestURL + path);
result.setThumbnail(FileServerUtil.isImage(upload) ? (requestURL + "/thumbnail" + path) : null);
fileRecordService.save(result);
return success(result);
} catch (Exception e) {
e.printStackTrace();
return fail("上传失败", result).setError(e.toString());
}
}
@ApiOperation("查看原文件")
@GetMapping("/{dir}/{name:.+}")
public void preview(@PathVariable("dir") String dir, @PathVariable("name") String name,
HttpServletResponse response, HttpServletRequest request) {
File file = new File(getUploadDir(), dir + "/" + name);
FileServerUtil.preview(file, getPdfOutDir(), config.getOpenOfficeHome(), response, request);
}
@ApiOperation("下载原文件")
@GetMapping("/download/{dir}/{name:.+}")
public void download(@PathVariable("dir") String dir, @PathVariable("name") String name,
HttpServletResponse response, HttpServletRequest request) {
File file = new File(getUploadDir(), dir + "/" + name);
FileServerUtil.preview(file, true, null, null, response, request);
}
@ApiOperation("查看缩略图")
@GetMapping("/thumbnail/{dir}/{name:.+}")
public void thumbnail(@PathVariable("dir") String dir, @PathVariable("name") String name,
HttpServletResponse response, HttpServletRequest request) {
File file = new File(getUploadDir(), dir + "/" + name);
File thumbnail = new File(getUploadSmDir(), dir + "/" + name);
FileServerUtil.previewThumbnail(file, thumbnail, config.getThumbnailSize(), response, request);
}
@PreAuthorize("hasAuthority('sys:file:remove')")
@OperationLog
@ApiOperation("删除文件")
@DeleteMapping("/remove/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (fileRecordService.removeById(id)) {
FileRecord record = fileRecordService.getById(id);
if (StrUtil.isNotBlank(record.getPath())) {
new File(getUploadDir(), record.getPath()).delete();
new File(getUploadSmDir(), record.getPath()).delete();
}
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:file:list')")
@OperationLog
@ApiOperation("分页查询文件")
@GetMapping("/page")
public ApiResult<PageResult<FileRecord>> page(FileRecordParam param, HttpServletRequest request) {
PageResult<FileRecord> result = fileRecordService.pageRel(param);
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/page");
for (FileRecord record : result.getList()) {
record.setUrl(requestURL + record.getPath());
record.setThumbnail(requestURL + "/thumbnail" + record.getPath());
}
return success(result);
}
@PreAuthorize("hasAuthority('sys:file:list')")
@OperationLog
@ApiOperation("查询全部文件")
@GetMapping("/list")
public ApiResult<List<FileRecord>> list(FileRecordParam param, HttpServletRequest request) {
List<FileRecord> records = fileRecordService.listRel(param);
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/list");
for (FileRecord record : records) {
record.setUrl(requestURL + record.getPath());
record.setThumbnail(requestURL + "/thumbnail" + record.getPath());
}
return success(records);
}
/**
*
*/
private String getUploadBaseDir() {
return File.listRoots()[config.getUploadLocation()].getAbsolutePath()
.replace("\\", "/") + "/upload/";
}
/**
*
*/
private String getUploadDir() {
return getUploadBaseDir() + "file/";
}
/**
*
*/
private String getUploadSmDir() {
return getUploadBaseDir() + "thumbnail/";
}
/**
* officepdf
*/
private String getPdfOutDir() {
return getUploadBaseDir() + "pdf/";
}
}

View File

@ -0,0 +1,58 @@
package com.eleadmin.common.system.controller;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.common.system.entity.LoginRecord;
import com.eleadmin.common.system.param.LoginRecordParam;
import com.eleadmin.common.system.service.LoginRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:31
*/
@Api(tags = "登录日志")
@RestController
@RequestMapping("/api/system/login-record")
public class LoginRecordController extends BaseController {
@Resource
private LoginRecordService loginRecordService;
@PreAuthorize("hasAuthority('sys:login-record:view')")
@OperationLog
@ApiOperation("分页查询登录日志")
@GetMapping("/page")
public ApiResult<PageResult<LoginRecord>> page(LoginRecordParam param) {
return success(loginRecordService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:login-record:view')")
@OperationLog
@ApiOperation("查询全部登录日志")
@GetMapping()
public ApiResult<List<LoginRecord>> list(LoginRecordParam param) {
return success(loginRecordService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:login-record:view')")
@OperationLog
@ApiOperation("根据id查询登录日志")
@GetMapping("/{id}")
public ApiResult<LoginRecord> get(@PathVariable("id") Integer id) {
return success(loginRecordService.getByIdRel(id));
}
}

View File

@ -0,0 +1,140 @@
package com.eleadmin.common.system.controller;
import cn.hutool.core.util.StrUtil;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.config.ConfigProperties;
import com.eleadmin.common.core.security.JwtSubject;
import com.eleadmin.common.core.security.JwtUtil;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.system.entity.LoginRecord;
import com.eleadmin.common.system.entity.Menu;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.result.CaptchaResult;
import com.eleadmin.common.system.param.LoginParam;
import com.eleadmin.common.system.result.LoginResult;
import com.eleadmin.common.system.param.UpdatePasswordParam;
import com.eleadmin.common.system.service.LoginRecordService;
import com.eleadmin.common.system.service.RoleMenuService;
import com.eleadmin.common.system.service.UserService;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:11
*/
@Api(tags = "登录认证")
@RestController
@RequestMapping("/api")
public class MainController extends BaseController {
@Resource
private ConfigProperties configProperties;
@Resource
private UserService userService;
@Resource
private RoleMenuService roleMenuService;
@Resource
private LoginRecordService loginRecordService;
@ApiOperation("用户登录")
@PostMapping("/login")
public ApiResult<LoginResult> login(@RequestBody LoginParam param, HttpServletRequest request) {
String username = param.getUsername();
Integer tenantId = param.getTenantId();
User user = userService.getByUsername(username, tenantId);
if (user == null) {
String message = "账号不存在";
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
return fail(message, null);
}
if (!user.getStatus().equals(0)) {
String message = "账号被冻结";
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
return fail(message, null);
}
if (!userService.comparePassword(user.getPassword(), param.getPassword())) {
String message = "密码错误";
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
return fail(message, null);
}
loginRecordService.saveAsync(username, LoginRecord.TYPE_LOGIN, null, tenantId, request);
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(username, tenantId),
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, user));
}
@ApiOperation("获取登录用户信息")
@GetMapping("/auth/user")
public ApiResult<User> userInfo() {
return success(userService.getByIdRel(getLoginUserId()));
}
@ApiOperation("获取登录用户菜单")
@GetMapping("/auth/menu")
public ApiResult<List<Menu>> userMenu() {
List<Menu> menus = roleMenuService.listMenuByUserId(getLoginUserId(), Menu.TYPE_MENU);
return success(CommonUtil.toTreeData(menus, 0, Menu::getParentId, Menu::getMenuId, Menu::setChildren));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@OperationLog
@ApiOperation("修改个人信息")
@PutMapping("/auth/user")
public ApiResult<User> updateInfo(@RequestBody User user) {
user.setUserId(getLoginUserId());
// 不能修改的字段
user.setUsername(null);
user.setPassword(null);
user.setEmailVerified(null);
user.setOrganizationId(null);
user.setStatus(null);
if (userService.updateById(user)) {
return success(userService.getByIdRel(user.getUserId()));
}
return fail("保存失败", null);
}
@PreAuthorize("hasAuthority('sys:auth:password')")
@OperationLog
@ApiOperation("修改自己密码")
@PutMapping("/auth/password")
public ApiResult<?> updatePassword(@RequestBody UpdatePasswordParam param) {
if (StrUtil.hasBlank(param.getOldPassword(), param.getPassword())) {
return fail("参数不能为空");
}
Integer userId = getLoginUserId();
if (userId == null) {
return fail("未登录");
}
if (!userService.comparePassword(userService.getById(userId).getPassword(), param.getOldPassword())) {
return fail("原密码输入不正确");
}
User user = new User();
user.setUserId(userId);
user.setPassword(userService.encodePassword(param.getPassword()));
if (userService.updateById(user)) {
return success("修改成功");
}
return fail("修改失败");
}
@ApiOperation("图形验证码")
@GetMapping("/captcha")
public ApiResult<CaptchaResult> captcha() {
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
return success(new CaptchaResult(specCaptcha.toBase64(), specCaptcha.text().toLowerCase()));
}
}

View File

@ -0,0 +1,123 @@
package com.eleadmin.common.system.controller;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.*;
import com.eleadmin.common.system.entity.Menu;
import com.eleadmin.common.system.param.MenuParam;
import com.eleadmin.common.system.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:23
*/
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/api/system/menu")
public class MenuController extends BaseController {
@Resource
private MenuService menuService;
@PreAuthorize("hasAuthority('sys:menu:list')")
@OperationLog
@ApiOperation("分页查询菜单")
@GetMapping("/page")
public ApiResult<PageResult<Menu>> page(MenuParam param) {
PageParam<Menu, MenuParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(menuService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:menu:list')")
@OperationLog
@ApiOperation("查询全部菜单")
@GetMapping()
public ApiResult<List<Menu>> list(MenuParam param) {
PageParam<Menu, MenuParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(menuService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:menu:list')")
@OperationLog
@ApiOperation("根据id查询菜单")
@GetMapping("/{id}")
public ApiResult<Menu> get(@PathVariable("id") Integer id) {
return success(menuService.getById(id));
}
@PreAuthorize("hasAuthority('sys:menu:save')")
@OperationLog
@ApiOperation("添加菜单")
@PostMapping()
public ApiResult<?> add(@RequestBody Menu menu) {
if (menuService.save(menu)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@OperationLog
@ApiOperation("修改菜单")
@PutMapping()
public ApiResult<?> update(@RequestBody Menu menu) {
if (menuService.updateById(menu)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:menu:remove')")
@OperationLog
@ApiOperation("删除菜单")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (menuService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:menu:save')")
@OperationLog
@ApiOperation("批量添加菜单")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Menu> menus) {
if (menuService.saveBatch(menus)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@OperationLog
@ApiOperation("批量修改菜单")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<Menu> batchParam) {
if (batchParam.update(menuService, "menu_id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:menu:remove')")
@OperationLog
@ApiOperation("批量删除菜单")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (menuService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@ -0,0 +1,62 @@
package com.eleadmin.common.system.controller;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.common.system.entity.OperationRecord;
import com.eleadmin.common.system.param.OperationRecordParam;
import com.eleadmin.common.system.service.OperationRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:12
*/
@Api(tags = "操作日志")
@RestController
@RequestMapping("/api/system/operation-record")
public class OperationRecordController extends BaseController {
@Resource
private OperationRecordService operationRecordService;
/**
*
*/
@PreAuthorize("hasAuthority('sys:operation-record:view')")
@ApiOperation("分页查询操作日志")
@GetMapping("/page")
public ApiResult<PageResult<OperationRecord>> page(OperationRecordParam param) {
return success(operationRecordService.pageRel(param));
}
/**
*
*/
@PreAuthorize("hasAuthority('sys:operation-record:view')")
@OperationLog
@ApiOperation("查询全部操作日志")
@GetMapping()
public ApiResult<List<OperationRecord>> list(OperationRecordParam param) {
return success(operationRecordService.listRel(param));
}
/**
* id
*/
@PreAuthorize("hasAuthority('sys:operation-record:view')")
@ApiOperation("根据id查询操作日志")
@GetMapping("/{id}")
public ApiResult<OperationRecord> get(@PathVariable("id") Integer id) {
return success(operationRecordService.getByIdRel(id));
}
}

View File

@ -0,0 +1,139 @@
package com.eleadmin.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.*;
import com.eleadmin.common.system.entity.Organization;
import com.eleadmin.common.system.param.OrganizationParam;
import com.eleadmin.common.system.service.OrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
@Api(tags = "组织机构管理")
@RestController
@RequestMapping("/api/system/organization")
public class OrganizationController extends BaseController {
@Resource
private OrganizationService organizationService;
@PreAuthorize("hasAuthority('sys:org:list')")
@OperationLog
@ApiOperation("分页查询组织机构")
@GetMapping("/page")
public ApiResult<PageResult<Organization>> page(OrganizationParam param) {
return success(organizationService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:org:list')")
@OperationLog
@ApiOperation("查询全部组织机构")
@GetMapping()
public ApiResult<List<Organization>> list(OrganizationParam param) {
return success(organizationService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:org:list')")
@OperationLog
@ApiOperation("根据id查询组织机构")
@GetMapping("/{id}")
public ApiResult<Organization> get(@PathVariable("id") Integer id) {
return success(organizationService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:org:save')")
@OperationLog
@ApiOperation("添加组织机构")
@PostMapping()
public ApiResult<?> add(@RequestBody Organization organization) {
if (organization.getParentId() == null) {
organization.setParentId(0);
}
if (organizationService.count(new LambdaQueryWrapper<Organization>()
.eq(Organization::getOrganizationName, organization.getOrganizationName())
.eq(Organization::getParentId, organization.getParentId())) > 0) {
return fail("机构名称已存在");
}
if (organizationService.save(organization)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:org:update')")
@OperationLog
@ApiOperation("修改组织机构")
@PutMapping()
public ApiResult<?> update(@RequestBody Organization organization) {
if (organization.getOrganizationName() != null) {
if (organization.getParentId() == null) {
organization.setParentId(0);
}
if (organizationService.count(new LambdaQueryWrapper<Organization>()
.eq(Organization::getOrganizationName, organization.getOrganizationName())
.eq(Organization::getParentId, organization.getParentId())
.ne(Organization::getOrganizationId, organization.getOrganizationId())) > 0) {
return fail("机构名称已存在");
}
}
if (organizationService.updateById(organization)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:org:remove')")
@OperationLog
@ApiOperation("删除组织机构")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (organizationService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:org:save')")
@OperationLog
@ApiOperation("批量添加组织机构")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Organization> organizationList) {
if (organizationService.saveBatch(organizationList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:org:update')")
@OperationLog
@ApiOperation("批量修改组织机构")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<Organization> batchParam) {
if (batchParam.update(organizationService, Organization::getOrganizationId)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:org:remove')")
@OperationLog
@ApiOperation("批量删除组织机构")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (organizationService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@ -0,0 +1,152 @@
package com.eleadmin.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.web.PageParam;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.common.system.entity.Role;
import com.eleadmin.common.system.param.RoleParam;
import com.eleadmin.common.system.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:02
*/
@Api(tags = "角色管理")
@RestController
@RequestMapping("/api/system/role")
public class RoleController extends BaseController {
@Resource
private RoleService roleService;
@PreAuthorize("hasAuthority('sys:role:list')")
@OperationLog
@ApiOperation("分页查询角色")
@GetMapping("/page")
public ApiResult<PageResult<Role>> page(RoleParam param) {
PageParam<Role, RoleParam> page = new PageParam<>(param);
return success(roleService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:role:list')")
@OperationLog
@ApiOperation("查询全部角色")
@GetMapping()
public ApiResult<List<Role>> list(RoleParam param) {
PageParam<Role, RoleParam> page = new PageParam<>(param);
return success(roleService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:role:list')")
@OperationLog
@ApiOperation("根据id查询角色")
@GetMapping("/{id}")
public ApiResult<Role> get(@PathVariable("id") Integer id) {
return success(roleService.getById(id));
}
@PreAuthorize("hasAuthority('sys:role:save')")
@OperationLog
@ApiOperation("添加角色")
@PostMapping()
public ApiResult<?> save(@RequestBody Role role) {
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, role.getRoleCode())) > 0) {
return fail("角色标识已存在");
}
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, role.getRoleName())) > 0) {
return fail("角色名称已存在");
}
if (roleService.save(role)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:role:update')")
@OperationLog
@ApiOperation("修改角色")
@PutMapping()
public ApiResult<?> update(@RequestBody Role role) {
if (role.getRoleCode() != null && roleService.count(new LambdaQueryWrapper<Role>()
.eq(Role::getRoleCode, role.getRoleCode())
.ne(Role::getRoleId, role.getRoleId())) > 0) {
return fail("角色标识已存在");
}
if (role.getRoleName() != null && roleService.count(new LambdaQueryWrapper<Role>()
.eq(Role::getRoleName, role.getRoleName())
.ne(Role::getRoleId, role.getRoleId())) > 0) {
return fail("角色名称已存在");
}
if (roleService.updateById(role)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:role:remove')")
@OperationLog
@ApiOperation("删除角色")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (roleService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:role:save')")
@OperationLog
@ApiOperation("批量添加角色")
@PostMapping("/batch")
public ApiResult<List<String>> saveBatch(@RequestBody List<Role> list) {
// 校验是否重复
if (CommonUtil.checkRepeat(list, Role::getRoleName)) {
return fail("角色名称存在重复", null);
}
if (CommonUtil.checkRepeat(list, Role::getRoleCode)) {
return fail("角色标识存在重复", null);
}
// 校验是否存在
List<Role> codeExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleCode,
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
if (codeExists.size() > 0) {
return fail("角色标识已存在", codeExists.stream().map(Role::getRoleCode)
.collect(Collectors.toList())).setCode(2);
}
List<Role> nameExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleName,
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
if (nameExists.size() > 0) {
return fail("角色标识已存在", nameExists.stream().map(Role::getRoleCode)
.collect(Collectors.toList())).setCode(3);
}
if (roleService.saveBatch(list)) {
return success("添加成功", null);
}
return fail("添加失败", null);
}
@PreAuthorize("hasAuthority('sys:role:remove')")
@OperationLog
@ApiOperation("批量删除角色")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (roleService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@ -0,0 +1,100 @@
package com.eleadmin.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.exception.BusinessException;
import com.eleadmin.common.system.entity.Menu;
import com.eleadmin.common.system.entity.RoleMenu;
import com.eleadmin.common.system.service.MenuService;
import com.eleadmin.common.system.service.RoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:01
*/
@Api(tags = "角色菜单管理")
@RestController
@RequestMapping("/api/system/role-menu")
public class RoleMenuController extends BaseController {
@Resource
private RoleMenuService roleMenuService;
@Resource
private MenuService menuService;
@PreAuthorize("hasAuthority('sys:role:list')")
@OperationLog
@ApiOperation("查询角色菜单")
@GetMapping("/{id}")
public ApiResult<List<Menu>> list(@PathVariable("id") Integer roleId) {
List<Menu> menus = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSortNumber));
List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
.eq(RoleMenu::getRoleId, roleId));
for (Menu menu : menus) {
menu.setChecked(roleMenus.stream().anyMatch((d) -> d.getMenuId().equals(menu.getMenuId())));
}
return success(menus);
}
@Transactional(rollbackFor = {Exception.class})
@PreAuthorize("hasAuthority('sys:role:update')")
@OperationLog
@ApiOperation("修改角色菜单")
@PutMapping("/{id}")
public ApiResult<?> update(@PathVariable("id") Integer roleId, @RequestBody List<Integer> menuIds) {
roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
if (menuIds != null && menuIds.size() > 0) {
List<RoleMenu> roleMenuList = new ArrayList<>();
for (Integer menuId : menuIds) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenuList.add(roleMenu);
}
if (!roleMenuService.saveBatch(roleMenuList)) {
throw new BusinessException("保存失败");
}
}
return success("保存成功");
}
@PreAuthorize("hasAuthority('sys:role:update')")
@OperationLog
@ApiOperation("添加角色菜单")
@PostMapping("/{id}")
public ApiResult<?> addRoleAuth(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
if (roleMenuService.save(roleMenu)) {
return success();
}
return fail();
}
@PreAuthorize("hasAuthority('sys:role:update')")
@OperationLog
@ApiOperation("移除角色菜单")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
if (roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>()
.eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMenuId, menuId))) {
return success();
}
return fail();
}
}

View File

@ -0,0 +1,298 @@
package com.eleadmin.common.system.controller;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.*;
import com.eleadmin.common.system.entity.DictionaryData;
import com.eleadmin.common.system.entity.Organization;
import com.eleadmin.common.system.entity.Role;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.param.UserImportParam;
import com.eleadmin.common.system.param.UserParam;
import com.eleadmin.common.system.service.DictionaryDataService;
import com.eleadmin.common.system.service.OrganizationService;
import com.eleadmin.common.system.service.RoleService;
import com.eleadmin.common.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:41
*/
@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/system/user")
public class UserController extends BaseController {
@Resource
private UserService userService;
@Resource
private RoleService roleService;
@Resource
private OrganizationService organizationService;
@Resource
private DictionaryDataService dictionaryDataService;
@PreAuthorize("hasAuthority('sys:user:list')")
@OperationLog
@ApiOperation("分页查询用户")
@GetMapping("/page")
public ApiResult<PageResult<User>> page(UserParam param) {
return success(userService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:user:list')")
@OperationLog
@ApiOperation("查询全部用户")
@GetMapping()
public ApiResult<List<User>> list(UserParam param) {
return success(userService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:user:list')")
@OperationLog
@ApiOperation("根据id查询用户")
@GetMapping("/{id}")
public ApiResult<User> get(@PathVariable("id") Integer id) {
return success(userService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:user:save')")
@OperationLog
@ApiOperation("添加用户")
@PostMapping()
public ApiResult<?> add(@RequestBody User user) {
user.setStatus(0);
user.setPassword(userService.encodePassword(user.getPassword()));
if (userService.saveUser(user)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("修改用户")
@PutMapping()
public ApiResult<?> update(@RequestBody User user) {
user.setStatus(null);
user.setUsername(null);
user.setPassword(null);
if (userService.updateUser(user)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:remove')")
@OperationLog
@ApiOperation("删除用户")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (userService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("批量修改用户")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<User> batchParam) {
if (batchParam.update(userService, User::getUserId)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:remove')")
@OperationLog
@ApiOperation("批量删除用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "id数组", required = true, dataType = "string")
})
@DeleteMapping("/batch")
public ApiResult<?> deleteBatch(@RequestBody List<Integer> ids) {
if (userService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("修改用户状态")
@PutMapping("/status")
public ApiResult<?> updateStatus(@RequestBody User user) {
if (user.getUserId() == null || user.getStatus() == null || !Arrays.asList(0, 1).contains(user.getStatus())) {
return fail("参数不正确");
}
User u = new User();
u.setUserId(user.getUserId());
u.setStatus(user.getStatus());
if (userService.updateById(u)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("批量修改用户状态")
@PutMapping("/status/batch")
public ApiResult<?> updateStatusBatch(@RequestBody BatchParam<Integer> batchParam) {
if (!Arrays.asList(0, 1).contains(batchParam.getData())) {
return fail("状态值不正确");
}
if (userService.update(new LambdaUpdateWrapper<User>()
.in(User::getUserId, batchParam.getIds())
.set(User::getStatus, batchParam.getData()))) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("重置密码")
@PutMapping("/password")
public ApiResult<?> resetPassword(@RequestBody User user) {
if (user.getUserId() == null || StrUtil.isBlank(user.getPassword())) {
return fail("参数不正确");
}
User u = new User();
u.setUserId(user.getUserId());
u.setPassword(userService.encodePassword(user.getPassword()));
if (userService.updateById(u)) {
return success("重置成功");
} else {
return fail("重置失败");
}
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@ApiOperation("批量重置密码")
@PutMapping("/password/batch")
public ApiResult<?> resetPasswordBatch(@RequestBody BatchParam<String> batchParam) {
if (batchParam.getIds() == null || batchParam.getIds().size() == 0) {
return fail("请选择用户");
}
if (batchParam.getData() == null) {
return fail("请输入密码");
}
if (userService.update(new LambdaUpdateWrapper<User>()
.in(User::getUserId, batchParam.getIds())
.set(User::getPassword, userService.encodePassword(batchParam.getData())))) {
return success("重置成功");
} else {
return fail("重置失败");
}
}
@PreAuthorize("hasAuthority('sys:user:list')")
@OperationLog
@ApiOperation("检查用户是否存在")
@GetMapping("/existence")
public ApiResult<?> existence(ExistenceParam<User> param) {
if (param.isExistence(userService, User::getUserId)) {
return success(param.getValue() + "已存在");
}
return fail(param.getValue() + "不存在");
}
/**
* excel
*/
@PreAuthorize("hasAuthority('sys:user:save')")
@OperationLog
@ApiOperation("导入用户")
@Transactional(rollbackFor = {Exception.class})
@PostMapping("/import")
public ApiResult<List<String>> importBatch(MultipartFile file) {
ImportParams importParams = new ImportParams();
try {
List<UserImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(),
UserImportParam.class, importParams);
// 校验是否重复
if (CommonUtil.checkRepeat(list, UserImportParam::getUsername)) {
return fail("账号存在重复", null);
}
if (CommonUtil.checkRepeat(list, UserImportParam::getPhone)) {
return fail("手机号存在重复", null);
}
// 校验是否存在
List<User> usernameExists = userService.list(new LambdaQueryWrapper<User>().in(User::getUsername,
list.stream().map(UserImportParam::getUsername).collect(Collectors.toList())));
if (usernameExists.size() > 0) {
return fail("账号已经存在",
usernameExists.stream().map(User::getUsername).collect(Collectors.toList()));
}
List<User> phoneExists = userService.list(new LambdaQueryWrapper<User>().in(User::getPhone,
list.stream().map(UserImportParam::getPhone).collect(Collectors.toList())));
if (phoneExists.size() > 0) {
return fail("手机号已经存在",
phoneExists.stream().map(User::getPhone).collect(Collectors.toList()));
}
// 添加
List<User> users = new ArrayList<>();
for (UserImportParam one : list) {
User u = new User();
u.setStatus(0);
u.setUsername(one.getUsername());
u.setPassword(userService.encodePassword(one.getPassword()));
u.setNickname(one.getNickname());
u.setPhone(one.getPhone());
Role role = roleService.getOne(new QueryWrapper<Role>()
.eq("role_name", one.getRoleName()), false);
if (role == null) {
return fail("角色不存在", Collections.singletonList(one.getRoleName()));
} else {
u.setRoles(Collections.singletonList(role));
}
Organization organization = organizationService.getOne(new QueryWrapper<Organization>()
.eq("organization_full_name", one.getOrganizationName()), false);
if (organization == null) {
return fail("机构不存在", Collections.singletonList(one.getOrganizationName()));
} else {
u.setOrganizationId(organization.getOrganizationId());
}
DictionaryData sex = dictionaryDataService.getByDictCodeAndName("sex", one.getSexName());
if (sex == null) {
return fail("性别不存在", Collections.singletonList(one.getSexName()));
} else {
u.setSex(sex.getDictDataCode());
}
}
if (userService.saveBatch(users)) {
return success("导入成功", null);
}
} catch (Exception e) {
e.printStackTrace();
}
return fail("导入失败", null);
}
}

View File

@ -0,0 +1,53 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.util.Date;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:03
*/
@Data
@ApiModel(description = "字典")
@TableName("sys_dictionary")
public class Dictionary implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "字典id")
@TableId(type = IdType.AUTO)
private Integer dictId;
@ApiModelProperty(value = "字典标识")
private String dictCode;
@ApiModelProperty(value = "字典名称")
private String dictName;
@ApiModelProperty(value = "排序号")
private Integer sortNumber;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "修改时间")
private Date updateTime;
}

View File

@ -0,0 +1,61 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
@Data
@ApiModel(description = "字典数据")
@TableName("sys_dictionary_data")
public class DictionaryData implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "字典数据id")
@TableId(type = IdType.AUTO)
private Integer dictDataId;
@ApiModelProperty(value = "字典id")
private Integer dictId;
@ApiModelProperty(value = "字典数据标识")
private String dictDataCode;
@ApiModelProperty(value = "字典数据名称")
private String dictDataName;
@ApiModelProperty(value = "排序号")
private Integer sortNumber;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "修改时间")
private Date updateTime;
@ApiModelProperty(value = "字典代码")
@TableField(exist = false)
private String dictCode;
@ApiModelProperty(value = "字典名称")
@TableField(exist = false)
private String dictName;
}

View File

@ -0,0 +1,56 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 12:36:35
*/
@Data
@ApiModel(description = "邮件发送记录")
@TableName("sys_email_record")
public class EmailRecord implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("邮件标题")
private String title;
@ApiModelProperty("邮件内容")
private String content;
@ApiModelProperty("收件邮箱")
private String receiver;
@ApiModelProperty("发件邮箱")
private String sender;
@ApiModelProperty("创建人")
private Integer createUserId;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
}

View File

@ -0,0 +1,70 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 12:36:32
*/
@Data
@ApiModel(description = "文件上传记录")
@TableName("sys_file_record")
public class FileRecord implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("文件名称")
private String name;
@ApiModelProperty("文件存储路径")
private String path;
@ApiModelProperty("文件大小")
private Long length;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("创建人")
private Integer createUserId;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("文件访问地址")
@TableField(exist = false)
private String url;
@ApiModelProperty("文件缩略图访问地址")
@TableField(exist = false)
private String thumbnail;
@ApiModelProperty("创建人账号")
@TableField(exist = false)
private String createUsername;
@ApiModelProperty("创建人名称")
@TableField(exist = false)
private String createNickname;
}

View File

@ -0,0 +1,72 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:41
*/
@Data
@ApiModel(description = "登录日志")
@TableName("sys_login_record")
public class LoginRecord implements Serializable {
private static final long serialVersionUID = 1L;
public static final int TYPE_LOGIN = 0; // 登录成功
public static final int TYPE_ERROR = 1; // 登录失败
public static final int TYPE_LOGOUT = 2; // 退出登录
public static final int TYPE_REFRESH = 3; // 续签token
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("操作系统")
private String os;
@ApiModelProperty("设备名称")
private String device;
@ApiModelProperty("浏览器类型")
private String browser;
@ApiModelProperty("ip地址")
private String ip;
@ApiModelProperty("操作类型, 0登录成功, 1登录失败, 2退出登录, 3续签token")
private Integer loginType;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("操作时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("用户id")
@TableField(exist = false)
private Integer userId;
@ApiModelProperty("用户昵称")
@TableField(exist = false)
private String nickname;
}

View File

@ -0,0 +1,90 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import java.util.Date;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:17
*/
@Data
@ApiModel(description = "菜单")
@TableName("sys_menu")
public class Menu implements GrantedAuthority {
private static final long serialVersionUID = 1L;
public static final int TYPE_MENU = 0; // 菜单类型
public static final int TYPE_BTN = 1; // 按钮类型
@ApiModelProperty("菜单id")
@TableId(type = IdType.AUTO)
private Integer menuId;
@ApiModelProperty("上级id, 0是顶级")
private Integer parentId;
@ApiModelProperty("菜单名称")
private String title;
@ApiModelProperty("菜单路由地址")
private String path;
@ApiModelProperty("菜单组件地址")
private String component;
@ApiModelProperty("菜单类型, 0菜单, 1按钮")
private Integer menuType;
@ApiModelProperty("排序号")
private Integer sortNumber;
@ApiModelProperty("权限标识")
private String authority;
@ApiModelProperty("打开位置")
private String target;
@ApiModelProperty("菜单图标")
private String icon;
@ApiModelProperty("图标颜色")
private String color;
@ApiModelProperty("是否隐藏, 0否, 1是(仅注册路由不显示左侧菜单)")
private Integer hide;
@ApiModelProperty("侧栏菜单选中的path")
private String active;
@ApiModelProperty("路由元信息")
private String meta;
@ApiModelProperty("是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("子菜单")
@TableField(exist = false)
private List<Menu> children;
@ApiModelProperty("角色权限树选中状态")
@TableField(exist = false)
private Boolean checked;
}

View File

@ -0,0 +1,95 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:33
*/
@Data
@ApiModel(description = "操作日志")
@TableName("sys_operation_record")
public class OperationRecord implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("用户id")
private Integer userId;
@ApiModelProperty("操作模块")
private String module;
@ApiModelProperty("操作功能")
private String description;
@ApiModelProperty("请求地址")
private String url;
@ApiModelProperty("请求方式")
private String requestMethod;
@ApiModelProperty("调用方法")
private String method;
@ApiModelProperty("请求参数")
private String params;
@ApiModelProperty("返回结果")
private String result;
@ApiModelProperty("异常信息")
private String error;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("消耗时间, 单位毫秒")
private Long spendTime;
@ApiModelProperty("操作系统")
private String os;
@ApiModelProperty("设备名称")
private String device;
@ApiModelProperty("浏览器类型")
private String browser;
@ApiModelProperty("ip地址")
private String ip;
@ApiModelProperty("状态, 0成功, 1异常")
private Integer status;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("操作时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("用户昵称")
@TableField(exist = false)
private String nickname;
@ApiModelProperty("用户账号")
@TableField(exist = false)
private String username;
}

View File

@ -0,0 +1,77 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
*
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
@Data
@ApiModel(description = "组织机构")
@TableName("sys_organization")
public class Organization implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "机构id")
@TableId(type = IdType.AUTO)
private Integer organizationId;
@ApiModelProperty(value = "上级id, 0是顶级")
private Integer parentId;
@ApiModelProperty(value = "机构名称")
private String organizationName;
@ApiModelProperty(value = "机构全称")
private String organizationFullName;
@ApiModelProperty(value = "机构代码")
private String organizationCode;
@ApiModelProperty(value = "机构类型, 字典标识")
private String organizationType;
@ApiModelProperty(value = "负责人id")
private Integer leaderId;
@ApiModelProperty(value = "排序号")
private Integer sortNumber;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "修改时间")
private Date updateTime;
@ApiModelProperty(value = "机构类型名称")
@TableField(exist = false)
private String organizationTypeName;
@ApiModelProperty(value = "负责人姓名")
@TableField(exist = false)
private String leaderNickname;
@ApiModelProperty(value = "负责人账号")
@TableField(exist = false)
private String leaderUsername;
}

View File

@ -0,0 +1,53 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:01
*/
@Data
@ApiModel(description = "角色")
@TableName("sys_role")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("角色id")
@TableId(type = IdType.AUTO)
private Integer roleId;
@ApiModelProperty("角色标识")
private String roleCode;
@ApiModelProperty("角色名称")
private String roleName;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty(hidden = true)
@TableField(exist = false)
private Integer userId;
}

View File

@ -0,0 +1,44 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:54
*/
@Data
@ApiModel(description = "角色权限")
@TableName("sys_role_menu")
public class RoleMenu implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("角色id")
private Integer roleId;
@ApiModelProperty("菜单id")
private Integer menuId;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
}

View File

@ -0,0 +1,46 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2021-08-28 11:31:06
*/
@Data
@ApiModel(description = "租户")
@TableName("sys_tenant")
public class Tenant implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("租户id")
@TableId(type = IdType.AUTO)
private Integer tenantId;
@ApiModelProperty("租户名称")
private String tenantName;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
}

View File

@ -0,0 +1,121 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Date;
import java.util.List;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:13
*/
@Data
@ApiModel(description = "用户")
@TableName("sys_user")
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
@ApiModelProperty("用户id")
@TableId(type = IdType.AUTO)
private Integer userId;
@ApiModelProperty("账号")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("昵称")
private String nickname;
@ApiModelProperty("头像")
private String avatar;
@ApiModelProperty("性别, 字典标识")
private String sex;
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("邮箱是否验证, 0否, 1是")
private Integer emailVerified;
@ApiModelProperty("真实姓名")
private String realName;
@ApiModelProperty("身份证号")
private String idCard;
@ApiModelProperty("出生日期")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
@ApiModelProperty("个人简介")
private String introduction;
@ApiModelProperty("机构id")
private Integer organizationId;
@ApiModelProperty("状态, 0正常, 1冻结")
private Integer status;
@ApiModelProperty("是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty("注册时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("机构名称")
@TableField(exist = false)
private String organizationName;
@ApiModelProperty("性别名称")
@TableField(exist = false)
private String sexName;
@ApiModelProperty("角色列表")
@TableField(exist = false)
private List<Role> roles;
@ApiModelProperty("权限列表")
@TableField(exist = false)
private List<Menu> authorities;
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return this.status != null && this.status == 0;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@ -0,0 +1,46 @@
package com.eleadmin.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author EleAdmin
* @since 2018-12-24 16:10:23
*/
@Data
@ApiModel(description = "用户角色")
@TableName("sys_user_role")
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("用户id")
private Integer userId;
@ApiModelProperty("角色id")
private Integer roleId;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("修改时间")
private Date updateTime;
@ApiModelProperty("角色名称")
@TableField(exist = false)
private String roleName;
}

View File

@ -0,0 +1,47 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.DictionaryData;
import com.eleadmin.common.system.param.DictionaryDataParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
public interface DictionaryDataMapper extends BaseMapper<DictionaryData> {
/**
*
*
* @param page
* @param param
* @return List<DictionaryData>
*/
List<DictionaryData> selectPageRel(@Param("page") IPage<DictionaryData> page,
@Param("param") DictionaryDataParam param);
/**
*
*
* @param param
* @return List<DictionaryData>
*/
List<DictionaryData> selectListRel(@Param("param") DictionaryDataParam param);
/**
* dictCodedictDataName
*
* @param dictCode
* @param dictDataName
* @return List<DictionaryData>
*/
List<DictionaryData> getByDictCodeAndName(@Param("dictCode") String dictCode,
@Param("dictDataName") String dictDataName);
}

View File

@ -0,0 +1,14 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.Dictionary;
/**
* Mapper
*
* @author EleAdmin
* @since 2020-03-14 11:29:03
*/
public interface DictionaryMapper extends BaseMapper<Dictionary> {
}

View File

@ -0,0 +1,14 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.EmailRecord;
/**
* Mapper
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
public interface EmailRecordMapper extends BaseMapper<EmailRecord> {
}

View File

@ -0,0 +1,37 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.FileRecord;
import com.eleadmin.common.system.param.FileRecordParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2021-08-30 11:18:04
*/
public interface FileRecordMapper extends BaseMapper<FileRecord> {
/**
*
*
* @param page
* @param param
* @return List<FileRecord>
*/
List<FileRecord> selectPageRel(@Param("page") IPage<FileRecord> page,
@Param("param") FileRecordParam param);
/**
*
*
* @param param
* @return List<FileRecord>
*/
List<FileRecord> selectListRel(@Param("param") FileRecordParam param);
}

View File

@ -0,0 +1,48 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.LoginRecord;
import com.eleadmin.common.system.param.LoginRecordParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:11
*/
public interface LoginRecordMapper extends BaseMapper<LoginRecord> {
/**
* ,
*
* @param entity LoginRecord
* @return int
*/
@Override
@InterceptorIgnore(tenantLine = "true")
int insert(LoginRecord entity);
/**
*
*
* @param page
* @param param
* @return List<LoginRecord>
*/
List<LoginRecord> selectPageRel(@Param("page") IPage<LoginRecord> page,
@Param("param") LoginRecordParam param);
/**
*
*
* @param param
* @return List<LoginRecord>
*/
List<LoginRecord> selectListRel(@Param("param") LoginRecordParam param);
}

View File

@ -0,0 +1,14 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.Menu;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:32
*/
public interface MenuMapper extends BaseMapper<Menu> {
}

View File

@ -0,0 +1,48 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.OperationRecord;
import com.eleadmin.common.system.param.OperationRecordParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:03
*/
public interface OperationRecordMapper extends BaseMapper<OperationRecord> {
/**
* ,
*
* @param entity OperationRecord
* @return int
*/
@Override
@InterceptorIgnore(tenantLine = "true")
int insert(OperationRecord entity);
/**
*
*
* @param page
* @param param
* @return List<OperationRecord>
*/
List<OperationRecord> selectPageRel(@Param("page") IPage<OperationRecord> page,
@Param("param") OperationRecordParam param);
/**
*
*
* @param param
* @return List<OperationRecord>
*/
List<OperationRecord> selectListRel(@Param("param") OperationRecordParam param);
}

View File

@ -0,0 +1,37 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.Organization;
import com.eleadmin.common.system.param.OrganizationParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2020-03-14 11:29:04
*/
public interface OrganizationMapper extends BaseMapper<Organization> {
/**
*
*
* @param page
* @param param
* @return List<Organization>
*/
List<Organization> selectPageRel(@Param("page") IPage<Organization> page,
@Param("param") OrganizationParam param);
/**
*
*
* @param param
* @return List<Organization>
*/
List<Organization> selectListRel(@Param("param") OrganizationParam param);
}

View File

@ -0,0 +1,14 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.Role;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:44
*/
public interface RoleMapper extends BaseMapper<Role> {
}

View File

@ -0,0 +1,39 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.Menu;
import com.eleadmin.common.system.entity.RoleMenu;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:21
*/
public interface RoleMenuMapper extends BaseMapper<RoleMenu> {
/**
*
*
* @param userId id
* @param menuType
* @return List<Menu>
*/
@InterceptorIgnore(tenantLine = "true")
List<Menu> listMenuByUserId(@Param("userId") Integer userId, @Param("menuType") Integer menuType);
/**
* id
*
* @param roleIds id
* @param menuType
* @return List<Menu>
*/
@InterceptorIgnore(tenantLine = "true")
List<Menu> listMenuByRoleIds(@Param("roleIds") List<Integer> roleIds, @Param("menuType") Integer menuType);
}

View File

@ -0,0 +1,48 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.param.UserParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:14
*/
public interface UserMapper extends BaseMapper<User> {
/**
*
*
* @param page
* @param param
* @return List<User>
*/
List<User> selectPageRel(@Param("page") IPage<User> page,
@Param("param") UserParam param);
/**
*
*
* @param param
* @return List<User>
*/
List<User> selectListRel(@Param("param") UserParam param);
/**
*
*
* @param username
* @param tenantId id
* @return User
*/
@InterceptorIgnore(tenantLine = "true")
User selectByUsername(@Param("username") String username, @Param("tenantId") Integer tenantId);
}

View File

@ -0,0 +1,45 @@
package com.eleadmin.common.system.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.eleadmin.common.system.entity.Role;
import com.eleadmin.common.system.entity.UserRole;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author EleAdmin
* @since 2018-12-24 16:10:02
*/
public interface UserRoleMapper extends BaseMapper<UserRole> {
/**
*
*
* @param userId id
* @param roleIds id
* @return int
*/
int insertBatch(@Param("userId") Integer userId, @Param("roleIds") List<Integer> roleIds);
/**
* id
*
* @param userId id
* @return List<Role>
*/
@InterceptorIgnore(tenantLine = "true")
List<Role> selectByUserId(@Param("userId") Integer userId);
/**
* id
*
* @param userIds id
* @return List<RoleResult>
*/
List<Role> selectByUserIds(@Param("userIds") List<Integer> userIds);
}

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.eleadmin.common.system.mapper.DictionaryDataMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.dict_code,
b.dict_name
FROM sys_dictionary_data a
LEFT JOIN sys_dictionary b ON a.dict_id = b.dict_id
<where>
AND a.deleted = 0
<if test="param.dictDataId != null">
AND a.dict_data_id = #{param.dictDataId}
</if>
<if test="param.dictId != null">
AND a.dict_id = #{param.dictId}
</if>
<if test="param.dictDataCode != null">
AND a.dict_data_code LIKE CONCAT('%', #{param.dictDataCode}, '%')
</if>
<if test="param.dictDataName != null">
AND a.dict_data_name LIKE CONCAT('%', #{param.dictDataName}, '%')
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.dictCode != null">
AND b.dict_code = #{param.dictCode}
</if>
<if test="param.dictName != null">
AND b.dict_name = #{param.dictName}
</if>
<if test="param.keywords != null">
AND (
a.dict_data_code LIKE CONCAT('%', #{param.keywords}, '%')
OR a.dict_data_name LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.DictionaryData">
<include refid="selectSql"/>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.DictionaryData">
<include refid="selectSql"/>
</select>
<!-- 根据dictCode和dictDataName查询 -->
<select id="getByDictCodeAndName" resultType="com.eleadmin.common.system.entity.DictionaryData">
SELECT a.*,
b.dict_code,
b.dict_name
FROM sys_dictionary_data a
LEFT JOIN sys_dictionary b ON a.dict_id = b.dict_id
WHERE a.dict_data_name = #{dictDataName}
AND b.dict_code = #{dictCode}
</select>
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.eleadmin.common.system.mapper.DictionaryMapper">
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.eleadmin.common.system.mapper.EmailRecordMapper">
</mapper>

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.FileRecordMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.username create_username,
b.nickname create_nickname
FROM sys_file_record a
LEFT JOIN sys_user b ON a.create_user_id = b.user_id
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.name != null">
AND a.name LIKE CONCAT('%', #{param.name}, '%')
</if>
<if test="param.path != null">
AND a.path LIKE CONCAT('%', #{param.path}, '%')
</if>
<if test="param.createUserId != null">
AND a.create_user_id = #{param.createUserId}
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.createUsername != null">
AND b.username = #{param.createUsername}
</if>
<if test="param.createNickname != null">
AND b.nickname LIKE CONCAT('%', #{param.createNickname}, '%')
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.FileRecord">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.FileRecord">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.LoginRecordMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.user_id,
b.nickname
FROM sys_login_record a
LEFT JOIN sys_user b ON a.username = b.username
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.username != null">
AND a.username LIKE CONCAT('%', #{param.username}, '%')
</if>
<if test="param.os != null">
AND a.os LIKE CONCAT('%', #{param.os}, '%')
</if>
<if test="param.device != null">
AND a.device LIKE CONCAT('%', #{param.device}, '%')
</if>
<if test="param.browser != null">
AND a.browser LIKE CONCAT('%', #{param.browser}, '%')
</if>
<if test="param.ip != null">
AND a.ip LIKE CONCAT('%', #{param.ip}, '%')
</if>
<if test="param.loginType != null">
AND a.login_type LIKE CONCAT('%', #{param.loginType}, '%')
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.userId != null">
AND b.user_id = #{param.userId}
</if>
<if test="param.nickname != null">
AND b.nickname LIKE CONCAT('%', #{param.nickname}, '%')
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.LoginRecord">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.LoginRecord">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.MenuMapper">
</mapper>

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.OperationRecordMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.nickname,
b.username
FROM sys_operation_record a
LEFT JOIN sys_user b ON a.user_id = b.user_id
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.module != null">
AND a.module LIKE CONCAT('%', #{param.module}, '%')
</if>
<if test="param.description != null">
AND a.description LIKE CONCAT('%', #{param.description}, '%')
</if>
<if test="param.url != null">
AND a.url LIKE CONCAT('%', #{param.url}, '%')
</if>
<if test="param.requestMethod != null">
AND a.request_method = #{param.requestMethod}
</if>
<if test="param.method != null">
AND a.method LIKE CONCAT('%', #{param.method}, '%')
</if>
<if test="param.description != null">
AND a.description LIKE CONCAT('%', #{param.description}, '%')
</if>
<if test="param.ip != null">
AND a.ip LIKE CONCAT('%', #{param.ip}, '%')
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.username != null">
AND b.username LIKE CONCAT('%', #{param.username}, '%')
</if>
<if test="param.nickname != null">
AND b.nickname LIKE CONCAT('%', #{param.nickname}, '%')
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.OperationRecord">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.OperationRecord">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.eleadmin.common.system.mapper.OrganizationMapper">
<!-- 机构类型字典查询sql -->
<sql id="selectOrgTypeDictSql">
SELECT ta.*
FROM sys_dictionary_data ta
LEFT JOIN sys_dictionary tb
ON ta.dict_id = tb.dict_id
AND tb.deleted = 0
WHERE ta.deleted = 0
AND tb.dict_code = 'organization_type'
</sql>
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.dict_data_name organization_type_name,
c.nickname leader_nickname,
c.username leader_username
FROM sys_organization a
LEFT JOIN (
<include refid="selectOrgTypeDictSql"/>
) b ON a.organization_type = b.dict_data_code
LEFT JOIN sys_user c ON a.leader_id = c.user_id
<where>
AND a.deleted = 0
<if test="param.organizationId != null">
AND a.organization_id = #{param.organizationId}
</if>
<if test="param.parentId != null">
AND a.parent_id = #{param.parentId}
</if>
<if test="param.organizationName != null">
AND a.organization_name LIKE CONCAT('%', #{param.organizationName}, '%')
</if>
<if test="param.organizationFullName != null">
AND a.organization_full_name LIKE CONCAT('%', #{param.organizationFullName}, '%')
</if>
<if test="param.organizationCode != null">
AND a.organization_code LIKE CONCAT('%', #{param.organizationCode}, '%')
</if>
<if test="param.organizationType != null">
AND a.organization_type = #{param.organizationType}
</if>
<if test="param.leaderId != null">
AND a.leader_id = #{param.leaderId}
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.organizationTypeName != null">
AND b.dict_data_name LIKE CONCAT('%', #{param.organizationTypeName}, '%')
</if>
<if test="param.leaderNickname != null">
AND c.nickname LIKE CONCAT('%', #{param.leaderNickname}, '%')
</if>
<if test="param.leaderUsername != null">
AND c.username LIKE CONCAT('%', #{param.leaderUsername}, '%')
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.Organization">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.Organization">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.RoleMapper">
</mapper>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.RoleMenuMapper">
<!-- 查询用户的菜单 -->
<select id="listMenuByUserId" resultType="com.eleadmin.common.system.entity.Menu">
SELECT a.*
FROM sys_menu a
<where>
AND a.menu_id IN (
SELECT menu_id FROM sys_role_menu WHERE role_id IN (
SELECT ta.role_id FROM sys_user_role ta LEFT JOIN sys_role tb ON ta.role_id = tb.role_id
WHERE ta.user_id = #{userId} AND tb.deleted = 0
)
)
<if test="menuType != null">
AND a.menu_type = #{menuType}
</if>
AND a.deleted = 0
</where>
ORDER BY a.sort_number
</select>
<!-- 根据角色id查询菜单 -->
<select id="listMenuByRoleIds" resultType="com.eleadmin.common.system.entity.Menu">
SELECT a.*
FROM sys_menu a
<where>
AND a.menu_id IN (SELECT menu_id FROM sys_role_menu WHERE role_id IN
<foreach collection="roleIds" item="roleId" separator="," open="(" close=")">
#{roleId}
</foreach>
)
<if test="menuType != null">
AND a.menu_type = #{menuType}
</if>
AND a.deleted = 0
</where>
ORDER BY a.sort_number
</select>
</mapper>

View File

@ -0,0 +1,140 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.UserMapper">
<!-- 性别字典查询sql -->
<sql id="selectSexDictSql">
SELECT ta.*
FROM sys_dictionary_data ta
LEFT JOIN sys_dictionary tb
ON ta.dict_id = tb.dict_id
AND tb.deleted = 0
WHERE ta.deleted = 0
AND tb.dict_code = 'sex'
</sql>
<!-- 用户角色查询sql -->
<sql id="selectUserRoleSql">
SELECT a.user_id,
GROUP_CONCAT(b.role_name) role_name
FROM sys_user_role a
LEFT JOIN sys_role b ON a.role_id = b.role_id
GROUP BY a.user_id
</sql>
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*,
b.organization_name,
c.dict_data_name sex_name
FROM sys_user a
LEFT JOIN sys_organization b ON a.organization_id = b.organization_id
LEFT JOIN (
<include refid="selectSexDictSql"/>
) c ON a.sex = c.dict_data_code
LEFT JOIN(
<include refid="selectUserRoleSql"/>
) d ON a.user_id = d.user_id
<where>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.username != null">
AND a.username LIKE CONCAT('%', #{param.username}, '%')
</if>
<if test="param.nickname != null">
AND a.nickname LIKE CONCAT('%', #{param.nickname}, '%')
</if>
<if test="param.sex != null">
AND a.sex = #{param.sex}
</if>
<if test="param.phone != null">
AND a.phone LIKE CONCAT('%', #{param.phone}, '%')
</if>
<if test="param.email != null">
AND a.email LIKE CONCAT('%', #{param.email}, '%')
</if>
<if test="param.emailVerified != null">
AND a.email_verified = #{param.emailVerified}
</if>
<if test="param.realName != null">
AND a.real_name LIKE CONCAT('%', #{param.realName}, '%')
</if>
<if test="param.idCard != null">
AND a.id_card LIKE CONCAT('%', #{param.idCard}, '%')
</if>
<if test="param.birthday != null">
AND a.birthday LIKE CONCAT('%', #{param.birthday}, '%')
</if>
<if test="param.organizationId != null">
AND a.organization_id = #{param.organizationId}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.deleted != null">
AND a.deleted = #{param.deleted}
</if>
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.roleId != null">
AND a.user_id IN (SELECT user_id FROM sys_user_role WHERE role_id=#{param.roleId})
</if>
<if test="param.organizationName != null">
AND b.organization_name LIKE CONCAT('%', #{param.organizationName}, '%')
</if>
<if test="param.sexName != null">
AND c.dict_data_name = #{param.sexName}
</if>
<if test="param.keywords != null">
AND (
a.username LIKE CONCAT('%', #{param.keywords}, '%')
OR a.nickname LIKE CONCAT('%', #{param.keywords}, '%')
OR b.organization_name LIKE CONCAT('%', #{param.keywords}, '%')
OR c.dict_data_name LIKE CONCAT('%', #{param.keywords}, '%')
OR d.role_name LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.eleadmin.common.system.entity.User">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.eleadmin.common.system.entity.User">
<include refid="selectSql"></include>
</select>
<!-- 根据账号查询 -->
<select id="selectByUsername" resultType="com.eleadmin.common.system.entity.User">
SELECT a.* ,
b.organization_name,
c.dict_data_name sex_name
FROM sys_user a
LEFT JOIN sys_organization b ON a.organization_id = b.organization_id
LEFT JOIN (
<include refid="selectSexDictSql"/>
) c ON a.sex = c.dict_data_code
<where>
AND a.deleted = 0
AND a.username = #{username}
<if test="tenantId != null">
AND a.tenant_id = #{tenantId}
</if>
<if test="tenantId == null">
AND a.tenant_id = 1
</if>
</where>
</select>
</mapper>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eleadmin.common.system.mapper.UserRoleMapper">
<insert id="insertBatch">
INSERT INTO sys_user_role(user_id, role_id) VALUES
<foreach collection="roleIds" item="roleId" separator=",">
(#{userId}, #{roleId})
</foreach>
</insert>
<select id="selectByUserId" resultType="com.eleadmin.common.system.entity.Role">
SELECT *
FROM sys_role
WHERE role_id IN (
SELECT role_id
FROM sys_user_role
WHERE user_id = #{userId}
)
AND deleted = 0
</select>
<select id="selectByUserIds" resultType="com.eleadmin.common.system.entity.Role">
SELECT a.user_id, b.*
FROM sys_user_role a
LEFT JOIN sys_role b ON a.role_id = b.role_id
WHERE a.user_id IN
<foreach collection="userIds" open="(" close=")" separator="," item="userId">
#{userId}
</foreach>
AND b.deleted = 0
</select>
</mapper>

View File

@ -0,0 +1,55 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-28 22:12:02
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "字典数据查询参数")
public class DictionaryDataParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "字典数据id")
@QueryField(type = QueryType.EQ)
private Integer dictDataId;
@ApiModelProperty(value = "字典id")
@QueryField(type = QueryType.EQ)
private Integer dictId;
@ApiModelProperty(value = "字典数据标识")
private String dictDataCode;
@ApiModelProperty(value = "字典数据名称")
private String dictDataName;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "字典代码")
@TableField(exist = false)
private String dictCode;
@ApiModelProperty(value = "字典名称")
@TableField(exist = false)
private String dictName;
@ApiModelProperty(value = "字典数据代码或字典数据名称")
@TableField(exist = false)
private String keywords;
}

View File

@ -0,0 +1,38 @@
package com.eleadmin.common.system.param;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-28 22:12:01
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "字典查询参数")
public class DictionaryParam extends BaseParam {
private static final long serialVersionUID = 1L;
@QueryField(type = QueryType.EQ)
@ApiModelProperty(value = "字典id")
private Integer dictId;
@ApiModelProperty(value = "字典标识")
private String dictCode;
@ApiModelProperty(value = "字典名称")
private String dictName;
@ApiModelProperty(value = "备注")
private String comments;
}

View File

@ -0,0 +1,51 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-30 11:29:31
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "文件上传记录查询参数")
public class FileRecordParam extends BaseParam {
private static final long serialVersionUID = 1L;
@QueryField(type = QueryType.EQ)
@ApiModelProperty("主键id")
private Integer id;
@ApiModelProperty("文件名称")
private String name;
@ApiModelProperty("文件存储路径")
private String path;
@QueryField(type = QueryType.EQ)
@ApiModelProperty("创建人")
private Integer createUserId;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("创建人账号")
@TableField(exist = false)
private String createUsername;
@ApiModelProperty("创建人名称")
@TableField(exist = false)
private String createNickname;
}

View File

@ -0,0 +1,31 @@
package com.eleadmin.common.system.param;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2021-08-30 17:35:16
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "登录参数")
public class LoginParam implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("账号")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
}

View File

@ -0,0 +1,60 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 19:09:23
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "登录日志查询参数")
public class LoginRecordParam extends BaseParam {
private static final long serialVersionUID = 1L;
@QueryField(type = QueryType.EQ)
@ApiModelProperty("主键id")
private Integer id;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("操作系统")
private String os;
@ApiModelProperty("设备名")
private String device;
@ApiModelProperty("浏览器类型")
private String browser;
@ApiModelProperty("ip地址")
private String ip;
@QueryField(type = QueryType.EQ)
@ApiModelProperty("操作类型, 0登录成功, 1登录失败, 2退出登录, 3续签token")
private Integer loginType;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("用户id")
@TableField(exist = false)
private Integer userId;
@ApiModelProperty("用户昵称")
@TableField(exist = false)
private String nickname;
}

View File

@ -0,0 +1,56 @@
package com.eleadmin.common.system.param;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 19:36:10
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "菜单查询参数")
public class MenuParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty("菜单id")
@QueryField(type = QueryType.EQ)
private Integer menuId;
@ApiModelProperty("上级id, 0是顶级")
@QueryField(type = QueryType.EQ)
private Integer parentId;
@ApiModelProperty("菜单名称")
private String title;
@ApiModelProperty("菜单路由关键字")
private String path;
@ApiModelProperty("菜单组件地址")
private String component;
@ApiModelProperty("菜单类型, 0菜单, 1按钮")
@QueryField(type = QueryType.EQ)
private Integer menuType;
@ApiModelProperty("权限标识")
private String authority;
@ApiModelProperty("菜单图标")
private String icon;
@ApiModelProperty("是否隐藏, 0否, 1是(仅注册路由不显示左侧菜单)")
@QueryField(type = QueryType.EQ)
private Integer hide;
}

View File

@ -0,0 +1,67 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 20:35:09
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "操作日志参数")
public class OperationRecordParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键id")
@QueryField(type = QueryType.EQ)
private Integer id;
@ApiModelProperty("用户id")
@QueryField(type = QueryType.EQ)
private Integer userId;
@ApiModelProperty("操作模块")
private String module;
@ApiModelProperty("操作功能")
private String description;
@ApiModelProperty("请求地址")
private String url;
@ApiModelProperty("请求方式")
private String requestMethod;
@ApiModelProperty("调用方法")
private String method;
@ApiModelProperty("ip地址")
private String ip;
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty("状态, 0成功, 1异常")
@QueryField(type = QueryType.EQ)
private Integer status;
@ApiModelProperty("用户账号")
@TableField(exist = false)
private String username;
@ApiModelProperty("用户昵称")
@TableField(exist = false)
private String nickname;
}

View File

@ -0,0 +1,65 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 20:35:09
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "组织机构查询参数")
public class OrganizationParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "机构id")
@QueryField(type = QueryType.EQ)
private Integer organizationId;
@ApiModelProperty(value = "上级id, 0是顶级")
@QueryField(type = QueryType.EQ)
private Integer parentId;
@ApiModelProperty(value = "机构名称")
private String organizationName;
@ApiModelProperty(value = "机构全称")
private String organizationFullName;
@ApiModelProperty(value = "机构代码")
private String organizationCode;
@ApiModelProperty(value = "机构类型(字典代码)")
private String organizationType;
@ApiModelProperty(value = "负责人id")
@QueryField(type = QueryType.EQ)
private Integer leaderId;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "机构类型名称")
@TableField(exist = false)
private String organizationTypeName;
@ApiModelProperty(value = "负责人姓名")
@TableField(exist = false)
private String leaderNickname;
@ApiModelProperty(value = "负责人账号")
@TableField(exist = false)
private String leaderUsername;
}

View File

@ -0,0 +1,38 @@
package com.eleadmin.common.system.param;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 20:35:09
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "角色查询参数")
public class RoleParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty("角色id")
@QueryField(type = QueryType.EQ)
private Integer roleId;
@ApiModelProperty("角色标识")
private String roleCode;
@ApiModelProperty("角色名称")
private String roleName;
@ApiModelProperty("备注")
private String comments;
}

View File

@ -0,0 +1,28 @@
package com.eleadmin.common.system.param;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2021-08-30 17:35:16
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "修改密码参数")
public class UpdatePasswordParam implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("原始密码")
private String oldPassword;
@ApiModelProperty("新密码")
private String password;
}

View File

@ -0,0 +1,42 @@
package com.eleadmin.common.system.param;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2011-10-15 17:33:34
*/
@Data
public class UserImportParam implements Serializable {
private static final long serialVersionUID = 1L;
@Excel(name = "账号")
private String username;
@Excel(name = "密码")
private String password;
@Excel(name = "昵称")
private String nickname;
@Excel(name = "手机号")
private String phone;
@Excel(name = "邮箱")
private String email;
@Excel(name = "组织机构")
private String organizationName;
@Excel(name = "性别")
private String sexName;
@Excel(name = "角色")
private String roleName;
}

View File

@ -0,0 +1,88 @@
package com.eleadmin.common.system.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.eleadmin.common.core.annotation.QueryField;
import com.eleadmin.common.core.annotation.QueryType;
import com.eleadmin.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author EleAdmin
* @since 2021-08-29 20:35:09
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "用户查询参数")
public class UserParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty("用户id")
@QueryField(type = QueryType.EQ)
private Integer userId;
@ApiModelProperty("账号")
private String username;
@ApiModelProperty("昵称")
private String nickname;
@ApiModelProperty("性别(字典)")
@QueryField(type = QueryType.EQ)
private String sex;
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("邮箱是否验证, 0否, 1是")
@QueryField(type = QueryType.EQ)
private Integer emailVerified;
@ApiModelProperty("真实姓名")
private String realName;
@ApiModelProperty("身份证号")
private String idCard;
@ApiModelProperty("出生日期")
private String birthday;
@ApiModelProperty("机构id")
@QueryField(type = QueryType.EQ)
private Integer organizationId;
@ApiModelProperty("状态, 0正常, 1冻结")
@QueryField(type = QueryType.EQ)
private Integer status;
@ApiModelProperty("是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty("角色id")
@TableField(exist = false)
private Integer roleId;
@ApiModelProperty("机构名称")
@TableField(exist = false)
private String organizationName;
@ApiModelProperty("性别名称")
@TableField(exist = false)
private String sexName;
@ApiModelProperty("搜索关键字")
@TableField(exist = false)
private String keywords;
}

View File

@ -0,0 +1,30 @@
package com.eleadmin.common.system.result;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
*
*
* @author EleAdmin
* @since 2021-08-30 17:35:16
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "验证码返回结果")
public class CaptchaResult implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("图形验证码base64数据")
private String base64;
@ApiModelProperty("验证码文本")
private String text;
}

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