From a600c1ea75ea04cdb1af8525c6d788f338252ad3 Mon Sep 17 00:00:00 2001 From: fengjing Date: Wed, 11 Oct 2017 16:37:41 +0800 Subject: [PATCH] Initial commit --- .gitignore | 24 ++ mvnw | 225 ++++++++++++++++++ mvnw.cmd | 143 +++++++++++ pom.xml | 184 ++++++++++++++ src/main/java/net/ameizi/Application.java | 53 +++++ .../java/net/ameizi/config/KaptchaConfig.java | 49 ++++ .../java/net/ameizi/config/ShiroConfig.java | 182 ++++++++++++++ .../ameizi/config/SwaggerConfiguration.java | 82 +++++++ .../ameizi/controller/LoginController.java | 178 ++++++++++++++ src/main/java/net/ameizi/cors/CorsConfig.java | 40 ++++ .../java/net/ameizi/domain/SysResource.java | 145 +++++++++++ src/main/java/net/ameizi/domain/SysRole.java | 105 ++++++++ .../net/ameizi/domain/SysRoleResource.java | 33 +++ src/main/java/net/ameizi/domain/SysUser.java | 205 ++++++++++++++++ .../java/net/ameizi/domain/SysUserRole.java | 33 +++ .../shiro/StatelessDefaultSubjectFactory.java | 19 ++ .../shiro/filter/JcaptchaValidateFilter.java | 76 ++++++ .../shiro/filter/JwtAuthenticationFilter.java | 80 +++++++ .../java/net/ameizi/shiro/jwt/JwtRealm.java | 108 +++++++++ .../java/net/ameizi/shiro/jwt/JwtToken.java | 28 +++ .../ameizi/utils/ApplicationContextUtil.java | 25 ++ .../java/net/ameizi/utils/SubjectUtil.java | 56 +++++ src/main/java/net/ameizi/utils/TokenUtil.java | 168 +++++++++++++ src/main/resources/application.properties | 18 ++ src/main/resources/application.yml | 9 + src/main/resources/generatorConfig.xml | 65 +++++ src/main/resources/shiro.sql | 146 ++++++++++++ .../java/net/ameizi/ApplicationTests.java | 16 ++ 28 files changed, 2495 insertions(+) create mode 100644 .gitignore create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/net/ameizi/Application.java create mode 100644 src/main/java/net/ameizi/config/KaptchaConfig.java create mode 100644 src/main/java/net/ameizi/config/ShiroConfig.java create mode 100644 src/main/java/net/ameizi/config/SwaggerConfiguration.java create mode 100644 src/main/java/net/ameizi/controller/LoginController.java create mode 100644 src/main/java/net/ameizi/cors/CorsConfig.java create mode 100644 src/main/java/net/ameizi/domain/SysResource.java create mode 100644 src/main/java/net/ameizi/domain/SysRole.java create mode 100644 src/main/java/net/ameizi/domain/SysRoleResource.java create mode 100644 src/main/java/net/ameizi/domain/SysUser.java create mode 100644 src/main/java/net/ameizi/domain/SysUserRole.java create mode 100644 src/main/java/net/ameizi/shiro/StatelessDefaultSubjectFactory.java create mode 100644 src/main/java/net/ameizi/shiro/filter/JcaptchaValidateFilter.java create mode 100644 src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java create mode 100644 src/main/java/net/ameizi/shiro/jwt/JwtRealm.java create mode 100644 src/main/java/net/ameizi/shiro/jwt/JwtToken.java create mode 100644 src/main/java/net/ameizi/utils/ApplicationContextUtil.java create mode 100644 src/main/java/net/ameizi/utils/SubjectUtil.java create mode 100644 src/main/java/net/ameizi/utils/TokenUtil.java create mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/application.yml create mode 100644 src/main/resources/generatorConfig.xml create mode 100644 src/main/resources/shiro.sql create mode 100644 src/test/java/net/ameizi/ApplicationTests.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2af7cef --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..5bf251c --- /dev/null +++ b/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 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 Migwn, 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)`" + # TODO classpath? +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 + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +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 + +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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..019bd74 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 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 key stroke 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 enable echoing my 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 + +%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% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f052c47 --- /dev/null +++ b/pom.xml @@ -0,0 +1,184 @@ + + + 4.0.0 + + net.ameizi + shiro-jwt-springboot + 0.0.1-SNAPSHOT + jar + + shiro-jwt-springboot + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.7.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + io.jsonwebtoken + jjwt + 0.8.0 + + + + org.apache.commons + commons-lang3 + 3.6 + + + + commons-codec + commons-codec + 1.10 + + + + commons-io + commons-io + 2.5 + + + + com.google.guava + guava + 23.0 + + + + org.apache.shiro + shiro-spring + 1.2.2 + + + + org.apache.shiro + shiro-ehcache + 1.2.2 + + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + com.github.axet + kaptcha + 0.0.9 + + + + io.springfox + springfox-swagger2 + 2.6.1 + + + + io.springfox + springfox-swagger-ui + 2.6.1 + + + + com.alibaba + fastjson + 1.2.38 + + + + org.springframework.mobile + spring-mobile-device + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.mybatis.generator + mybatis-generator-maven-plugin + 1.3.5 + + src/main/resources/generatorConfig.xml + true + true + + + + Generate MyBatis Artifacts + + generate + + + + + + org.mybatis.generator + mybatis-generator-core + 1.3.5 + + + mysql + mysql-connector-java + 5.1.38 + + + + + + + + + diff --git a/src/main/java/net/ameizi/Application.java b/src/main/java/net/ameizi/Application.java new file mode 100644 index 0000000..b0f249b --- /dev/null +++ b/src/main/java/net/ameizi/Application.java @@ -0,0 +1,53 @@ +package net.ameizi; + +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.web.HttpMessageConverters; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; + +import java.util.ArrayList; +import java.util.List; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + + /** + * 1.需要定义一个convert转换消息的对象 + * 2.创建配置信息,加入配置信息:比如是否需要格式化返回的json + * 3.converter中添加配置信息 + * 4.convert添加到converters当中 + */ + @Bean + public HttpMessageConverters fastJsonHttpMessageConverters() { + // 1.需要定义一个convert转换消息的对象 + FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); + + //2.创建配置信息,加入配置信息:比如是否需要格式化返回的json + FastJsonConfig fastJsonConfig = new FastJsonConfig(); + fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); + + //3.converter中添加配置信息 + fastConverter.setFastJsonConfig(fastJsonConfig); + + /** + * 设置json 返回格式和编码方式 处理乱码问题 + */ + List mediaTypeList=new ArrayList<>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8); + fastConverter.setSupportedMediaTypes(mediaTypeList); + + //4.convert添加到converters当中 + HttpMessageConverter converter = fastConverter; + return new HttpMessageConverters(converter); + } +} diff --git a/src/main/java/net/ameizi/config/KaptchaConfig.java b/src/main/java/net/ameizi/config/KaptchaConfig.java new file mode 100644 index 0000000..6e64c04 --- /dev/null +++ b/src/main/java/net/ameizi/config/KaptchaConfig.java @@ -0,0 +1,49 @@ +package net.ameizi.config; + +import com.google.code.kaptcha.impl.DefaultKaptcha; +import com.google.code.kaptcha.util.Config; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Properties; + +@Configuration +public class KaptchaConfig { + + @Bean + public DefaultKaptcha captchaProducer(){ + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + + Properties properties = new Properties(); + //验证码宽度 + properties.setProperty("kaptcha.image.width","115"); + //验证码高度 + properties.setProperty("kaptcha.image.height","35"); + //生成验证码内容范围 + properties.setProperty("kaptcha.textproducer.char.string","abcde2345678gfynmnpwx"); + // 验证码个数 + properties.setProperty("kaptcha.textproducer.char.length","5"); + //是否有边框 + properties.setProperty("kaptcha.border","no"); + //验证码字体颜色 + properties.setProperty("kaptcha.textproducer.font.color","red"); + //验证码字体大小 + properties.setProperty("kaptcha.textproducer.font.size","24"); + // 验证码所属字体样式 + properties.setProperty("kaptcha.textproducer.font.names","Arial, Courier"); + properties.setProperty("kaptcha.background.clear.from","white"); + properties.setProperty("kaptcha.background.clear.to","white"); + properties.setProperty("kaptcha.obscurificator.impl","com.google.code.kaptcha.impl.ShadowGimpy"); + properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise"); + //干扰线颜色 + properties.setProperty("kaptcha.noise.color","red"); + //验证码文本字符间距 + properties.setProperty("kaptcha.textproducer.char.space","3"); + + Config Config = new Config(properties); + defaultKaptcha.setConfig(Config); + + return defaultKaptcha; + } + +} diff --git a/src/main/java/net/ameizi/config/ShiroConfig.java b/src/main/java/net/ameizi/config/ShiroConfig.java new file mode 100644 index 0000000..5201b98 --- /dev/null +++ b/src/main/java/net/ameizi/config/ShiroConfig.java @@ -0,0 +1,182 @@ +package net.ameizi.config; + +import net.ameizi.shiro.StatelessDefaultSubjectFactory; +import net.ameizi.shiro.filter.JcaptchaValidateFilter; +import net.ameizi.shiro.filter.JwtAuthenticationFilter; +import net.ameizi.shiro.jwt.JwtRealm; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.credential.CredentialsMatcher; +import org.apache.shiro.authc.credential.HashedCredentialsMatcher; +import org.apache.shiro.cache.CacheManager; +import org.apache.shiro.cache.MemoryConstrainedCacheManager; +import org.apache.shiro.mgt.DefaultSecurityManager; +import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; +import org.apache.shiro.mgt.DefaultSubjectDAO; +import org.apache.shiro.session.mgt.DefaultSessionManager; +import org.apache.shiro.spring.LifecycleBeanPostProcessor; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.apache.shiro.web.mgt.DefaultWebSubjectFactory; +import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.web.filter.DelegatingFilterProxy; + +import javax.servlet.Filter; +import java.util.LinkedHashMap; +import java.util.Map; + +@Configuration +public class ShiroConfig { + + /** + * 自定义Realm + * @return + */ + @Bean(name = "jwtRealm") + @DependsOn("lifecycleBeanPostProcessor") + public JwtRealm jwtRealm() { + JwtRealm jwtRealm = new JwtRealm(); + // jwtRealm.setCredentialsMatcher(credentialsMatcher()); + jwtRealm.setCachingEnabled(false); + return jwtRealm; + } + + @Bean + public FilterRegistrationBean delegatingFilterProxy() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); + DelegatingFilterProxy proxy = new DelegatingFilterProxy(); + proxy.setTargetFilterLifecycle(true); + proxy.setTargetBeanName("shiroFilter"); + filterRegistrationBean.setFilter(proxy); + return filterRegistrationBean; + } + + @Bean("shiroFilter") + @DependsOn("securityManager") + public ShiroFilterFactoryBean shiroFilter(DefaultSecurityManager securityManager){ + ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); + shiroFilter.setSecurityManager(securityManager); + // 拦截器 + Map filterChainDefinitionMap = new LinkedHashMap(); + + // 允许用户匿名访问/login(登录接口) + filterChainDefinitionMap.put("/login", "anon"); + // 验证码允许匿名访问 + filterChainDefinitionMap.put("/captcha*","anon"); + + filterChainDefinitionMap.put("/**", "jwt"); + + // filterChainDefinitionMap.put("/**","anon"); + + shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap); + + Map filters = new LinkedHashMap<>(); + filters.put("jwt",new JwtAuthenticationFilter()); + filters.put("jcaptchaValidate",new JcaptchaValidateFilter()); + + shiroFilter.setFilters(filters); + + return shiroFilter; + } + + /** + * Subject工厂管理器 + * @return + */ + @Bean + public DefaultWebSubjectFactory subjectFactory(){ + DefaultWebSubjectFactory subjectFactory = new StatelessDefaultSubjectFactory(); + return subjectFactory; + } + + /** + * 安全管理器 + * @return + */ + @Bean("securityManager") + public DefaultWebSecurityManager securityManager(){ + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); + + securityManager.setRealm(jwtRealm()); + + // 替换默认的DefaultSubjectFactory,用于关闭session功能 + securityManager.setSubjectFactory(subjectFactory()); + securityManager.setSessionManager(sessionManager()); + + // 关闭session存储,禁用Session作为存储策略的实现,但它没有完全地禁用Session所以需要配合SubjectFactory中的context.setSessionCreationEnabled(false) + ((DefaultSessionStorageEvaluator) ((DefaultSubjectDAO)securityManager.getSubjectDAO()).getSessionStorageEvaluator()).setSessionStorageEnabled(false); + + // 用户授权/认证信息Cache, 后期可采用EhCache缓存 + // securityManager.setCacheManager(cacheManager()); + + SecurityUtils.setSecurityManager(securityManager); + return securityManager; + } + + /** + * 会话管理器 + * @return + */ + public DefaultSessionManager sessionManager(){ + DefaultSessionManager sessionManager =new DefaultSessionManager(); + // 关闭session定时检查,通过setSessionValidationSchedulerEnabled禁用掉会话调度器 + sessionManager.setSessionValidationSchedulerEnabled(false); + return sessionManager; + } + + /** + * 用户授权信息缓存 + * @return + */ + @Bean + public CacheManager cacheManager() { + // EhCacheManager cacheManager = new EhCacheManager(); + // cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml"); + return new MemoryConstrainedCacheManager(); + } + + /** + * 凭证匹配器 + * @return + */ + @Bean + public CredentialsMatcher credentialsMatcher(){ + HashedCredentialsMatcher hashedCredentialsMatcher =new HashedCredentialsMatcher(); + hashedCredentialsMatcher.setHashAlgorithmName("MD5"); + hashedCredentialsMatcher.setHashIterations(1024); + hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true); + return hashedCredentialsMatcher; + } + + /** + * Shiro生命周期处理器 + * @return + */ + @Bean(name = "lifecycleBeanPostProcessor") + public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { + return new LifecycleBeanPostProcessor(); + } + + /** + * 开启Shiro注解(如@RequiresRoles,@RequiresPermissions) + * @return + */ + @Bean + @DependsOn("lifecycleBeanPostProcessor") + public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){ + DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); + advisorAutoProxyCreator.setProxyTargetClass(true); + return advisorAutoProxyCreator; + } + + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(){ + AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); + authorizationAttributeSourceAdvisor.setSecurityManager(securityManager()); + return authorizationAttributeSourceAdvisor; + } +} diff --git a/src/main/java/net/ameizi/config/SwaggerConfiguration.java b/src/main/java/net/ameizi/config/SwaggerConfiguration.java new file mode 100644 index 0000000..4aee9c8 --- /dev/null +++ b/src/main/java/net/ameizi/config/SwaggerConfiguration.java @@ -0,0 +1,82 @@ +package net.ameizi.config; + +import com.google.common.collect.Lists; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.service.Parameter; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.List; + +@Configuration +@EnableSwagger2 +public class SwaggerConfiguration extends WebMvcConfigurerAdapter { + + @Value("${swagger.host}") + private String swaggerHost; + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("amz") + .description("基于shiro和jwt的前后端分离权限系统") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("", "", "")) + .build(); + } + + @Bean + public Docket createRestApi() { + ParameterBuilder builder = new ParameterBuilder(); + Parameter parameter = builder + // 从cookie中获取token + .parameterType("cookie") //参数类型支持header, cookie, body, query etc + .name("token") //参数名 + .defaultValue("") //默认值 + .description("请输入token") + .modelRef(new ModelRef("string")) //指定参数值的类型 + .required(false).build(); //非必需,这里是全局配置,然而在登陆的时候是不用验证的 + List parameters = Lists.newArrayList(parameter); + return new Docket(DocumentationType.SWAGGER_2) + .host(this.swaggerHost) + .select() + .apis(RequestHandlerSelectors.basePackage("net.ameizi")) + .paths(PathSelectors.any()) + .build() + .apiInfo(this.apiInfo()) + .globalOperationParameters(parameters); + } + + /** + * swagger ui资源映射 + * @param registry + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars*") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + /** + * swagger-ui.html路径映射,浏览器中使用/api-docs访问 + * @param registry + */ + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addRedirectViewController("/api-docs","/swagger-ui.html"); + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/controller/LoginController.java b/src/main/java/net/ameizi/controller/LoginController.java new file mode 100644 index 0000000..e62fdaf --- /dev/null +++ b/src/main/java/net/ameizi/controller/LoginController.java @@ -0,0 +1,178 @@ +package net.ameizi.controller; + +import com.alibaba.fastjson.JSONObject; +import com.google.code.kaptcha.impl.DefaultKaptcha; +import com.google.common.collect.ImmutableMap; +import net.ameizi.shiro.jwt.JwtToken; +import net.ameizi.utils.TokenUtil; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.subject.Subject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.mobile.device.Device; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.imageio.ImageIO; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.TimeUnit; + +@RestController +public class LoginController { + + @Autowired + private TokenUtil tokenUtil; + + @Autowired + private DefaultKaptcha captchaProducer; + + @Autowired + private RedisTemplate redisTemplate; + + @GetMapping(value="/captcha") + public Map captcha(){ + try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + String capText = captchaProducer.createText(); + String uuid = UUID.randomUUID().toString(); + redisTemplate.boundValueOps(uuid).set(capText,60, TimeUnit.SECONDS); + BufferedImage bi = captchaProducer.createImage(capText); + ImageIO.write(bi, "png", baos); + String imgBase64 = Base64.encodeBase64String(baos.toByteArray()); + return ImmutableMap.of(uuid,"data:image/jpeg;base64,"+imgBase64); + } catch (IOException e) { + throw new RuntimeException(e.getMessage(),e); + } + } + + @PostMapping("/login") + public Object login(HttpServletRequest request, HttpServletResponse response, Device device) throws IOException { + JSONObject jsonObject = new JSONObject(); + + String username = request.getParameter("username"); + String password = request.getParameter("password"); + + // 验证用户名密码成功后生成token + String token = tokenUtil.generateToken(username, device); + // 构建JwtToken + JwtToken jwtToken = JwtToken.builder().token(token).principal(username).build(); + + Subject subject = SecurityUtils.getSubject(); + try { + // 该方法会调用JwtRealm中的doGetAuthenticationInfo方法 + subject.login(jwtToken); + } catch (UnknownAccountException exception) { + exception.printStackTrace(); + System.out.println("账号不存在"); + } catch (IncorrectCredentialsException exception) { + exception.printStackTrace(); + System.out.println("错误的凭证,用户名或密码不正确"); + } catch (LockedAccountException exception) { + exception.printStackTrace(); + System.out.println("账户已锁定"); + } catch (ExcessiveAttemptsException exception) { + exception.printStackTrace(); + System.out.println("错误次数过多"); + } catch (AuthenticationException exception) { + exception.printStackTrace(); + System.out.println("认证失败"); + } + + // 认证通过 + if(subject.isAuthenticated()){ + + // 将token写出到cookie + Cookie cookie =new Cookie("token",token); + cookie.setHttpOnly(true); + cookie.setMaxAge(3600 * 5); + cookie.setPath("/"); + response.addCookie(cookie); + response.flushBuffer(); + + jsonObject.put("code",200); + jsonObject.put("msg","认证成功!"); + jsonObject.put("token",token); + jsonObject.put("timestamp", Calendar.getInstance().getTimeInMillis()); + return jsonObject; + }else{ + jsonObject.put("code",403); + jsonObject.put("msg","认证失败"); + jsonObject.put("token",null); + jsonObject.put("timestamp", Calendar.getInstance().getTimeInMillis()); + return jsonObject; + } + } + + + /** + * 检查是否登录 + * @param token + * @return + */ + @GetMapping(value = "/checkLogin") + public Object checkLogin(@CookieValue("token") String token){ + JSONObject jsonObject = new JSONObject(); + jsonObject.put("code",200); + if(StringUtils.isEmpty(token)){ + jsonObject.put("msg","令牌为空"); + } + + // 根据token获取用户信息 + + // 检查token合法性及用户身份 + + return jsonObject; + } + + + /** + * 登出 + * @param request + * @param response + * @return + * @throws IOException + */ + @GetMapping(value = "/logout") + public Object logout(HttpServletRequest request,HttpServletResponse response) throws IOException { + Optional cookie = Arrays.stream(request.getCookies()) + .filter(ck -> "token".equals(ck.getName())) + .limit(1) + .map(ck -> { + ck.setMaxAge(0); + ck.setHttpOnly(true); + ck.setPath("/"); + return ck; + }) + .findFirst(); + response.addCookie(cookie.get()); + response.flushBuffer(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("code",200); + jsonObject.put("msg","success"); + return jsonObject; + } + + + /** + * 更新token + * @param token + * @return + */ + @RequestMapping("/token/refresh") + public Object refreshToken(@CookieValue(value = "token") String token) { + JSONObject jsonObject = new JSONObject(); + String newToken = tokenUtil.refreshToken(token); + jsonObject.put("code",200); + jsonObject.put("msg","success"); + jsonObject.put("token",newToken); + jsonObject.put("timestamp", Calendar.getInstance().getTimeInMillis()); + return jsonObject; + } +} diff --git a/src/main/java/net/ameizi/cors/CorsConfig.java b/src/main/java/net/ameizi/cors/CorsConfig.java new file mode 100644 index 0000000..d8166cd --- /dev/null +++ b/src/main/java/net/ameizi/cors/CorsConfig.java @@ -0,0 +1,40 @@ +package net.ameizi.cors; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class CorsConfig { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurerAdapter() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "HEAD", "DELETE", "OPTION"); + } + }; + } + + private CorsConfiguration buildConfig() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.addAllowedOrigin("*"); + corsConfiguration.addAllowedHeader("*"); + corsConfiguration.addAllowedMethod("*"); + return corsConfiguration; + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", buildConfig()); + return new CorsFilter(source); + } + +} diff --git a/src/main/java/net/ameizi/domain/SysResource.java b/src/main/java/net/ameizi/domain/SysResource.java new file mode 100644 index 0000000..b87c2fe --- /dev/null +++ b/src/main/java/net/ameizi/domain/SysResource.java @@ -0,0 +1,145 @@ +package net.ameizi.domain; + +import java.util.Date; + +public class SysResource { + private Long id; + + private String type; + + private String name; + + private String permission; + + private String icon; + + private Integer sort; + + private String url; + + private String description; + + private Boolean status; + + private Long parentId; + + private Long createBy; + + private Date createAt; + + private Long updateBy; + + private Date updateAt; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type == null ? null : type.trim(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name == null ? null : name.trim(); + } + + public String getPermission() { + return permission; + } + + public void setPermission(String permission) { + this.permission = permission == null ? null : permission.trim(); + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon == null ? null : icon.trim(); + } + + public Integer getSort() { + return sort; + } + + public void setSort(Integer sort) { + this.sort = sort; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url == null ? null : url.trim(); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description == null ? null : description.trim(); + } + + public Boolean getStatus() { + return status; + } + + public void setStatus(Boolean status) { + this.status = status; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public Long getCreateBy() { + return createBy; + } + + public void setCreateBy(Long createBy) { + this.createBy = createBy; + } + + public Date getCreateAt() { + return createAt; + } + + public void setCreateAt(Date createAt) { + this.createAt = createAt; + } + + public Long getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(Long updateBy) { + this.updateBy = updateBy; + } + + public Date getUpdateAt() { + return updateAt; + } + + public void setUpdateAt(Date updateAt) { + this.updateAt = updateAt; + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/domain/SysRole.java b/src/main/java/net/ameizi/domain/SysRole.java new file mode 100644 index 0000000..c16f009 --- /dev/null +++ b/src/main/java/net/ameizi/domain/SysRole.java @@ -0,0 +1,105 @@ +package net.ameizi.domain; + +import java.util.Date; + +public class SysRole { + private Long id; + + private String name; + + private String code; + + private String remark; + + private Boolean status; + + private Long parentId; + + private Long createBy; + + private Date createAt; + + private Long updateBy; + + private Date updateAt; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name == null ? null : name.trim(); + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code == null ? null : code.trim(); + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark == null ? null : remark.trim(); + } + + public Boolean getStatus() { + return status; + } + + public void setStatus(Boolean status) { + this.status = status; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public Long getCreateBy() { + return createBy; + } + + public void setCreateBy(Long createBy) { + this.createBy = createBy; + } + + public Date getCreateAt() { + return createAt; + } + + public void setCreateAt(Date createAt) { + this.createAt = createAt; + } + + public Long getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(Long updateBy) { + this.updateBy = updateBy; + } + + public Date getUpdateAt() { + return updateAt; + } + + public void setUpdateAt(Date updateAt) { + this.updateAt = updateAt; + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/domain/SysRoleResource.java b/src/main/java/net/ameizi/domain/SysRoleResource.java new file mode 100644 index 0000000..bacd118 --- /dev/null +++ b/src/main/java/net/ameizi/domain/SysRoleResource.java @@ -0,0 +1,33 @@ +package net.ameizi.domain; + +public class SysRoleResource { + private Long id; + + private Long roleId; + + private Long resourceId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public Long getResourceId() { + return resourceId; + } + + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/domain/SysUser.java b/src/main/java/net/ameizi/domain/SysUser.java new file mode 100644 index 0000000..49e60eb --- /dev/null +++ b/src/main/java/net/ameizi/domain/SysUser.java @@ -0,0 +1,205 @@ +package net.ameizi.domain; + +import java.util.Date; + +public class SysUser { + private Long id; + + private String mobilePhone; + + private String userName; + + private String nickname; + + private String password; + + private String salt; + + private String signature; + + private Boolean gender; + + private Long qq; + + private String email; + + private String avatar; + + private String province; + + private String city; + + private String regIp; + + private Integer score; + + private Integer status; + + private Long createBy; + + private Date createAt; + + private Long updateBy; + + private Date updateAt; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMobilePhone() { + return mobilePhone; + } + + public void setMobilePhone(String mobilePhone) { + this.mobilePhone = mobilePhone == null ? null : mobilePhone.trim(); + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName == null ? null : userName.trim(); + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname == null ? null : nickname.trim(); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password == null ? null : password.trim(); + } + + public String getSalt() { + return salt; + } + + public void setSalt(String salt) { + this.salt = salt == null ? null : salt.trim(); + } + + public String getSignature() { + return signature; + } + + public void setSignature(String signature) { + this.signature = signature == null ? null : signature.trim(); + } + + public Boolean getGender() { + return gender; + } + + public void setGender(Boolean gender) { + this.gender = gender; + } + + public Long getQq() { + return qq; + } + + public void setQq(Long qq) { + this.qq = qq; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email == null ? null : email.trim(); + } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar == null ? null : avatar.trim(); + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province == null ? null : province.trim(); + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city == null ? null : city.trim(); + } + + public String getRegIp() { + return regIp; + } + + public void setRegIp(String regIp) { + this.regIp = regIp == null ? null : regIp.trim(); + } + + public Integer getScore() { + return score; + } + + public void setScore(Integer score) { + this.score = score; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Long getCreateBy() { + return createBy; + } + + public void setCreateBy(Long createBy) { + this.createBy = createBy; + } + + public Date getCreateAt() { + return createAt; + } + + public void setCreateAt(Date createAt) { + this.createAt = createAt; + } + + public Long getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(Long updateBy) { + this.updateBy = updateBy; + } + + public Date getUpdateAt() { + return updateAt; + } + + public void setUpdateAt(Date updateAt) { + this.updateAt = updateAt; + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/domain/SysUserRole.java b/src/main/java/net/ameizi/domain/SysUserRole.java new file mode 100644 index 0000000..03c284a --- /dev/null +++ b/src/main/java/net/ameizi/domain/SysUserRole.java @@ -0,0 +1,33 @@ +package net.ameizi.domain; + +public class SysUserRole { + private Long id; + + private Long userId; + + private Long roleId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } +} \ No newline at end of file diff --git a/src/main/java/net/ameizi/shiro/StatelessDefaultSubjectFactory.java b/src/main/java/net/ameizi/shiro/StatelessDefaultSubjectFactory.java new file mode 100644 index 0000000..254c099 --- /dev/null +++ b/src/main/java/net/ameizi/shiro/StatelessDefaultSubjectFactory.java @@ -0,0 +1,19 @@ +package net.ameizi.shiro; + +import org.apache.shiro.subject.Subject; +import org.apache.shiro.subject.SubjectContext; +import org.apache.shiro.web.mgt.DefaultWebSubjectFactory; + +/** + * 通过调用context.setSessionCreationEnabled(false)表示不创建会话, + * 如果之后调用Subject.getSession()将抛出DisabledSessionException异常。 + */ +public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory { + + @Override + public Subject createSubject(SubjectContext context) { + // 不创建session + context.setSessionCreationEnabled(false); + return super.createSubject(context); + } +} diff --git a/src/main/java/net/ameizi/shiro/filter/JcaptchaValidateFilter.java b/src/main/java/net/ameizi/shiro/filter/JcaptchaValidateFilter.java new file mode 100644 index 0000000..25c97cc --- /dev/null +++ b/src/main/java/net/ameizi/shiro/filter/JcaptchaValidateFilter.java @@ -0,0 +1,76 @@ +package net.ameizi.shiro.filter; + +import net.ameizi.utils.ApplicationContextUtil; +import org.apache.shiro.web.filter.AccessControlFilter; +import org.apache.shiro.web.util.WebUtils; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.util.StringUtils; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +public class JcaptchaValidateFilter extends AccessControlFilter { + + private boolean jcaptchaEbabled = true; //是否开启验证码支持 + + private String jcaptchaParam = "jcaptchaCode"; //前台提交的验证码参数名 + + public static String failureKeyAttribute = "jcaptcha.message"; //验证失败后存储到的属性名 + + private String redisCaptchaKey = "vcodeKey"; + + public void setJcaptchaEbabled(boolean jcaptchaEbabled) { + this.jcaptchaEbabled = jcaptchaEbabled; + } + + public void setJcaptchaParam(String jcaptchaParam) { + this.jcaptchaParam = jcaptchaParam; + } + + public void setFailureKeyAttribute(String failureKeyAttribute) { + JcaptchaValidateFilter.failureKeyAttribute = failureKeyAttribute; + } + + public void setRedisCaptchaKey(String redisCaptchaKey) { + this.redisCaptchaKey = redisCaptchaKey; + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse servletResponse, Object o) throws Exception { + //1、设置验证码是否开启属性,页面可以根据该属性来决定是否显示验证码 + request.setAttribute("jcaptchaEbabled",jcaptchaEbabled); + HttpServletRequest httpRequest = WebUtils.toHttp(request); + + //2、判断验证码是否禁用或不是表单提交(允许访问) + if(!jcaptchaEbabled || !"post".equalsIgnoreCase(httpRequest.getMethod())){ + return true; + } + String captchaKey = httpRequest.getParameter(redisCaptchaKey); + if(StringUtils.isEmpty(captchaKey)){ + request.setAttribute(failureKeyAttribute,"验证码Key为空!"); + return false; + } + + RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBeanObj("redisTemplate"); + String captchaValue = (String) redisTemplate.boundValueOps(captchaKey).get(); + + if(StringUtils.isEmpty(captchaValue)){ + request.setAttribute(failureKeyAttribute,"验证码已过期!"); + return false; + } + + if((httpRequest.getParameter(jcaptchaParam)).equalsIgnoreCase(captchaValue)){ + return true; + } + + request.setAttribute(failureKeyAttribute,"验证码输入错误!"); + + return false; + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse servletResponse) throws Exception { + return true; + } +} diff --git a/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java b/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java new file mode 100644 index 0000000..208fd3e --- /dev/null +++ b/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java @@ -0,0 +1,80 @@ +package net.ameizi.shiro.filter; + +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.ameizi.shiro.jwt.JwtToken; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.filter.authc.AuthenticatingFilter; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Arrays; + +public class JwtAuthenticationFilter extends AuthenticatingFilter { + + private static final String TOKEN = "token"; + + @Override + protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { + HttpServletRequest httpRequest = (HttpServletRequest) request; + // 先从Header里面获取 + String token = httpRequest.getHeader(TOKEN); + if(StringUtils.isEmpty(token)){ + // 获取不到再从Parameter中拿 + token = httpRequest.getParameter(TOKEN); + // 还是获取不到再从Cookie中拿 + if(StringUtils.isEmpty(token)){ + token = Arrays.stream(httpRequest.getCookies()) + .filter(ck -> "token".equals(ck.getName())) + .limit(1) + .findFirst() + .get() + .getValue(); + } + } + return JwtToken.builder() + .token(token) + .build(); + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { + return false; + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + return executeLogin(request, response); + } + + @Override + protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, + ServletResponse response) throws Exception { + return true; + } + + @Override + protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request, + ServletResponse response) { + HttpServletResponse servletResponse = (HttpServletResponse) response; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("code", HttpServletResponse.SC_UNAUTHORIZED); + jsonObject.put("msg","登录失败,无权访问"); + jsonObject.put("timestamp", System.currentTimeMillis()); + try { + servletResponse.setCharacterEncoding("UTF-8"); + servletResponse.setContentType("application/json;charset=UTF-8"); + servletResponse.setHeader("Access-Control-Allow-Origin","*"); + ObjectMapper objectMapper = new ObjectMapper(); + response.getWriter().write(objectMapper.writeValueAsString(jsonObject)); + } catch (IOException e) { + } + return false; + } +} diff --git a/src/main/java/net/ameizi/shiro/jwt/JwtRealm.java b/src/main/java/net/ameizi/shiro/jwt/JwtRealm.java new file mode 100644 index 0000000..23e8d39 --- /dev/null +++ b/src/main/java/net/ameizi/shiro/jwt/JwtRealm.java @@ -0,0 +1,108 @@ +package net.ameizi.shiro.jwt; + +import com.google.common.collect.Sets; +import net.ameizi.domain.SysUser; +import net.ameizi.utils.TokenUtil; +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.springframework.beans.factory.annotation.Autowired; + +import static org.apache.shiro.web.filter.mgt.DefaultFilter.user; + +public class JwtRealm extends AuthorizingRealm { + + @Autowired + private TokenUtil tokenUtil; + + @Override + public boolean supports(AuthenticationToken token) { + //表示此Realm只支持JwtToken类型 + return token instanceof JwtToken; + } + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + // 根据用户名查找角色,请根据需求实现 + String username = (String)principals.getPrimaryPrincipal(); + + SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); + + // 根据username查询角色 + authorizationInfo.setRoles(Sets.newHashSet("admin","superadmin")); + + // 根据username查询权限 + authorizationInfo.setStringPermissions(Sets.newHashSet("system:*")); + + return authorizationInfo; + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { + JwtToken jwtToken = (JwtToken) authenticationToken; + + // 获取token + String token = jwtToken.getToken(); + + // 从token中获取用户名 + String username = tokenUtil.getUsernameFromToken(token); + + // 根据用户名查询数据库 + + SysUser user = new SysUser(); + user.setUserName(username); + user.setStatus(1); + user.setPassword("000000"); + + // 用户不存在 + if (user == null) { + throw new UnknownAccountException(); + } + + // 用户被禁用 + if(user.getStatus()==0){ + throw new LockedAccountException(); + } + + try { + return new SimpleAuthenticationInfo( + username, + token, + getName() + ); + } catch (Exception e) { + throw new AuthenticationException(e); + } + } + + @Override + public void clearCachedAuthorizationInfo(PrincipalCollection principals) { + super.clearCachedAuthorizationInfo(principals); + } + + @Override + public void clearCachedAuthenticationInfo(PrincipalCollection principals) { + super.clearCachedAuthenticationInfo(principals); + } + + @Override + public void clearCache(PrincipalCollection principals) { + super.clearCache(principals); + } + + public void clearAllCachedAuthorizationInfo() { + getAuthorizationCache().clear(); + } + + public void clearAllCachedAuthenticationInfo() { + getAuthenticationCache().clear(); + } + + public void clearAllCache() { + clearAllCachedAuthenticationInfo(); + clearAllCachedAuthorizationInfo(); + } + +} diff --git a/src/main/java/net/ameizi/shiro/jwt/JwtToken.java b/src/main/java/net/ameizi/shiro/jwt/JwtToken.java new file mode 100644 index 0000000..d1baaec --- /dev/null +++ b/src/main/java/net/ameizi/shiro/jwt/JwtToken.java @@ -0,0 +1,28 @@ +package net.ameizi.shiro.jwt; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.apache.shiro.authc.AuthenticationToken; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class JwtToken implements AuthenticationToken { + + private String principal; + + private String token; + + @Override + public String getPrincipal() { + return principal; + } + + @Override + public Object getCredentials() { + return token; + } +} diff --git a/src/main/java/net/ameizi/utils/ApplicationContextUtil.java b/src/main/java/net/ameizi/utils/ApplicationContextUtil.java new file mode 100644 index 0000000..cfed8ca --- /dev/null +++ b/src/main/java/net/ameizi/utils/ApplicationContextUtil.java @@ -0,0 +1,25 @@ +package net.ameizi.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationContextUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + ApplicationContextUtil.applicationContext = applicationContext; + } + + public static T getBean(Class cls){ + return applicationContext.getBean(cls); + } + + public static Object getBeanObj(String beanName){ + return applicationContext.getBean(beanName); + } +} + diff --git a/src/main/java/net/ameizi/utils/SubjectUtil.java b/src/main/java/net/ameizi/utils/SubjectUtil.java new file mode 100644 index 0000000..da22406 --- /dev/null +++ b/src/main/java/net/ameizi/utils/SubjectUtil.java @@ -0,0 +1,56 @@ +package net.ameizi.utils; + +import org.apache.shiro.SecurityUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +@Component +public class SubjectUtil { + + @Autowired + private TokenUtil tokenUtil; + + public Integer getSubjectId() { + String username = (String) SecurityUtils.getSubject().getPrincipal(); + if (StringUtils.isEmpty(username)) { + throw new IllegalArgumentException("该用户未登录"); + } + return 1; + } + + + /** + * 直接从token获取用户id,不抛异常。 + * @param token token + * @return 用户id + */ +// public Long getSubjectIdFromToken(String token) { +// User user = this.getSubjectUserFromToken(token); +// return user.getId(); +// } + + + /** + * 直接从token获取用户id,不抛异常。 + * @param token token + * @return 用户id + */ +// public User getSubjectUserFromToken(String token) { +// if(StringUtils.isEmpty(token)){ +// throw new TokenParserException("令牌为空!"); +// } +// +// String username = tokenUtil.getUsernameFromToken(token); +// +// if (StringUtils.isEmpty(username)) { +// throw new TokenParserException("从令牌中解析用户名为空!"); +// } +// User user = this.userService.selectOne(User.builder().username(username).build()); +// if (user == null) { +// throw new LoginException("用户不存在!"); +// } +// return user; +// } + +} diff --git a/src/main/java/net/ameizi/utils/TokenUtil.java b/src/main/java/net/ameizi/utils/TokenUtil.java new file mode 100644 index 0000000..650ca2d --- /dev/null +++ b/src/main/java/net/ameizi/utils/TokenUtil.java @@ -0,0 +1,168 @@ +package net.ameizi.utils; + +import io.jsonwebtoken.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mobile.device.Device; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@Component +public class TokenUtil { + + static final String CLAIM_KEY_USERNAME = "sub"; + static final String CLAIM_KEY_AUDIENCE = "audience"; + static final String CLAIM_KEY_CREATED = "created"; + + private static final String AUDIENCE_UNKNOWN = "unknown"; + private static final String AUDIENCE_WEB = "web"; + private static final String AUDIENCE_MOBILE = "mobile"; + private static final String AUDIENCE_TABLET = "tablet"; + + @Value("${jwt.token.secret}") + private String secret; + + @Value("${jwt.token.expiration}") + private Long expiration; + + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public Long getExpiration() { + return expiration; + } + + public void setExpiration(Long expiration) { + this.expiration = expiration; + } + + private Claims getClaimsFromToken(String token) { + Claims claims; + try { + claims = Jwts.parser() + .setSigningKey(secret) + .parseClaimsJws(token) + .getBody(); + } catch (Exception e) { + claims = null; + } + return claims; + } + + + /** + * 生成token + * @param username 用户名 + * @param device org.springframework.mobile.device 设备判断对象 + * @return + */ + public String generateToken(String username, Device device) { + Map claims = new HashMap<>(); + claims.put(CLAIM_KEY_USERNAME, username); + claims.put(CLAIM_KEY_AUDIENCE, generateAudience(device)); + claims.put(CLAIM_KEY_CREATED, new Date()); + return generateToken(claims); + } + + private String generateToken(Map claims) { + return Jwts.builder() + .setClaims(claims) + .setExpiration(generateExpirationDate()) + .signWith(SignatureAlgorithm.HS512, this.secret) + .compact(); + } + + /** + * 生成token时间 = 当前时间 + expiration(properties中配置的失效时间) + * @return + */ + private Date generateExpirationDate() { + return new Date(System.currentTimeMillis() + expiration * 1000); + } + + /** + * 通过spring-mobile-device的device检测访问主体 + * @param device + * @return + */ + private String generateAudience(Device device) { + String audience = AUDIENCE_UNKNOWN; + if (device.isNormal()) { + audience = AUDIENCE_WEB;//PC端 + } else if (device.isTablet()) { + audience = AUDIENCE_TABLET;//平板 + } else if (device.isMobile()) { + audience = AUDIENCE_MOBILE;//手机 + } + return audience; + } + + /** + * 根据token获取用户名 + * @param token + * @return + */ + public String getUsernameFromToken(String token) { + String username; + try { + final Claims claims = getClaimsFromToken(token); + username = claims.getSubject(); + } catch (Exception e) { + username = null; + } + return username; + } + + /** + * 判断token失效时间是否到了 + * @param token + * @return + */ + private Boolean isTokenExpired(String token) { + final Date expiration = getExpirationDateFromToken(token); + return expiration.before(new Date()); + } + + /** + * 获取设置的token失效时间 + * @param token + * @return + */ + public Date getExpirationDateFromToken(String token) { + Date expiration; + try { + final Claims claims = getClaimsFromToken(token); + expiration = claims.getExpiration(); + } catch (Exception e) { + expiration = null; + } + return expiration; + } + + // /** + // * Token失效校验 + // * @param token token字符串 + // * @param loginInfo 用户信息 + // * @return + // */ + // public Boolean validateToken(String token, LoginInfo loginInfo) { + // final String username = getUsernameFromToken(token); + // return ( + // username.equals(loginInfo.getUsername()) + // && !isTokenExpired(token)); + // } + + public String refreshToken(String token) { + final Claims claims = this.getClaimsFromToken(token); + claims.put(CLAIM_KEY_CREATED, new Date()); + return generateToken(claims); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..afcd47c --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,18 @@ +#spring.datasource.url = jdbc:mysql://localhost:3306/shiro +#spring.datasource.username = root +#spring.datasource.password = root +#spring.datasource.driverClassName = com.mysql.jdbc.Driver +#spring.datasource.max-active=20 +#spring.datasource.max-idle=8 +#spring.datasource.min-idle=8 +#spring.datasource.initial-size=10 + +swagger.host = localhost:8080 + +#jwt.header= Authorization +jwt.token.secret= mySecret +jwt.token.expiration= 604800 + +spring.redis.host=localhost +spring.redis.database=0 +spring.redis.port=6379 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..91a080a --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,9 @@ + +spring: + jackson: + serialization: + INDENT_OUTPUT: true + date-format: yyyy-MM-dd HH:mm:ss + joda-date-time-format: yyyy-MM-dd HH:mm:ss + default-property-inclusion: non_null + time-zone: GMT+8 \ No newline at end of file diff --git a/src/main/resources/generatorConfig.xml b/src/main/resources/generatorConfig.xml new file mode 100644 index 0000000..2b2fbfb --- /dev/null +++ b/src/main/resources/generatorConfig.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+ + + +
+
\ No newline at end of file diff --git a/src/main/resources/shiro.sql b/src/main/resources/shiro.sql new file mode 100644 index 0000000..e2c974d --- /dev/null +++ b/src/main/resources/shiro.sql @@ -0,0 +1,146 @@ + +-- ---------------------------- +-- Table structure for sys_resource +-- ---------------------------- +DROP TABLE IF EXISTS `sys_resource`; +CREATE TABLE `sys_resource` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `type` varchar(255) DEFAULT '' COMMENT '权限类型:menu、button、url', + `name` varchar(255) NOT NULL COMMENT '权限名称', + `permission` varchar(255) NOT NULL COMMENT '权限字符串', + `icon` varchar(255) DEFAULT NULL, + `sort` int(11) DEFAULT '0', + `url` varchar(255) DEFAULT '', + `description` varchar(255) DEFAULT '' COMMENT '资源描述', + `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态值', + `parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '父ID', + `create_by` bigint(20) DEFAULT NULL, + `create_at` datetime NOT NULL, + `update_by` bigint(20) DEFAULT NULL, + `update_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uq_resource_type` (`type`,`permission`) USING BTREE, + KEY `create_by` (`create_by`), + KEY `update_by` (`update_by`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='资源(权限)表'; + + +-- ---------------------------- +-- Table structure for sys_role +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role`; +CREATE TABLE `sys_role` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `code` varchar(255) NOT NULL, + `remark` varchar(255) DEFAULT '', + `status` tinyint(1) NOT NULL DEFAULT '1', + `parent_id` bigint(20) DEFAULT NULL, + `create_by` bigint(20) DEFAULT NULL, + `create_at` datetime NOT NULL, + `update_by` bigint(20) DEFAULT NULL, + `update_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `create_by` (`create_by`), + KEY `update_by` (`update_by`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; + + +-- ---------------------------- +-- Table structure for sys_role_resource +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role_resource`; +CREATE TABLE `sys_role_resource` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `role_id` bigint(20) DEFAULT NULL, + `resource_id` bigint(20) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `role_id` (`role_id`), + KEY `resource_id` (`resource_id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; + +-- ---------------------------- +-- Table structure for sys_user +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user`; +CREATE TABLE `sys_user` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `mobile_phone` varchar(255) NOT NULL DEFAULT '' COMMENT '手机号码', + `user_name` varchar(50) DEFAULT NULL COMMENT '用户名', + `nickname` varchar(255) DEFAULT NULL COMMENT '昵称', + `password` varchar(255) NOT NULL COMMENT '密码', + `salt` varchar(255) DEFAULT '' COMMENT '加密混淆字符', + `signature` varchar(255) DEFAULT NULL COMMENT '个性签名', + `gender` tinyint(1) DEFAULT '0' COMMENT '性别', + `qq` bigint(20) DEFAULT NULL COMMENT 'QQ号码', + `email` varchar(255) DEFAULT NULL COMMENT '邮箱地址', + `avatar` varchar(500) DEFAULT '' COMMENT '头像图片路径', + `province` varchar(50) DEFAULT '' COMMENT '省', + `city` varchar(50) DEFAULT '' COMMENT '市', + `reg_ip` varchar(50) DEFAULT NULL COMMENT '注册时IP地址', + `score` int(10) DEFAULT '0' COMMENT '积分值', + `status` int(10) DEFAULT '1' COMMENT '状态:0禁用 1正常', + `create_by` bigint(20) DEFAULT NULL, + `create_at` datetime DEFAULT NULL, + `update_by` bigint(20) DEFAULT NULL, + `update_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uq_user_name` (`user_name`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表'; + +-- ---------------------------- +-- Table structure for sys_user_role +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user_role`; +CREATE TABLE `sys_user_role` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `user_id` bigint(20) NOT NULL, + `role_id` bigint(20) NOT NULL, + PRIMARY KEY (`id`), + KEY `fk_user_roles` (`user_id`), + KEY `fk_role_users` (`role_id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; + + + +-- ---------------------------- +-- Records of sys_user +-- ---------------------------- +INSERT INTO `sys_user` VALUES ('1', '18966668888', 'super', '超级管理员', 'e10adc3949ba59abbe56e057f20f883e', null, null, null, null, '', null, null, null, null, null, '1', null, '2015-09-28 17:47:18', null, '2015-09-30 17:36:16'); +INSERT INTO `sys_user` VALUES ('2', '13988886666', 'admin', '系统管理员A', 'e10adc3949ba59abbe56e057f20f883e', null, null, null, '1234567', 'super@millinch.com', null, null, null, null, null, '1', null, '2015-09-29 17:47:22', null, '2015-09-30 17:32:07'); + +-- ---------------------------- +-- Records of sys_role +-- ---------------------------- +INSERT INTO `sys_role` VALUES ('1', '超级管理员', 'superManager', '拥有所有权限', '1', null, '0', '2015-09-01 14:36:16', null, '2016-01-03 22:29:58'); +INSERT INTO `sys_role` VALUES ('2', '系统管理员', 'systemManager', '拥有部分权限', '1', null, '0', '2015-08-30 18:03:47', null, '2015-08-30 18:03:47'); +INSERT INTO `sys_role` VALUES ('3', '角色1', 'role1', 'nothing 34', '1', null, null, '2015-10-05 18:20:35', null, '2015-10-05 18:35:57'); + +-- ---------------------------- +-- Records of sys_resource +-- ---------------------------- +INSERT INTO `sys_resource` VALUES ('1', '菜单', '系统管理', 'system:*', 'fa fa-dashboard', '1', '', '', '1', '0', '0', '2015-07-01 19:33:21', null, '2015-10-09 10:34:05'); +INSERT INTO `sys_resource` VALUES ('2', '菜单', '角色管理', 'system:role:*', 'fa fa-male', '12', '/role/config', '', '1', '1', '0', '2015-07-01 19:38:38', null, '2015-07-01 19:38:38'); +INSERT INTO `sys_resource` VALUES ('3', '菜单', '密码修改', 'system:password', null, '14', '/user/password/edition', '', '1', '1', '0', '2015-07-01 19:38:51', null, '2015-07-01 19:39:51'); +INSERT INTO `sys_resource` VALUES ('4', '菜单', '操作日志', 'system:log:*', null, '15', '/handle/operation/log', '', '1', '1', '0', '2015-07-01 19:40:37', null, '2015-07-01 19:40:37'); +INSERT INTO `sys_resource` VALUES ('5', 'URL', '新增角色', 'system:role:create', null, '13', '/role/addition', '', '1', '1', '0', '2015-07-01 19:41:21', null, '2015-10-08 16:45:43'); +INSERT INTO `sys_resource` VALUES ('6', '菜单', '用户管理', 'system:admin:*', 'fa fa-users', '11', '/user/config', '', '1', '1', '0', '2015-07-01 19:34:38', null, '2015-07-01 19:34:38'); +INSERT INTO `sys_resource` VALUES ('7', 'URL', '新增用户', 'system:admin:create', '', null, '/user/addition', 'bbb', '1', '0', '0', '2015-08-30 18:29:56', null, '2015-10-09 11:33:03'); + +-- ---------------------------- +-- Records of sys_role_resource +-- ---------------------------- +INSERT INTO `sys_role_resource` VALUES ('1', '1', '1'); +INSERT INTO `sys_role_resource` VALUES ('2', '1', '2'); +INSERT INTO `sys_role_resource` VALUES ('3', '1', '3'); +INSERT INTO `sys_role_resource` VALUES ('4', '1', '4'); +INSERT INTO `sys_role_resource` VALUES ('5', '1', '5'); +INSERT INTO `sys_role_resource` VALUES ('6', '1', '6'); +INSERT INTO `sys_role_resource` VALUES ('7', '1', '7'); +INSERT INTO `sys_role_resource` VALUES ('8', '2', '2'); + +-- ---------------------------- +-- Records of sys_user_role +-- ---------------------------- +INSERT INTO `sys_user_role` VALUES ('1', '1', '1'); +INSERT INTO `sys_user_role` VALUES ('2', '2', '2'); diff --git a/src/test/java/net/ameizi/ApplicationTests.java b/src/test/java/net/ameizi/ApplicationTests.java new file mode 100644 index 0000000..0838b98 --- /dev/null +++ b/src/test/java/net/ameizi/ApplicationTests.java @@ -0,0 +1,16 @@ +package net.ameizi; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +}