Commit 7e6f0a35 by tongpuxin

云教投放落地页配置后台、小程序短链接配置后台

parent 3402ab3e
<?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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.app.framework</groupId>
<artifactId>ydl-admin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>yunjiao-admin</name>
<description>云教投放落地页配置后台、小程序短链接配置后台</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<mybatis-plus.version>3.3.2</mybatis-plus.version>
<mysql-connector-java.version>8.0.11</mysql-connector-java.version>
<com.alibaba.druid.version>1.1.10</com.alibaba.druid.version>
<com.alibaba.fastjson.version>1.2.83</com.alibaba.fastjson.version>
<hutool.version>5.3.10</hutool.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons.codec.version>1.10</commons.codec.version>
<commons.io.version>2.5</commons.io.version>
<commons.lang.version>2.6</commons.lang.version>
<commons.lang3.version>3.5</commons.lang3.version>
<aspectj.aspectjweaver.version>1.8.5</aspectj.aspectjweaver.version>
<lombok.version>1.18.6</lombok.version>
<org.apache.shiro.version>1.6.0</org.apache.shiro.version>
</properties>
<dependencies>
<!-- 引用公共模块 -->
<dependency>
<groupId>cn.gladiolus</groupId>
<artifactId>gladiolus-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${com.alibaba.druid.version}</version>
<exclusions>
<exclusion>
<groupId>com.alibaba</groupId>
<artifactId>jconsole</artifactId>
</exclusion>
<exclusion>
<groupId>com.alibaba</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${com.alibaba.fastjson.version}</version>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons.codec.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
<!-- jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- freemarker依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--Apache Shiro所需的jar包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>net.mingsoft</groupId>
<artifactId>shiro-freemarker-tags</artifactId>
<version>1.0.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
</exclusion>
<exclusion>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- sqlite3驱动包 -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.27.2.1</version>
</dependency>
<!-- 多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<configuration>
<!-- 指定该Main Class为全局的唯一入口 -->
<mainClass>com.app.YunjiaoAdminApplication</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skipTests>true</skipTests> <!--默认关掉单元测试 -->
</configuration>
</plugin>
<!-- 打war包时排除tomcat开头的6个jar包,否则外部tomcat下无法启动 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>
WEB-INF/lib/tomcat-*.jar
</packagingExcludes>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!-- 控制资源文件的拷贝 -->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
package com.app;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* 启动类
* SpringBoot运行:默认(仅有main方法)
* 外置tomcat部署:继承 SpringBootServletInitializer 并重写 configure 方法
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.app.**.dao"})
@EnableAsync(proxyTargetClass = true)
public class YunjiaoAdminApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 注意这里要指向原先用main方法执行的Application启动类
return builder.sources(YunjiaoAdminApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(YunjiaoAdminApplication.class, args);
}
}
package com.app.admin.common.ueditor;
import com.app.admin.common.ueditor.define.ActionMap;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.State;
import com.app.admin.common.ueditor.hunter.FileManager;
import com.app.admin.common.ueditor.hunter.ImageHunter;
import com.app.admin.common.ueditor.upload.Uploader;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class ActionEnter {
private HttpServletRequest request = null;
private String rootPath = "/";
private String configRootPath = null;
private String actionType = null;
private ConfigManager configManager = null;
public ActionEnter ( HttpServletRequest request, String configRootPath ) {
this.request = request;
this.configRootPath = configRootPath;
this.actionType = request.getParameter( "action" );
this.configManager = ConfigManager.getInstance( this.rootPath, this.configRootPath );
}
public String exec () {
String callbackName = this.request.getParameter("callback");
if ( callbackName != null ) {
if ( !validCallbackName( callbackName ) ) {
return new BaseState( false, AppInfo.ILLEGAL ).toJSONString();
}
return callbackName+"("+this.invoke()+");";
} else {
return this.invoke();
}
}
public String invoke() {
if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
}
if ( this.configManager == null || !this.configManager.valid() ) {
return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
}
State state = null;
int actionCode = ActionMap.getType( this.actionType );
Map<String, Object> conf = null;
switch ( actionCode ) {
case ActionMap.CONFIG:
return this.configManager.getAllConfig().toString();
case ActionMap.UPLOAD_IMAGE:
case ActionMap.UPLOAD_SCRAWL:
case ActionMap.UPLOAD_VIDEO:
case ActionMap.UPLOAD_FILE:
conf = this.configManager.getConfig( actionCode );
state = new Uploader( request, conf ).doExec();
break;
case ActionMap.CATCH_IMAGE:
conf = configManager.getConfig( actionCode );
String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
state = new ImageHunter( request, conf ).capture( list );
break;
case ActionMap.LIST_IMAGE:
case ActionMap.LIST_FILE:
conf = configManager.getConfig( actionCode );
int start = this.getStartIndex();
state = new FileManager( conf ).listFile( start );
break;
}
return state.toJSONString();
}
public int getStartIndex () {
String start = this.request.getParameter( "start" );
try {
return Integer.parseInt( start );
} catch ( Exception e ) {
return 0;
}
}
/**
* callback参数验证
*/
public boolean validCallbackName ( String name ) {
if ( name.matches( "^[a-zA-Z_]+[\\w0-9_]*$" ) ) {
return true;
}
return false;
}
}
\ No newline at end of file
package com.app.admin.common.ueditor;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.define.ActionMap;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* 配置管理器
* @author hancong03@baidu.com
*
*/
public final class ConfigManager {
private final String rootPath;
private final String configRootPath;
private static final String configFileName = "config.json";
private JSONObject jsonConfig = null;
// 涂鸦上传filename定义
private final static String SCRAWL_FILE_NAME = "scrawl";
// 远程图片抓取filename定义
private final static String REMOTE_FILE_NAME = "remote";
/*
* 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件
*/
private ConfigManager ( String rootPath, String configRootPath ) throws FileNotFoundException, IOException {
rootPath = rootPath.replace( "\\", "/" );
this.rootPath = rootPath;
this.configRootPath = configRootPath;
this.initEnv();
}
/**
* 配置管理器构造工厂
* @param rootPath 服务器根路径
* @param configRootPath 前端配置文件路径
* @return 配置管理器实例或者null
*/
public static ConfigManager getInstance ( String rootPath, String configRootPath ) {
try {
return new ConfigManager(rootPath, configRootPath);
} catch ( Exception e ) {
e.printStackTrace();
return null;
}
}
// 验证配置文件加载是否正确
public boolean valid () {
return this.jsonConfig != null;
}
public JSONObject getAllConfig () {
return this.jsonConfig;
}
public Map<String, Object> getConfig ( int type ) {
Map<String, Object> conf = new HashMap<String, Object>();
String savePath = null;
switch ( type ) {
case ActionMap.UPLOAD_FILE:
conf.put( "isBase64", "false" );
conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) );
conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) );
savePath = this.jsonConfig.getString( "filePathFormat" );
break;
case ActionMap.UPLOAD_IMAGE:
conf.put( "isBase64", "false" );
conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) );
conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) );
savePath = this.jsonConfig.getString( "imagePathFormat" );
break;
case ActionMap.UPLOAD_VIDEO:
conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) );
conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) );
savePath = this.jsonConfig.getString( "videoPathFormat" );
break;
case ActionMap.UPLOAD_SCRAWL:
conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME );
conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) );
conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) );
conf.put( "isBase64", "true" );
savePath = this.jsonConfig.getString( "scrawlPathFormat" );
break;
case ActionMap.CATCH_IMAGE:
conf.put( "filename", ConfigManager.REMOTE_FILE_NAME );
conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) );
conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" );
savePath = this.jsonConfig.getString( "catcherPathFormat" );
break;
case ActionMap.LIST_IMAGE:
conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) );
conf.put( "count", this.jsonConfig.getInteger( "imageManagerListSize" ) );
break;
case ActionMap.LIST_FILE:
conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) );
conf.put( "count", this.jsonConfig.getInteger( "fileManagerListSize" ) );
break;
}
conf.put( "savePath", savePath );
conf.put( "rootPath", this.rootPath );
return conf;
}
private void initEnv () throws FileNotFoundException, IOException {
String configContent = this.readFile( this.getConfigPath() );
try{
JSONObject jsonConfig = (JSONObject) JSONObject.parse( configContent );
this.jsonConfig = jsonConfig;
} catch ( Exception e ) {
this.jsonConfig = null;
}
}
private String getConfigPath () {
return this.configRootPath + File.separator + ConfigManager.configFileName;
}
private String[] getArray ( String key ) {
JSONArray jsonArray = this.jsonConfig.getJSONArray( key );
String[] result = new String[ jsonArray.size() ];
for ( int i = 0, len = jsonArray.size(); i < len; i++ ) {
result[i] = jsonArray.getString( i );
}
return result;
}
private String readFile ( String path ) throws IOException {
StringBuilder builder = new StringBuilder();
try {
Resource resource = new ClassPathResource(path);
InputStreamReader reader = new InputStreamReader(resource.getInputStream(), "UTF-8" );
BufferedReader bfReader = new BufferedReader( reader );
String tmpContent = null;
while ( ( tmpContent = bfReader.readLine() ) != null ) {
builder.append( tmpContent );
}
bfReader.close();
reader.close();
} catch ( UnsupportedEncodingException e ) {
// 忽略
e.printStackTrace();
}
return this.filter( builder.toString() );
}
// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
private String filter ( String input ) {
return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" );
}
}
package com.app.admin.common.ueditor;
public class Encoder {
public static String toUnicode ( String input ) {
StringBuilder builder = new StringBuilder();
char[] chars = input.toCharArray();
for ( char ch : chars ) {
if ( ch < 256 ) {
builder.append( ch );
} else {
builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) );
}
}
return builder.toString();
}
}
\ No newline at end of file
package com.app.admin.common.ueditor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathFormat {
private static final String TIME = "time";
private static final String FULL_YEAR = "yyyy";
private static final String YEAR = "yy";
private static final String MONTH = "mm";
private static final String DAY = "dd";
private static final String HOUR = "hh";
private static final String MINUTE = "ii";
private static final String SECOND = "ss";
private static final String RAND = "rand";
private static Date currentDate = null;
public static String parse ( String input ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
Matcher matcher = pattern.matcher(input);
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) );
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 格式化路径, 把windows路径替换成标准路径
* @param input 待格式化的路径
* @return 格式化后的路径
*/
public static String format ( String input ) {
return input.replace( "\\", "/" );
}
public static String parse ( String input, String filename ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
Matcher matcher = pattern.matcher(input);
String matchStr = null;
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matchStr = matcher.group( 1 );
if ( matchStr.indexOf( "filename" ) != -1 ) {
filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" );
matcher.appendReplacement(sb, filename );
} else {
matcher.appendReplacement(sb, PathFormat.getString( matchStr ) );
}
}
matcher.appendTail(sb);
return sb.toString();
}
private static String getString ( String pattern ) {
pattern = pattern.toLowerCase();
// time 处理
if ( pattern.indexOf( PathFormat.TIME ) != -1 ) {
return PathFormat.getTimestamp();
} else if ( pattern.indexOf( PathFormat.FULL_YEAR ) != -1 ) {
return PathFormat.getFullYear();
} else if ( pattern.indexOf( PathFormat.YEAR ) != -1 ) {
return PathFormat.getYear();
} else if ( pattern.indexOf( PathFormat.MONTH ) != -1 ) {
return PathFormat.getMonth();
} else if ( pattern.indexOf( PathFormat.DAY ) != -1 ) {
return PathFormat.getDay();
} else if ( pattern.indexOf( PathFormat.HOUR ) != -1 ) {
return PathFormat.getHour();
} else if ( pattern.indexOf( PathFormat.MINUTE ) != -1 ) {
return PathFormat.getMinute();
} else if ( pattern.indexOf( PathFormat.SECOND ) != -1 ) {
return PathFormat.getSecond();
} else if ( pattern.indexOf( PathFormat.RAND ) != -1 ) {
return PathFormat.getRandom( pattern );
}
return pattern;
}
private static String getTimestamp () {
return System.currentTimeMillis() + "";
}
private static String getFullYear () {
return new SimpleDateFormat( "yyyy" ).format( PathFormat.currentDate );
}
private static String getYear () {
return new SimpleDateFormat( "yy" ).format( PathFormat.currentDate );
}
private static String getMonth () {
return new SimpleDateFormat( "MM" ).format( PathFormat.currentDate );
}
private static String getDay () {
return new SimpleDateFormat( "dd" ).format( PathFormat.currentDate );
}
private static String getHour () {
return new SimpleDateFormat( "HH" ).format( PathFormat.currentDate );
}
private static String getMinute () {
return new SimpleDateFormat( "mm" ).format( PathFormat.currentDate );
}
private static String getSecond () {
return new SimpleDateFormat( "ss" ).format( PathFormat.currentDate );
}
private static String getRandom ( String pattern ) {
int length = 0;
pattern = pattern.split( ":" )[ 1 ].trim();
length = Integer.parseInt( pattern );
return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length );
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
package com.app.admin.common.ueditor.define;
import java.util.HashMap;
import java.util.Map;
/**
* 定义请求action类型
* @author hancong03@baidu.com
*
*/
@SuppressWarnings("serial")
public final class ActionMap {
public static final Map<String, Integer> mapping;
// 获取配置请求
public static final int CONFIG = 0;
public static final int UPLOAD_IMAGE = 1;
public static final int UPLOAD_SCRAWL = 2;
public static final int UPLOAD_VIDEO = 3;
public static final int UPLOAD_FILE = 4;
public static final int CATCH_IMAGE = 5;
public static final int LIST_FILE = 6;
public static final int LIST_IMAGE = 7;
static {
mapping = new HashMap<String, Integer>(){{
put( "config", ActionMap.CONFIG );
put( "uploadimage", ActionMap.UPLOAD_IMAGE );
put( "uploadscrawl", ActionMap.UPLOAD_SCRAWL );
put( "uploadvideo", ActionMap.UPLOAD_VIDEO );
put( "uploadfile", ActionMap.UPLOAD_FILE );
put( "catchimage", ActionMap.CATCH_IMAGE );
put( "listfile", ActionMap.LIST_FILE );
put( "listimage", ActionMap.LIST_IMAGE );
}};
}
public static int getType ( String key ) {
return ActionMap.mapping.get( key );
}
}
package com.app.admin.common.ueditor.define;
public enum ActionState {
UNKNOW_ERROR
}
package com.app.admin.common.ueditor.define;
import java.util.HashMap;
import java.util.Map;
public final class AppInfo {
public static final int SUCCESS = 0;
public static final int MAX_SIZE = 1;
public static final int PERMISSION_DENIED = 2;
public static final int FAILED_CREATE_FILE = 3;
public static final int IO_ERROR = 4;
public static final int NOT_MULTIPART_CONTENT = 5;
public static final int PARSE_REQUEST_ERROR = 6;
public static final int NOTFOUND_UPLOAD_DATA = 7;
public static final int NOT_ALLOW_FILE_TYPE = 8;
public static final int INVALID_ACTION = 101;
public static final int CONFIG_ERROR = 102;
public static final int PREVENT_HOST = 201;
public static final int CONNECTION_ERROR = 202;
public static final int REMOTE_FAIL = 203;
public static final int NOT_DIRECTORY = 301;
public static final int NOT_EXIST = 302;
public static final int ILLEGAL = 401;
public static Map<Integer, String> info = new HashMap<Integer, String>(){{
put( AppInfo.SUCCESS, "SUCCESS" );
// 无效的Action
put( AppInfo.INVALID_ACTION, "\u65E0\u6548\u7684Action" );
// 配置文件初始化失败
put( AppInfo.CONFIG_ERROR, "\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u5931\u8D25" );
// 抓取远程图片失败
put( AppInfo.REMOTE_FAIL, "\u6293\u53D6\u8FDC\u7A0B\u56FE\u7247\u5931\u8D25" );
// 被阻止的远程主机
put( AppInfo.PREVENT_HOST, "\u88AB\u963B\u6B62\u7684\u8FDC\u7A0B\u4E3B\u673A" );
// 远程连接出错
put( AppInfo.CONNECTION_ERROR, "\u8FDC\u7A0B\u8FDE\u63A5\u51FA\u9519" );
// "文件大小超出限制"
put( AppInfo.MAX_SIZE, "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u9650\u5236" );
// 权限不足, 多指写权限
put( AppInfo.PERMISSION_DENIED, "\u6743\u9650\u4E0D\u8DB3" );
// 创建文件失败
put( AppInfo.FAILED_CREATE_FILE, "\u521B\u5EFA\u6587\u4EF6\u5931\u8D25" );
// IO错误
put( AppInfo.IO_ERROR, "IO\u9519\u8BEF" );
// 上传表单不是multipart/form-data类型
put( AppInfo.NOT_MULTIPART_CONTENT, "\u4E0A\u4F20\u8868\u5355\u4E0D\u662Fmultipart/form-data\u7C7B\u578B" );
// 解析上传表单错误
put( AppInfo.PARSE_REQUEST_ERROR, "\u89E3\u6790\u4E0A\u4F20\u8868\u5355\u9519\u8BEF" );
// 未找到上传数据
put( AppInfo.NOTFOUND_UPLOAD_DATA, "\u672A\u627E\u5230\u4E0A\u4F20\u6570\u636E" );
// 不允许的文件类型
put( AppInfo.NOT_ALLOW_FILE_TYPE, "\u4E0D\u5141\u8BB8\u7684\u6587\u4EF6\u7C7B\u578B" );
// 指定路径不是目录
put( AppInfo.NOT_DIRECTORY, "\u6307\u5B9A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55" );
// 指定路径并不存在
put( AppInfo.NOT_EXIST, "\u6307\u5B9A\u8DEF\u5F84\u5E76\u4E0D\u5B58\u5728" );
// callback参数名不合法
put( AppInfo.ILLEGAL, "Callback\u53C2\u6570\u540D\u4E0D\u5408\u6CD5" );
}};
public static String getStateInfo ( int key ) {
return AppInfo.info.get( key );
}
}
package com.app.admin.common.ueditor.define;
import com.app.admin.common.ueditor.Encoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class BaseState implements State {
private boolean state = false;
private String info = null;
private Map<String, String> infoMap = new HashMap<String, String>();
public BaseState () {
this.state = true;
}
public BaseState ( boolean state ) {
this.setState( state );
}
public BaseState ( boolean state, String info ) {
this.setState( state );
this.info = info;
}
public BaseState ( boolean state, int infoCode ) {
this.setState( state );
this.info = AppInfo.getStateInfo( infoCode );
}
public boolean isSuccess () {
return this.state;
}
public void setState ( boolean state ) {
this.state = state;
}
public void setInfo ( String info ) {
this.info = info;
}
public void setInfo ( int infoCode ) {
this.info = AppInfo.getStateInfo( infoCode );
}
@Override
public String toJSONString() {
return this.toString();
}
public String toString () {
String key = null;
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info;
StringBuilder builder = new StringBuilder();
builder.append( "{\"state\": \"" + stateVal + "\"" );
Iterator<String> iterator = this.infoMap.keySet().iterator();
while ( iterator.hasNext() ) {
key = iterator.next();
builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" );
}
builder.append( "}" );
return Encoder.toUnicode( builder.toString() );
}
@Override
public void putInfo(String name, String val) {
this.infoMap.put(name, val);
}
@Override
public void putInfo(String name, long val) {
this.putInfo(name, val+"");
}
}
package com.app.admin.common.ueditor.define;
import java.util.HashMap;
import java.util.Map;
public class FileType {
public static final String JPG = "JPG";
private static final Map<String, String> types = new HashMap<String, String>(){{
put( FileType.JPG, ".jpg" );
}};
public static String getSuffix ( String key ) {
return FileType.types.get( key );
}
/**
* 根据给定的文件名,获取其后缀信息
* @param filename
* @return
*/
public static String getSuffixByFilename ( String filename ) {
return filename.substring( filename.lastIndexOf( "." ) ).toLowerCase();
}
}
package com.app.admin.common.ueditor.define;
import java.util.HashMap;
import java.util.Map;
public class MIMEType {
public static final Map<String, String> types = new HashMap<String, String>(){{
put( "image/gif", ".gif" );
put( "image/jpeg", ".jpg" );
put( "image/jpg", ".jpg" );
put( "image/png", ".png" );
put( "image/bmp", ".bmp" );
}};
public static String getSuffix ( String mime ) {
return MIMEType.types.get( mime );
}
}
package com.app.admin.common.ueditor.define;
import com.app.admin.common.ueditor.Encoder;
import java.util.*;
/**
* 多状态集合状态
* 其包含了多个状态的集合, 其本身自己也是一个状态
* @author hancong03@baidu.com
*
*/
public class MultiState implements State {
private boolean state = false;
private String info = null;
private Map<String, Long> intMap = new HashMap<String, Long>();
private Map<String, String> infoMap = new HashMap<String, String>();
private List<String> stateList = new ArrayList<String>();
public MultiState ( boolean state ) {
this.state = state;
}
public MultiState ( boolean state, String info ) {
this.state = state;
this.info = info;
}
public MultiState ( boolean state, int infoKey ) {
this.state = state;
this.info = AppInfo.getStateInfo( infoKey );
}
@Override
public boolean isSuccess() {
return this.state;
}
public void addState ( State state ) {
stateList.add( state.toJSONString() );
}
/**
* 该方法调用无效果
*/
@Override
public void putInfo(String name, String val) {
this.infoMap.put(name, val);
}
@Override
public String toJSONString() {
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info;
StringBuilder builder = new StringBuilder();
builder.append( "{\"state\": \"" + stateVal + "\"" );
// 数字转换
Iterator<String> iterator = this.intMap.keySet().iterator();
while ( iterator.hasNext() ) {
stateVal = iterator.next();
builder.append( ",\""+ stateVal +"\": " + this.intMap.get( stateVal ) );
}
iterator = this.infoMap.keySet().iterator();
while ( iterator.hasNext() ) {
stateVal = iterator.next();
builder.append( ",\""+ stateVal +"\": \"" + this.infoMap.get( stateVal ) + "\"" );
}
builder.append( ", list: [" );
iterator = this.stateList.iterator();
while ( iterator.hasNext() ) {
builder.append( iterator.next() + "," );
}
if ( this.stateList.size() > 0 ) {
builder.deleteCharAt( builder.length() - 1 );
}
builder.append( " ]}" );
return Encoder.toUnicode( builder.toString() );
}
@Override
public void putInfo(String name, long val) {
this.intMap.put( name, val );
}
}
package com.app.admin.common.ueditor.define;
/**
* 处理状态接口
* @author hancong03@baidu.com
*
*/
public interface State {
public boolean isSuccess ();
public void putInfo( String name, String val );
public void putInfo ( String name, long val );
public String toJSONString ();
}
package com.app.admin.common.ueditor.hunter;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.MultiState;
import com.app.admin.common.ueditor.define.State;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
public class FileManager {
private String dir = null;
private String rootPath = null;
private String[] allowFiles = null;
private int count = 0;
public FileManager ( Map<String, Object> conf ) {
this.rootPath = (String)conf.get( "rootPath" );
this.dir = this.rootPath + (String)conf.get( "dir" );
this.allowFiles = this.getAllowFiles( conf.get("allowFiles") );
this.count = (Integer)conf.get( "count" );
}
public State listFile (int index ) {
File dir = new File( this.dir );
State state = null;
if ( !dir.exists() ) {
return new BaseState( false, AppInfo.NOT_EXIST );
}
if ( !dir.isDirectory() ) {
return new BaseState( false, AppInfo.NOT_DIRECTORY );
}
Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true );
if ( index < 0 || index > list.size() ) {
state = new MultiState( true );
} else {
Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count );
state = this.getState( fileList );
}
state.putInfo( "start", index );
state.putInfo( "total", list.size() );
return state;
}
private State getState ( Object[] files ) {
MultiState state = new MultiState( true );
BaseState fileState = null;
File file = null;
for ( Object obj : files ) {
if ( obj == null ) {
break;
}
file = (File)obj;
fileState = new BaseState( true );
fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) );
state.addState( fileState );
}
return state;
}
private String getPath ( File file ) {
String path = file.getAbsolutePath();
return path.replace( this.rootPath, "/" );
}
private String[] getAllowFiles ( Object fileExt ) {
String[] exts = null;
String ext = null;
if ( fileExt == null ) {
return new String[ 0 ];
}
exts = (String[])fileExt;
for ( int i = 0, len = exts.length; i < len; i++ ) {
ext = exts[ i ];
exts[ i ] = ext.replace( ".", "" );
}
return exts;
}
}
package com.app.admin.common.ueditor.hunter;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.*;
import com.app.admin.common.ueditor.upload.StorageManager;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.utils.file.UploadUtil;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 图片抓取器
* @author hancong03@baidu.com
*
*/
public class ImageHunter {
private HttpServletRequest request = null;
private String filename = null;
private String savePath = null;
private List<String> allowTypes = null;
private long maxSize = -1;
private List<String> filters = null;
public ImageHunter ( HttpServletRequest request, Map<String, Object> conf ) {
this.request = request;
this.filename = (String)conf.get( "filename" );
this.savePath = (String)conf.get( "savePath" );
this.maxSize = (Long)conf.get( "maxSize" );
this.allowTypes = Arrays.asList( (String[])conf.get( "allowFiles" ) );
this.filters = Arrays.asList( (String[])conf.get( "filter" ) );
}
public State capture (String[] list ) {
MultiState state = new MultiState( true );
for ( String source : list ) {
state.addState( captureRemoteData( source ) );
}
return state;
}
public State captureRemoteData ( String urlStr ) {
HttpURLConnection connection = null;
URL url = null;
String suffix = null;
try {
url = new URL( urlStr );
if ( !validHost( url.getHost() ) ) {
return new BaseState( false, AppInfo.PREVENT_HOST );
}
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects( true );
connection.setUseCaches( true );
if ( !validContentState( connection.getResponseCode() ) ) {
return new BaseState( false, AppInfo.CONNECTION_ERROR );
}
suffix = MIMEType.getSuffix( connection.getContentType() );
if ( !validFileType( suffix ) ) {
return new BaseState( false, AppInfo.NOT_ALLOW_FILE_TYPE );
}
if ( !validFileSize( connection.getContentLength() ) ) {
return new BaseState( false, AppInfo.MAX_SIZE );
}
SysConfigService sysConfigService = SpringUtil.getBean(SysConfigService.class);
JSONObject object = sysConfigService.getJson("UploadFile");
UploadUtil.init(object.getString("uploadPath"), object.getString("baseUrl"));
StringBuilder uPath = new StringBuilder();
uPath.append(PathFormat.parse(UploadUtil.getUploadPath(savePath), filename)).append(suffix);
State state = StorageManager.saveFileByInputStream( connection.getInputStream(), uPath.toString() );
if ( state.isSuccess() ) {
StringBuilder new_file_url = new StringBuilder();
new_file_url.append(PathFormat.parse(UploadUtil.getBaseUrl(request, savePath), filename)).append(suffix);
state.putInfo( "url", new_file_url.toString() );
state.putInfo( "source", urlStr );
}
return state;
} catch ( Exception e ) {
return new BaseState( false, AppInfo.REMOTE_FAIL );
}
}
private String getPath ( String savePath, String filename, String suffix ) {
return PathFormat.parse( savePath + suffix, filename );
}
private boolean validHost ( String hostname ) {
try {
InetAddress ip = InetAddress.getByName(hostname);
if (ip.isSiteLocalAddress()) {
return false;
}
} catch (UnknownHostException e) {
return false;
}
return !filters.contains( hostname );
}
private boolean validContentState ( int code ) {
return HttpURLConnection.HTTP_OK == code;
}
private boolean validFileType ( String type ) {
return this.allowTypes.contains( type );
}
private boolean validFileSize ( int size ) {
return size < this.maxSize;
}
}
package com.app.admin.common.ueditor.servlet;
import com.app.admin.common.ueditor.ActionEnter;
import org.apache.commons.lang.StringUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 百度编辑器文件上传(管理)入口
*/
public class BaiduUeditorServlet extends HttpServlet {
private String configRootPath;
public void init(ServletConfig config) {
configRootPath = config.getInitParameter("configRootPath");
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html");
if (StringUtils.isBlank(configRootPath)) {
configRootPath = "static/common/plugins/ueditor";
}
response.getWriter().write(new ActionEnter(request, configRootPath).exec());
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.app.admin.common.ueditor.upload;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.FileType;
import com.app.admin.common.ueditor.define.State;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.utils.file.UploadUtil;
import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public final class Base64Uploader {
public static State save(HttpServletRequest request, Map<String, Object> conf) {
String filedName = (String) conf.get("fieldName");
String content = request.getParameter(filedName);
byte[] data = decode(content);
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validSize(data, maxSize)) {
return new BaseState(false, AppInfo.MAX_SIZE);
}
String suffix = FileType.getSuffix("JPG");
String savePath = (String) conf.get("savePath");
String filename = (String) conf.get("filename");
savePath = PathFormat.parse(savePath, filename);
SysConfigService sysConfigService = SpringUtil.getBean(SysConfigService.class);
JSONObject object = sysConfigService.getJson("UploadFile");
UploadUtil.init(object.getString("uploadPath"), object.getString("baseUrl"));
StringBuilder uPath = new StringBuilder();
uPath.append(UploadUtil.getUploadPath(savePath)).append(suffix);
State storageState = StorageManager.saveBinaryFile(data, uPath.toString());
if (storageState.isSuccess()) {
StringBuilder new_file_url = new StringBuilder();
new_file_url.append(UploadUtil.getBaseUrl(request, savePath)).append(suffix);
storageState.putInfo("url", new_file_url.toString());
storageState.putInfo("type", suffix);
storageState.putInfo("original", "");
}
return storageState;
}
private static byte[] decode(String content) {
return Base64.decodeBase64(content);
}
private static boolean validSize(byte[] data, long length) {
return data.length <= length;
}
}
\ No newline at end of file
package com.app.admin.common.ueditor.upload;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.FileType;
import com.app.admin.common.ueditor.define.State;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.utils.file.UploadUtil;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class BinaryUploader {
public static final State save(HttpServletRequest request,
Map<String, Object> conf) {
FileItemStream fileStream = null;
boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;
if (!ServletFileUpload.isMultipartContent(request)) {
return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
}
ServletFileUpload upload = new ServletFileUpload(
new DiskFileItemFactory());
if ( isAjaxUpload ) {
upload.setHeaderEncoding( "UTF-8" );
}
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
fileStream = iterator.next();
if (!fileStream.isFormField())
break;
fileStream = null;
}
if (fileStream == null) {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
String originFileName = fileStream.getName();
String suffix = FileType.getSuffixByFilename(originFileName);
if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
long maxSize = ((Long) conf.get("maxSize")).longValue();
String savePath = (String) conf.get("savePath");
String filename = (String) conf.get("filename");
savePath = PathFormat.parse(savePath, filename);
SysConfigService sysConfigService = SpringUtil.getBean(SysConfigService.class);
JSONObject object = sysConfigService.getJson("UploadFile");
UploadUtil.init(object.getString("uploadPath"), object.getString("baseUrl"));
StringBuilder uPath = new StringBuilder();
uPath.append(UploadUtil.getUploadPath(savePath)).append(suffix);
InputStream is = fileStream.openStream();
State storageState = StorageManager.saveFileByInputStream(is, uPath.toString(), maxSize);
is.close();
if (storageState.isSuccess()) {
StringBuilder new_file_url = new StringBuilder();
new_file_url.append(UploadUtil.getBaseUrl(request, savePath)).append(suffix);
storageState.putInfo("url", new_file_url.toString());
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName + suffix);
}
return storageState;
} catch (FileUploadException e) {
return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
}
private static boolean validType(String type, String[] allowTypes) {
List<String> list = Arrays.asList(allowTypes);
return list.contains(type);
}
}
package com.app.admin.common.ueditor.upload;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.State;
import org.apache.commons.io.FileUtils;
import java.io.*;
public class StorageManager {
public static final int BUFFER_SIZE = 8192;
public StorageManager() {
}
public static State saveBinaryFile(byte[] data, String path) {
File file = new File(path);
State state = valid(file);
if (!state.isSuccess()) {
return state;
}
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bos.write(data);
bos.flush();
bos.close();
} catch (IOException ioe) {
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true, file.getAbsolutePath());
state.putInfo( "size", data.length );
state.putInfo( "title", file.getName() );
return state;
}
public static State saveFileByInputStream(InputStream is, String path,
long maxSize) {
State state = null;
File tmpFile = getTmpFile();
byte[] dataBuf = new byte[ 2048 ];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bos.flush();
bos.close();
if (tmpFile.length() > maxSize) {
tmpFile.delete();
return new BaseState(false, AppInfo.MAX_SIZE);
}
state = saveTmpFile(tmpFile, path);
if (!state.isSuccess()) {
tmpFile.delete();
}
return state;
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
}
public static State saveFileByInputStream(InputStream is, String path) {
State state = null;
File tmpFile = getTmpFile();
byte[] dataBuf = new byte[ 2048 ];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bos.flush();
bos.close();
state = saveTmpFile(tmpFile, path);
if (!state.isSuccess()) {
tmpFile.delete();
}
return state;
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
}
private static File getTmpFile() {
File tmpDir = FileUtils.getTempDirectory();
String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
return new File(tmpDir, tmpFileName);
}
private static State saveTmpFile(File tmpFile, String path) {
State state = null;
File targetFile = new File(path);
if (targetFile.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
try {
FileUtils.moveFile(tmpFile, targetFile);
} catch (IOException e) {
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true);
state.putInfo( "size", targetFile.length() );
state.putInfo( "title", targetFile.getName() );
return state;
}
private static State valid(File file) {
File parentPath = file.getParentFile();
if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
}
if (!parentPath.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
return new BaseState(true);
}
}
package com.app.admin.common.ueditor.upload;
import com.app.admin.common.ueditor.define.State;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class Uploader {
private HttpServletRequest request = null;
private Map<String, Object> conf = null;
public Uploader(HttpServletRequest request, Map<String, Object> conf) {
this.request = request;
this.conf = conf;
}
public final State doExec() {
State state = null;
if ("true".equals(this.conf.get("isBase64"))) {
state = Base64Uploader.save(this.request, this.conf);
} else {
state = BinaryUploader.save(this.request, this.conf);
}
return state;
}
}
package com.app.admin.framework.index.controller;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.permission.authorization.service.SysAdministratorRoleService;
import com.app.admin.framework.system.permission.authorization.service.SysRoleModuleService;
import com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudControllerSupport;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.utils.request.RequestUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("")
public class IndexController extends CrudControllerSupport {
@Autowired
SysConfigService sysConfigService;
@Autowired
SysAdministratorService sysAdministratorService;
@Autowired
SysAdministratorRoleService sysAdministratorRoleService;
@Autowired
SysRoleModuleService sysRoleModuleService;
/**
* 用户登录
*/
@RequestMapping(value = "/")
public void toIndex(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.getRequestDispatcher("/index").forward(request, response);
}
/**
* 用户登录
*/
@RequestMapping(value = "/login")
public ModelAndView tologin(HttpServletRequest request) throws Exception {
JSONObject app = sysConfigService.getJson("Website");
JSONObject seo = sysConfigService.getJson("SEO");
String icp = sysConfigService.getString("ICP");
HashMap<String, Object> map = new HashMap<>();
map.put("app", app);
map.put("seo", seo);
map.put("icp", icp);
return new ModelAndView("admin/framework/login.html", map);
}
@RequestMapping(value = "/index")
public ModelAndView index(HttpServletRequest request) {
SysAdministrator loginUser = SessionUtil.getCurrentUser(request);
JSONObject app = sysConfigService.getJson("Website");
JSONObject seo = sysConfigService.getJson("SEO");
String icp = sysConfigService.getString("ICP");
Map<String, Object> result = new HashMap<>();
result.put("app", app);
result.put("seo", seo);
result.put("icp", icp);
result.put("userInfo", loginUser);
if ("style_page".equals(loginUser.getAppStyle())) {
return new ModelAndView("admin/framework/index/index_page.html", result);
} else {
return new ModelAndView("admin/framework/index/index.html", result);
}
}
/**
* 欢迎页面
*/
@RequestMapping(value = "/welcome")
public ModelAndView welcome(HttpServletRequest request) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
List<SysAdministratorRoleView> roleList = sysAdministratorRoleService.selectByUserId(loginUser.getId(), StateEnum.NORMAL);
Map<String, Object> result = new HashMap<>();
result.put("userInfo", loginUser);
result.put("roleList", roleList);
result.put("loginIp", RequestUtil.getIpAddr(request));
result.put("lastTime", DateUtil.date().toString());
result.put("serverIp", request.getLocalAddr());
result.put("serverPort", request.getLocalPort());
return new ModelAndView("admin/framework/index/welcome.html", result);
}
/**
* 表单组件示例页面
*/
@RequestMapping(value = "/form_demo")
public ModelAndView form_demo(HttpServletRequest request) {
Map<String, Object> result = new HashMap<String, Object>();
return new ModelAndView("admin/demo.html", result);
}
}
package com.app.admin.framework.log.aspect;
import cn.hutool.core.date.DateUtil;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.utils.request.RequestUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* 利用AOP拦截记录日志
*/
@Aspect
@Component
public class OperationLogAspect {
@Autowired
OperationLogTask operationLogTask;
/**
* 方法执行后的切入点[采用LogOpsAfter注解的方法]
*/
@Pointcut("@annotation(com.app.framework.core.log.annotation.LogOps)")
public void doControllerAspectAfter() {
}
@After(value = "doControllerAspectAfter() && @annotation(annotation) && args(object,..)", argNames = "annotation,object")
public void doMethodAfter(JoinPoint jp, LogOps annotation, Object object) throws Throwable {
HttpServletRequest request = RequestUtil.getRequest();
operationLogTask.handler(request, jp, annotation, DateUtil.date().toString());
}
}
package com.app.admin.framework.log.aspect;
import com.app.admin.framework.log.model.SysOperationLog;
import com.app.admin.framework.log.service.SysOperationLogService;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.log.result.LogResult;
import com.app.framework.core.log.task.LogResultTask;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.utils.request.RequestUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class OperationLogTask extends LogResultTask {
@Autowired
SysOperationLogService sysOperationLogService;
@Async("taskExecutor")
public void handler(HttpServletRequest request, JoinPoint jp, LogOps annotation, String operationDate) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
if (loginUser == null) {
loginUser = (LoginUser) request.getAttribute("apiLoginUser");
}
SysOperationLog logOper = this.toLogOper(loginUser);
if (logOper == null) return;
logOper.setOperationType(annotation.type());
logOper.setOperationDate(operationDate);
if (StringUtils.isNotBlank(annotation.description())) {//有置顶日志内容
logOper.setContents(annotation.description());
} else {//利用日志拦截器处理日志内容
LogResult logResult = this.logResult(jp);
if (logResult == null) {
return;
}
logOper.setOperationDesc(logResult.getOperType());
logOper.setContents(logResult.processLogColmnList());
if (logResult.getOperatorId() != null) {
logOper.setOperatorId(logResult.getOperatorId());
}
if (StringUtils.isNotBlank(logResult.getOperatorName())) {
logOper.setOperatorName(logResult.getOperatorName());
}
}
logOper.setIpAddress(RequestUtil.getIpAddr(request));
sysOperationLogService.saveOperationLog(logOper);
}
/**
* 组装SysOperationLog
*
* @param loginUser
* @return
*/
private SysOperationLog toLogOper(LoginUser loginUser) {
if (loginUser != null) {
SysOperationLog log = new SysOperationLog();
log.setOrganizationId(loginUser.getOrganizationId());
log.setOperatorId(loginUser.getId());
log.setOperatorName(loginUser.getRealName());
log.setOperatorAccount(loginUser.getUsername());
return log;
}
return null;
}
}
package com.app.admin.framework.log.controller;
import com.app.admin.framework.log.model.SysOperationLog;
import com.app.admin.framework.log.service.SysOperationLogService;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudBaseControllerSupport;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* 日志管理
*/
@Controller
@RequestMapping("/sys/log")
public class SysOperationLogController extends CrudBaseControllerSupport<SysOperationLog> {
@Autowired
SysOperationLogService sysOperationLogService;
/**
* 查询列表的具体实现
* 请求:list
*
* @param request HttpServletRequest
* @param view 查询条件
* @param paging 分页条件
* @return 查询结果
*/
@Override
public List<SysOperationLog> list(HttpServletRequest request, SysOperationLog view, Paging paging) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
return sysOperationLogService.getPageList(view, loginUser, paging);
}
/**
* 保存记录的具体实现
* 请求:saveEntity
*
* @param request HttpServletRequest
* @param entity 实体
* @return 影响结果数
*/
@Override
public AjaxResult saveEntity(HttpServletRequest request, SysOperationLog entity) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
entity.setOrganizationId(loginUser.getOrganizationId());
boolean resultCount = sysOperationLogService.saveOperationLog(entity);
return AjaxResult.wrap(resultCount);
}
/**
* 删除记录,根据Id 具体实现
* 请求:deleteById 参数oid
* 请求:batchDelete 参数oid数组
*
* @param request HttpServletRequest
* @param oids 实体
* @return 影响结果数
*/
@Override
public AjaxResult batchDelete(HttpServletRequest request, Long oids[]) {
boolean b = sysOperationLogService.removeByIds(Arrays.stream(oids).collect(Collectors.toList()));
return AjaxResult.wrap(b);
}
/**
* 跳转到列表页面
*/
@RequestMapping(value = "/golist")
public ModelAndView golist(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/log/list.html");
}
}
package com.app.admin.framework.log.dao;
import com.app.admin.framework.log.model.SysOperationLog;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface SysOperationLogDao extends CrudBaseMapper<SysOperationLog> {
}
\ No newline at end of file
package com.app.admin.framework.log.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* sys_operation_log
* @author
*/
@Data
@ToString
@TableName("sys_operation_log")
public class SysOperationLog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID主键
*/
@TableId(type = IdType.AUTO)
private Long oid;
/**
* 组织机构ID,关联表sys_organization主键
*/
private Long organizationId;
/**
* 操作内容
*/
private String contents;
/**
* IP地址
*/
private String ipAddress;
/**
* mac地址
*/
private String macAddress;
/**
* 操作时间
*/
private String operationDate;
/**
* 操作描述
*/
private String operationDesc;
/**
* 操作类型
*/
private String operationType;
/**
* 操作人员账号
*/
private String operatorAccount;
/**
* 操作人员ID
*/
private Long operatorId;
/**
* 操作人员姓名
*/
private String operatorName;
}
\ No newline at end of file
package com.app.admin.framework.log.service;
import com.app.admin.framework.log.model.SysOperationLog;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.service.CrudBaseService;
import com.app.framework.core.support.view.grid.Paging;
import java.util.List;
/**
* 系统操作日志
*/
public interface SysOperationLogService extends CrudBaseService<SysOperationLog> {
List<SysOperationLog> getPageList(SysOperationLog view, LoginUser loginUser, Paging paging);
/**
* 保存对象
* @param entity 对象
*/
boolean saveOperationLog(SysOperationLog entity);
}
\ No newline at end of file
package com.app.admin.framework.log.service.impl;
import com.app.admin.framework.log.dao.SysOperationLogDao;
import com.app.admin.framework.log.model.SysOperationLog;
import com.app.admin.framework.log.service.SysOperationLogService;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.app.framework.core.support.view.grid.Paging;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 系统操作日志
*/
@Service
public class SysOperationLogServiceImpl extends CrudBaseServiceSupport<SysOperationLogDao, SysOperationLog> implements SysOperationLogService {
public List<SysOperationLog> getPageList(SysOperationLog view, LoginUser loginUser, Paging paging) {
LambdaQueryWrapper<SysOperationLog> wrapper = new LambdaQueryWrapper<>();
if (loginUser.getUserType().equals(LoginUser.TYPE_SUPER)) {//超级管理员:查看所有日志
} else if (loginUser.getUserType().equals(LoginUser.TYPE_ADMIN)) {//租户管理员:查看租户所有日志
wrapper.eq(SysOperationLog::getOrganizationId, loginUser.getOrganizationId());
} else {//查看自己的日志
wrapper.eq(SysOperationLog::getOperatorId, loginUser.getId());
}
if (StringUtils.isNotBlank(view.getOperatorName())) {
wrapper.like(SysOperationLog::getOperatorAccount, view.getOperatorName());
}
wrapper.orderByDesc(SysOperationLog::getOperationDate);
return this.pageList(wrapper, paging);
}
/**
* 保存对象
*
* @param entity 对象
*/
public boolean saveOperationLog(SysOperationLog entity) {
if (entity.getOrganizationId() == null) {
entity.setOrganizationId(LoginUser.ORGANIZATION_SUPER);
}
boolean resultCount;
if (entity.getOid() == null) {
resultCount = this.save(entity);
} else {
resultCount = this.updateById(entity);
}
return resultCount;
}
}
\ No newline at end of file
package com.app.admin.framework.system.administrator.controller;
import cn.hutool.crypto.SecureUtil;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.administrator.view.SysAdministratorView;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.log.constant.LogOpsType;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudBaseControllerSupport;
import com.app.framework.core.support.enums.BaseEnum;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.form.ModelEditForm;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.pwd.PasswordUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* 系统用户管理
*/
@Controller
@RequestMapping("/sys/user")
public class SysAdministratorController extends CrudBaseControllerSupport<SysAdministratorView> {
@Autowired
SysAdministratorService sysAdministratorService;
@Autowired
SysOrganizationService sysOrganizationService;
/**
* 查询列表的具体实现
* 租户管理员在租户管理处,故此处用户管理只需管理类型为2
*
* @param request HttpServletRequest
* @param view 查询条件
* @param paging 分页条件
* @return 查询结果
*/
@Override
public List<SysAdministratorView> list(HttpServletRequest request, SysAdministratorView view, Paging paging) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
view.setOrganizationId(loginUser.getOrganizationId());
List<SysAdministrator> list = sysAdministratorService.getPageList(view, paging);
return list.stream().map(a -> {
SysAdministratorView aview = new SysAdministratorView();
BeanUtils.copyProperties(a, aview);
if (a.getDeptId() != null) {
SysOrganization dept = sysOrganizationService.getById(a.getDeptId());
aview.setDeptName(dept.getName());
}
return aview;
}).collect(Collectors.toList());
}
/**
* 保存记录的具体实现
*
* @param request HttpServletRequest
* @param entity 对象
* @return View对象
*/
@Override
public AjaxResult saveEntity(HttpServletRequest request, SysAdministratorView entity) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
entity.setOrganizationId(loginUser.getOrganizationId());
return sysAdministratorService.saveSysUser(entity, loginUser);
}
/**
* 删除记录,根据Id 具体实现
*
* @param request HttpServletRequest
* @param oids 实体
*/
@Override
public AjaxResult batchDelete(HttpServletRequest request, Long oids[]) {
for (Long oid : oids) {
sysAdministratorService.updateState(oid, StateEnum.DELETE);
}
return AjaxResult.wrap(true);
}
/**
* 跳转到列表页面
*/
@RequestMapping(value = "/golist")
public ModelAndView golist(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/administrator/list.html");
}
/**
* 跳转到编辑页面
*/
@RequestMapping(value = "/edit")
public ModelAndView edit(HttpServletRequest request, SysAdministrator entity, ModelEditForm modelEditForm) {
HashMap<String, Object> map = new HashMap<String, Object>();
if (entity.getOid() != null) {
entity = sysAdministratorService.getById(entity.getOid());
}
if (entity.getDeptId() != null) {
SysOrganization dept = sysOrganizationService.getById(entity.getDeptId());
map.put("dept", dept);
} else {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
SysOrganization dept = sysOrganizationService.getById(loginUser.getOrganizationId());
map.put("dept", dept);
}
map.put("entity", entity);
map.put("editForm", modelEditForm);
return new ModelAndView("admin/framework/system/administrator/edit.html", map);
}
@RequestMapping(value = "/updateStatus")
@LogOps(type = LogOpsType.UPDATE)
public @ResponseBody AjaxResult updateStatus(Long oid, Integer state) {
sysAdministratorService.updateState(oid, BaseEnum.getByValue(StateEnum.class, state));
return AjaxResult.wrap(true);
}
/**
* 跳转到修改密码页面
*/
@RequestMapping(value = "/password")
public ModelAndView password(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/administrator/password.html");
}
/**
* 修改密码
*
* @param userPwd 旧密码
* @param password 新密码
*/
@RequestMapping(value = "/updatePwd")
@LogOps(type = LogOpsType.UPDATE)
public @ResponseBody AjaxResult updatePwd(HttpServletRequest request, String userPwd, String password) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
SysAdministrator sysUser = sysAdministratorService.getById(loginUser.getId());
if (userPwd.length() <= 16) {
userPwd = SecureUtil.md5(userPwd);
}
if (password.length() <= 16) {
password = SecureUtil.md5(password);
}
if (PasswordUtil.equalsPwd(userPwd, sysUser.getPassword())) {//旧密码正确
return sysAdministratorService.updateUserPwd(sysUser.getOid(), password);
} else {
return AjaxResult.wrapError("旧密码输入有误");
}
}
/**
* 重置密码
*/
@RequestMapping(value = "/resetPwd")
@LogOps(type = LogOpsType.UPDATE)
public @ResponseBody AjaxResult resetPwd(Long oid) {
sysAdministratorService.updateUserPwd(oid, LoginUser.DEFAULT_PWD);
return AjaxResult.wrap(true);
}
/**
* 跳转到修改头像页面
*/
@RequestMapping(value = "/editHeadImgUrl")
public ModelAndView editHeadImgUrl(HttpServletRequest request) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
HashMap<String, Object> map = new HashMap<String, Object>();
SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
map.put("entity", entity);
return new ModelAndView("admin/framework/system/administrator/headImg.html", map);
}
/**
* 修改头像
*/
@RequestMapping(value = "/saveHeadImgUrl")
public @ResponseBody AjaxResult updateHeadImgUrl(HttpServletRequest request, String headImgUrl) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
boolean result = sysAdministratorService.updateHeadImgUrl(loginUser.getId(), headImgUrl);
return AjaxResult.wrap(result);
}
/**
* 跳转到个人信息页面
*/
@RequestMapping(value = "/info")
public ModelAndView info(HttpServletRequest request) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
HashMap<String, Object> map = new HashMap<>();
map.put("entity", entity);
return new ModelAndView("admin/framework/system/administrator/info.html", map);
}
/**
* 保存个人信息
*
* @return
*/
@RequestMapping(value = "/saveInfo")
@ResponseBody
public AjaxResult saveInfo(HttpServletRequest request, SysAdministrator view) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
entity.setOid(loginUser.getId());
entity.setRealName(view.getRealName());
entity.setMobileTel(view.getMobileTel());
entity.setEmail(view.getEmail());
entity.setAppStyle(view.getAppStyle());
sysAdministratorService.updateById(entity);
return AjaxResult.wrap(true);
}
/**
* 跳转到选择用户页面
*/
@RequestMapping(value = "/select")
public ModelAndView select(HttpServletRequest request) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
HashMap<String, Object> map = new HashMap<>();
return new ModelAndView("admin/framework/system/administrator/select.html", map);
}
}
package com.app.admin.framework.system.administrator.dao;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface SysAdministratorDao extends CrudBaseMapper<SysAdministrator> {
}
\ No newline at end of file
package com.app.admin.framework.system.administrator.log;
import com.app.admin.framework.system.administrator.controller.SysAdministratorController;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.framework.core.log.intercept.LogInterceptSupport;
import com.app.framework.core.log.result.LogResult;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.enums.BaseEnum;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* 系统用户日志记录器
*/
@Component
public class SysAdministratorLogIntercept extends LogInterceptSupport<SysAdministratorController> {
public LogResult saveByEntity(HttpServletRequest request, SysAdministrator entity) {
LogResult result = new LogResult();
result.setOperType(entity.getOid() == null ? "添加用户" : "修改用户");
result.addColumn("realName", "姓名", entity.getRealName());
result.addColumn("username", "登录名", entity.getUsername());
return result;
}
public LogResult deleteById(HttpServletRequest request, Long oid) {
LogResult result = new LogResult();
result.setOperType("删除用户");
result.addColumn("oid", "用户ID", oid);
return result;
}
public LogResult batchDelete(HttpServletRequest request, Long oids[]) {
LogResult result = new LogResult();
result.setOperType("删除用户");
result.addColumn("oid", "用户ID", Arrays.toString(oids));
return result;
}
public LogResult updateStatus(Long oid, Integer state) {
StateEnum stateEnum = BaseEnum.getByValue(StateEnum.class, state);
LogResult result = new LogResult();
result.setOperType("修改用户状态");
result.addColumn("oid", "用户ID", oid);
result.addColumn("state", "用户状态", stateEnum.getText());
return result;
}
public LogResult updatePwd(HttpServletRequest request, String userPwd, String password) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
LogResult result = new LogResult();
result.setOperType("修改密码");
result.addColumn("oid", "用户ID", loginUser.getId());
result.addColumn("realName", "姓名", loginUser.getRealName());
return result;
}
public LogResult resetPwd(Long oid) {
LogResult result = new LogResult();
result.setOperType("重置密码");
result.addColumn("oid", "用户ID", oid);
return result;
}
}
package com.app.admin.framework.system.administrator.model;
import com.app.framework.core.support.auth.LoginUser;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* sys_administrator
* @author
*/
@Data
@ToString
@TableName("sys_administrator")
public class SysAdministrator implements LoginUser, Serializable {
private static final long serialVersionUID = 1L;
/**
* ID主键
*/
@TableId(type = IdType.AUTO)
private Long oid;
/**
* 组织机构ID,关联表sys_organization主键
*/
private Long organizationId;
/**
* 部门ID,关联表sys_organization主键
*/
private Long deptId;
/**
* 姓名
*/
private String realName;
/**
* 登录名
*/
private String username;
/**
* 登录密码
*/
private String password;
/**
* 用户类型(0:超级管理员 1:租户管理员 2:普通管理员即员工)
*/
private Integer userType;
/**
* 状态(1:正常 2:禁用 3:删除)
*/
private Integer state;
/**
* 备注
*/
private String remark;
/**
* 手机号码
*/
private String mobileTel;
/**
* 邮箱
*/
private String email;
/**
* 头像URL
*/
private String headImgUrl;
/**
* 系统风格(选项卡式:style_tab 单页面式:style_page)
*/
private String appStyle;
/**
* 创建人Id
*/
private Long createUserId;
/**
* 创建时间
*/
private Date createTime;
/**
* 最后修改时间
*/
private Date lastModifiedTime;
@Override
public Long getId() {
return oid;
}
}
\ No newline at end of file
package com.app.admin.framework.system.administrator.service;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.CrudBaseService;
import com.app.framework.core.support.view.form.AjaxResult;
/**
* 系统账号管理
*/
public interface SysAdministratorService extends CrudBaseService<SysAdministrator> {
/**
* 用户登录
*
* @param username 用户名
* @param password 登录密码,标准md5加密
* @param usertype 用户类型,可为空(注册会员登录时建议不要为空)
*/
AjaxResult login(String username, String password, Integer usertype);
/**
* 根据用户名加载用户信息
*
* @param username 用户名
* @return
*/
SysAdministrator findByUsername(String username);
/**
* 保存系统用户
*
* @param entity
*/
AjaxResult saveSysUser(SysAdministrator entity, LoginUser loginUser);
/**
* 修改密码
*
* @param oid 用户ID
* @param newPwd 新密码,MD5加密后
*/
AjaxResult updateUserPwd(Long oid, String newPwd);
/**
* 修改用户头像
*
* @param oid 用户Id
* @param headImgUrl 头像URL
* @return true: 修改成功 fasle: 修改失败
*/
boolean updateHeadImgUrl(Long oid, String headImgUrl);
/**
* 修改状态
*
* @param oid 用户Id
* @param stateEnum 状态
* @return true: 修改成功 fasle: 修改失败
*/
boolean updateState(Long oid, StateEnum stateEnum);
/**
* 保存组织机构管理员
*
* @param administrator 管理员
*/
SysAdministrator saveOrgAdministrator(SysAdministrator administrator);
/**
* 获取组织机构管理员
*
* @param organizationId 组织机构Id
*/
SysAdministrator getOrgAdministrator(Long organizationId);
}
\ No newline at end of file
package com.app.admin.framework.system.administrator.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.app.admin.framework.system.administrator.dao.SysAdministratorDao;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.framework.core.exception.ValidException;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.pwd.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 系统账号管理
*/
@Service
@Transactional
public class SysAdministratorServiceImpl extends CrudBaseServiceSupport<SysAdministratorDao, SysAdministrator> implements SysAdministratorService {
public List<SysAdministrator> getPageList(SysAdministrator view, Paging paging) {
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getOrganizationId, view.getOrganizationId());
wrapper.eq(SysAdministrator::getUserType, LoginUser.TYPE_EMP);
if (view.getDeptId() != null) {
wrapper.eq(SysAdministrator::getDeptId, view.getDeptId());
}
if (view.getState() != null) {
wrapper.eq(SysAdministrator::getState, view.getState());
}
if (StringUtils.isNotBlank(view.getRealName())) {
wrapper.like(SysAdministrator::getUsername, view.getRealName());
}
wrapper.orderByDesc(SysAdministrator::getCreateTime);
return this.pageList(wrapper, paging);
}
/**
* 用户登录
*
* @param username 用户名
* @param password 登录密码,标准md5加密
* @param usertype 用户类型,可为空(注册会员登录时建议不要为空)
*/
public AjaxResult login(String username, String password, Integer usertype) {
if (StringUtils.isBlank(username)) {// 用户名为空
return AjaxResult.wrapError("用户名不能为空");
}
if (StringUtils.isBlank(password)) {// 密码为空
return AjaxResult.wrapError("密码不能为空");
}
if (password.length() < 16) {
password = SecureUtil.md5(password);
}
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getUsername, username);
wrapper.eq(SysAdministrator::getUserType, usertype);
SysAdministrator account = this.getOne(wrapper);
if (account == null) {// 用户名不存在
return AjaxResult.wrapError("用户名不存在");
}
if (!PasswordUtil.equalsPwd(password, account.getPassword())) {//密码错误
return AjaxResult.wrapError("密码错误");
}
if (StateEnum.DISABLE.equalValue(account.getState())) {// 禁用
return AjaxResult.wrapError("用户已被禁用");
}
return AjaxResult.wrapData(account);
}
/**
* 根据用户名加载用户信息
*
* @param username 用户名
* @return
*/
public SysAdministrator findByUsername(String username) {
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getUsername, username);
return this.getOne(wrapper);
}
/**
* 保存系统用户
*
* @param entity
*/
public AjaxResult saveSysUser(SysAdministrator entity, LoginUser loginUser) {
if (this.checkUsername(entity)) {
return AjaxResult.wrapError("登录名已经存在");
}
entity.setUserType(LoginUser.TYPE_EMP);//普通管理员即员工
if (entity.getOrganizationId() == null) {
entity.setOrganizationId(LoginUser.ORGANIZATION_SUPER);
}
boolean count;
if (entity.getOid() == null) {
entity.setPassword(PasswordUtil.encrypt(LoginUser.DEFAULT_PWD));
entity.setCreateUserId(loginUser.getId());
entity.setCreateTime(DateUtil.date());
count = this.save(entity);
} else {
count = this.updateById(entity);
}
return AjaxResult.wrap(count);
}
/**
* 修改密码
*
* @param oid 用户ID
* @param newPwd 新密码,MD5加密后
*/
public AjaxResult updateUserPwd(Long oid, String newPwd) {
AjaxResult result = AjaxResult.wrap(false);
if (StringUtils.isBlank(newPwd) || "d41d8cd98f00b204e9800998ecf8427e".equals(newPwd)) {
result.setMsg("密码不能为空");
} else if (newPwd.length() < 16) {//密码格式不正确
result.setMsg("密码格式不正确");
} else {
SysAdministrator entity = new SysAdministrator();
entity.setOid(oid);
entity.setPassword(PasswordUtil.encrypt(newPwd));
this.updateById(entity);
result.setCode(AjaxResult.SUCCESS);
}
return result;
}
/**
* 修改用户头像
*
* @param oid 用户Id
* @param headImgUrl 头像URL
* @return true: 修改成功 fasle: 修改失败
*/
public boolean updateHeadImgUrl(Long oid, String headImgUrl) {
SysAdministrator record = new SysAdministrator();
record.setOid(oid);
record.setHeadImgUrl(headImgUrl);
return this.updateById(record);
}
/**
* 修改状态
*
* @param oid 用户Id
* @param stateEnum 状态
* @return true: 修改成功 fasle: 修改失败
*/
public boolean updateState(Long oid, StateEnum stateEnum) {
SysAdministrator record = new SysAdministrator();
record.setOid(oid);
record.setState(stateEnum.getValue());
return this.updateById(record);
}
/**
* 保存组织机构管理员
*
* @param administrator 管理员
*/
public SysAdministrator saveOrgAdministrator(SysAdministrator administrator) {
if (administrator.getOrganizationId() == null) {
throw new ValidException("组织机构ID不能为空");
}
SysAdministrator orgAdministrator = this.getOrgAdministrator(administrator.getOrganizationId());
if (orgAdministrator != null) {
if (!orgAdministrator.getState().equals(administrator.getState())) {
SysAdministrator record = new SysAdministrator();
record.setOid(orgAdministrator.getOid());
record.setState(administrator.getState());
this.updateById(record);
orgAdministrator.setState(administrator.getState());
}
return orgAdministrator;
}
boolean check = this.checkUsername(administrator);
if (check) {//用户名已经存在
throw new ValidException("管理员登录账号已经存在");
}
if (StringUtils.isBlank(administrator.getPassword())) {
administrator.setPassword(SysAdministrator.DEFAULT_PWD);
}
administrator.setPassword(PasswordUtil.encrypt(administrator.getPassword()));
administrator.setState(StateEnum.NORMAL.getValue());
administrator.setUserType(LoginUser.TYPE_ADMIN);
administrator.setCreateTime(DateUtil.date());
this.save(administrator);
return administrator;
}
/**
* 获取组织机构管理员
*
* @param organizationId 组织机构Id
*/
public SysAdministrator getOrgAdministrator(Long organizationId) {
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getOrganizationId, organizationId);
wrapper.eq(SysAdministrator::getUserType, LoginUser.TYPE_ADMIN);
return this.getOne(wrapper);
}
/**
* 判断姓名是否存在
*
* @param administrator
* @return true: 已存在 false: 不存在
*/
public boolean checkRealName(SysAdministrator administrator) {
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getRealName, administrator.getRealName());
if (administrator.getOid() != null) {
wrapper.ne(SysAdministrator::getOid, administrator.getOid());
}
int count = this.count(wrapper);
return count > 0;
}
/**
* 判断用户名是否存在
*
* @param administrator
* @return true: 已存在 false: 不存在
*/
public boolean checkUsername(SysAdministrator administrator) {
LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysAdministrator::getUsername, administrator.getUsername());
if (administrator.getOid() != null) {
wrapper.ne(SysAdministrator::getOid, administrator.getOid());
}
int count = this.count(wrapper);
return count > 0;
}
}
\ No newline at end of file
package com.app.admin.framework.system.administrator.view;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
@Data
@ToString
public class SysAdministratorView extends SysAdministrator implements Serializable {
/**
* 部门名称
*/
private String deptName;
}
package com.app.admin.framework.system.module.controller;
import com.app.admin.framework.system.module.convert.SysModuleTreeConvert;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.module.service.SysModuleService;
import com.app.admin.framework.system.module.view.SysModuleTreeNode;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudBaseControllerSupport;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* 菜单资源管理
*/
@Controller
@RequestMapping("/sys/module")
public class SysModuleController extends CrudBaseControllerSupport<SysModule> {
@Autowired
SysModuleService sysModuleService;
/**
* 查询列表的具体实现
* @param request HttpServletRequest
* @param view 查询条件
* @param paging 分页条件
* @return 查询结果
*/
@Override
public List<SysModule> list(HttpServletRequest request, SysModule view, Paging paging){
LoginUser loginUser = SessionUtil.getCurrentUser(request);
view.setOrganizationId(loginUser.getOrganizationId());
return sysModuleService.getPageList(view, paging);
}
/**
* 保存记录的具体实现
* @param request HttpServletRequest
* @param view 实体
* @return View对象
*/
@Override
public AjaxResult saveEntity(HttpServletRequest request, SysModule view){
String[] mtypeBtn = request.getParameterValues("mtypeBtn");
sysModuleService.saveModule(view, mtypeBtn);
return AjaxResult.wrap(true);
}
/**
* 删除记录,根据Id 具体实现
* @param request HttpServletRequest
* @param oids 实体
*/
@Override
public AjaxResult batchDelete(HttpServletRequest request, Long oids[]){
boolean b = sysModuleService.removeByIds(Arrays.stream(oids).collect(Collectors.toList()));
return AjaxResult.wrap(b);
}
@RequestMapping(value = "/main")
public ModelAndView main(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/module/main.html");
}
/**
* 跳转到编辑页面
*/
@RequestMapping(value = "/edit")
public ModelAndView edit(HttpServletRequest request, SysModule entity) {
HashMap<String, Object> map = new HashMap<String, Object>();
if(entity.getOid() != null){
entity = sysModuleService.getById(entity.getOid());
if(StringUtils.isNotBlank(entity.getParams())){
String params = entity.getParams().replace(" ", "&nbsp;").replace("\"", "&quot;");
entity.setParams(params);
}
if(StringUtils.isNotBlank(entity.getVisiturl())){
String visiturl = entity.getVisiturl().replace(" ", "&nbsp;").replace("\"", "&quot;");
entity.setVisiturl(visiturl);
}
}
if(entity.getParentId() != null){
SysModule parent = sysModuleService.getById(entity.getParentId());
map.put("parent", parent);
}
map.put("entity", entity);
return new ModelAndView("admin/framework/system/module/edit.html", map);
}
@RequestMapping(value = "/updateStatus")
public @ResponseBody AjaxResult updateStatus(Long oid, Integer state) {
SysModule entity = new SysModule();
entity.setOid(oid);
entity.setState(state);;
sysModuleService.updateById(entity);
return AjaxResult.wrap(true);
}
/**
* 模块树
*/
@RequestMapping(value = "/treeList")
public @ResponseBody List<SysModuleTreeNode> tree(HttpServletRequest request, SysModule view) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
view.setState(StateEnum.NORMAL.getValue());
view.setMtype(1);//菜单
view.setOrganizationId(loginUser.getOrganizationId());
List<SysModule> list = sysModuleService.getPageList(view, null);
return new SysModuleTreeConvert().transStaticTree(list);
}
}
package com.app.admin.framework.system.module.convert;
import com.app.admin.framework.system.module.enums.SysModuleBtnEnum;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.framework.core.support.enums.common.StateEnum;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SysModuleConvert {
/**
* 将功能按钮list转换为map
* @param list 功能按钮
* @return
*/
public static Map<String, SysModule> toFuncBtnMap(List<SysModule> list){
Map<String, SysModule> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
SysModule m = list.get(i);
map.put(m.getMark(), m);
}
return map;
}
public static SysModule buildBtn(SysModuleBtnEnum btnEnum, SysModule menu){
SysModule entity = new SysModule();
entity.setParentId(menu.getOid());
entity.setMark(menu.getMark() + "_" + btnEnum.toString());
entity.setName(btnEnum.getName());
entity.setMorder(btnEnum.getOrder());
entity.setMtype(2);//按钮
entity.setState(StateEnum.NORMAL.getValue());
return entity;
}
}
package com.app.admin.framework.system.module.convert;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.module.view.SysModuleTreeNode;
import com.app.framework.core.support.convert.ConvertTreeNodeUtils;
import org.springframework.beans.BeanUtils;
import java.util.Set;
public class SysModuleTreeConvert extends ConvertTreeNodeUtils<SysModule, SysModuleTreeNode> {
@Override
public void convert(SysModule entity, SysModuleTreeNode node) {
BeanUtils.copyProperties(entity, node, new String[]{"oid", "parent"});
node.setId(entity.getOid().toString());
node.setOid(entity.getOid().toString());
node.setIconCls(entity.getIconcls());
node.setOpen(true);
if (!entity.getParentId().equals(0L)) {
node.setParentId(entity.getParentId().toString());
}
}
@Override
public void nodeCheck(SysModuleTreeNode node, Set<String> checkedOidSet){
if (checkedOidSet != null && checkedOidSet.contains(node.getOid())) {
node.setChecked(true);
}
}
}
package com.app.admin.framework.system.module.dao;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface SysModuleDao extends CrudBaseMapper<SysModule> {
}
\ No newline at end of file
package com.app.admin.framework.system.module.enums;
/**
* 按钮枚举
*/
public enum SysModuleBtnEnum {
Query("查看", 1),
Add("添加", 2),
Edit("修改", 3),
Del("删除", 4),
Audit("审核", 5)
;
private String name;
private Integer order;
SysModuleBtnEnum(final String name, final Integer order) {
this.name = name;
this.order = order;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
}
package com.app.admin.framework.system.module.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* sys_module
* @author
*/
@Data
@ToString
@TableName("sys_module")
public class SysModule implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID主键
*/
@TableId(type = IdType.AUTO)
private Long oid;
/**
* 组织机构ID,关联表sys_organization主键
*/
private Long organizationId;
/**
* 菜单图标
*/
private String iconcls;
/**
* 资源代码
*/
private String mark;
/**
* 排序号
*/
private Integer morder;
/**
* 资源类型(1菜单 2功能按钮)
*/
private Integer mtype;
/**
* 资源名称
*/
private String name;
/**
* 参数,json格式
*/
private String params;
/**
* 上级资源ID
*/
private Long parentId;
/**
* 备注
*/
private String remark;
/**
* 访问地址类型(1:列表;2:单页;3:自定义)
*/
private Integer visiturlType;
/**
* 访问地址
*/
private String visiturl;
/**
* 状态
*/
private Integer state;
/**
* 英文名称
*/
private String englishName;
}
\ No newline at end of file
package com.app.admin.framework.system.module.service;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.framework.core.support.service.CrudBaseService;
/**
* 资源管理
*/
public interface SysModuleService extends CrudBaseService<SysModule> {
SysModule saveModule(SysModule view, String[] mtypeBtn);
}
\ No newline at end of file
package com.app.admin.framework.system.module.service.impl;
import com.app.admin.framework.system.module.convert.SysModuleConvert;
import com.app.admin.framework.system.module.dao.SysModuleDao;
import com.app.admin.framework.system.module.enums.SysModuleBtnEnum;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.module.service.SysModuleService;
import com.app.framework.core.exception.ValidUtils;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.app.framework.core.support.view.grid.Paging;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* 资源管理
*/
@Service
public class SysModuleServiceImpl extends CrudBaseServiceSupport<SysModuleDao, SysModule> implements SysModuleService {
private boolean checkMark(SysModule sysModule) {
LambdaQueryWrapper<SysModule> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysModule::getMark, sysModule.getMark());
int count = this.count(wrapper);
return count > 0;
}
/**
* 列表权限按钮
*
* @param parentId
* @return
*/
private List<SysModule> getFuncBtn(Long parentId) {
LambdaQueryWrapper<SysModule> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysModule::getParentId, parentId);
wrapper.eq(SysModule::getMtype, 2);
return this.list(wrapper);
}
private SysModule saveEntity(SysModule sysModule) {
if (sysModule.getMtype() == null) {
sysModule.setMtype(1);
}
if (sysModule.getState() == null) {
sysModule.setState(StateEnum.NORMAL.getValue());
}
if (sysModule.getOid() == null) {
this.save(sysModule);
} else {
this.updateById(sysModule);
}
return sysModule;
}
/**
* 查询所有记录,支持分页
*
* @param view 查询条件
* @param paging 分页条件(paging为null或isPage为false时不分页)
* @return List
*/
public List<SysModule> getPageList(SysModule view, Paging paging) {
LambdaQueryWrapper<SysModule> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysModule::getOrganizationId, view.getOrganizationId());
if (view.getMtype() != null) {
wrapper.eq(SysModule::getMtype, view.getMtype());
}
if (view.getState() != null) {
wrapper.eq(SysModule::getState, view.getState());
}
if (view.getParentId() != null) {
wrapper.eq(SysModule::getParentId, view.getParentId());
}
if (StringUtils.isNotBlank(view.getName())) {
wrapper.like(SysModule::getName, view.getName());
}
if (view.getVisiturlType() != null && view.getVisiturlType() == 0) {
wrapper.in(SysModule::getVisiturlType, new Integer[]{1, 2});
}
wrapper.orderByAsc(SysModule::getMtype);
wrapper.orderByAsc(SysModule::getMorder);
return this.pageList(wrapper, paging);
}
public SysModule saveModule(SysModule view, String[] mtypeBtn) {
SysModule sysModule = null;
if (view.getOid() == null) {
ValidUtils.valid(this.checkMark(view), "代码重复");
sysModule = new SysModule();
BeanUtils.copyProperties(view, sysModule);
} else {
sysModule = this.getById(view.getOid());
sysModule.setParentId(view.getParentId());
sysModule.setName(view.getName());
sysModule.setMark(view.getMark());
sysModule.setEnglishName(view.getEnglishName());
sysModule.setVisiturlType(view.getVisiturlType());
sysModule.setVisiturl(view.getVisiturl());
sysModule.setParams(view.getParams());
sysModule.setMtype(view.getMtype());
sysModule.setState(view.getState());
sysModule.setIconcls(view.getIconcls());
sysModule.setMorder(view.getMorder());
sysModule.setRemark(view.getRemark());
}
sysModule = this.saveEntity(sysModule);
//同时新增权限按钮
this.saveModuleBtn(sysModule, mtypeBtn);
return sysModule;
}
public void saveModuleBtn(SysModule sysModule, String[] mtypeBtn) {
if (!sysModule.getMtype().equals(1)) {
return;
}
if (mtypeBtn == null || mtypeBtn.length < 1) {
return;
}
//已入库的权限按钮
List<SysModule> funcBtnList = this.getFuncBtn(sysModule.getOid());
Map<String, SysModule> funcBtnMap = SysModuleConvert.toFuncBtnMap(funcBtnList);
//需创建的权限按钮
for (int i = 0; i < mtypeBtn.length; i++) {
SysModuleBtnEnum btnEnum = SysModuleBtnEnum.valueOf(mtypeBtn[i]);
SysModule module = SysModuleConvert.buildBtn(btnEnum, sysModule);
SysModule exist = funcBtnMap.get(module.getMark());
if (exist != null) {//已创建
module.setOid(exist.getOid());
module.setState(StateEnum.NORMAL.getValue());
}
this.saveEntity(module);
}
}
}
\ No newline at end of file
package com.app.admin.framework.system.module.view;
import com.app.framework.core.support.view.tree.ZTreeNode;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class SysModuleTreeNode extends ZTreeNode {
private static final long serialVersionUID = 1L;
/** 资源英文名称 */
private String englishName;
/**模块标识(菜单的话全局唯一,按钮的话在当前菜单下唯一)*/
private String mark;
/**排序号*/
private Integer morder;
/**访问地址*/
private String visiturl;
/**参数*/
private String params;
}
package com.app.admin.framework.system.organization.controller;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrgPowerService;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudBaseControllerSupport;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.form.ModelEditForm;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.support.view.tree.ExTreeNode;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 组织机构管理
*/
@Controller
@RequestMapping("/sys/organization")
public class SysOrganizationController extends CrudBaseControllerSupport<SysOrganizationView> {
@Resource
SysOrganizationService sysOrganizationService;
@Resource
SysAdministratorService sysAdministratorService;
@Resource
SysOrgPowerService sysOrgPowerService;
/**
* 查询列表的具体实现
* 请求:list
*
* @param request HttpServletRequest
* @param view 查询条件
* @param paging 分页条件
* @return 查询结果
*/
@Override
public List<SysOrganizationView> list(HttpServletRequest request, SysOrganizationView view, Paging paging) {
view.setParentId(0L);
List<SysOrganization> list = sysOrganizationService.getPageList(view, paging);
List<SysOrganizationView> viewList = new ArrayList<>(list.size());
list.forEach(organization -> {
SysAdministrator administrator = sysAdministratorService.getOrgAdministrator(organization.getId());
SysOrganizationView v = new SysOrganizationView();
BeanUtils.copyProperties(organization, v);
if (administrator != null) {
v.setAdministratorRealName(administrator.getRealName());
v.setAdministratorUsername(administrator.getUsername());
}
viewList.add(v);
});
return viewList;
}
/**
* 保存记录的具体实现
* 请求:saveEntity
*
* @param request HttpServletRequest
* @param view 实体
* @return 影响结果数
*/
@Override
public AjaxResult saveEntity(HttpServletRequest request, SysOrganizationView view) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
sysOrgPowerService.saveOrg(view, loginUser);
return AjaxResult.wrap(true);
}
/**
* 删除记录,根据Id 具体实现
* 请求:deleteById 参数oid
* 请求:batchDelete 参数oid数组
*
* @param request HttpServletRequest
* @param oids 实体
* @return 影响结果数
*/
@Override
public AjaxResult batchDelete(HttpServletRequest request, Long oids[]) {
for (Long id : oids) {
SysOrganization update = new SysOrganization();
update.setId(id);
update.setState(StateEnum.DELETE.getValue());
sysOrganizationService.updateById(update);
}
return AjaxResult.wrap(true);
}
/**
* 跳转到列表页面
*/
@RequestMapping(value = "/golist")
public ModelAndView goList(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/organization/list.html");
}
/**
* 跳转到编辑页面
*/
@RequestMapping(value = "/edit")
public ModelAndView edit(HttpServletRequest request, SysOrganization entity, ModelEditForm editForm) {
HashMap<String, Object> map = new HashMap<String, Object>();
SysAdministrator administrator = null;
if (entity.getId() != null) {
entity = sysOrganizationService.getById(entity.getId());
//机构管理员
administrator = sysAdministratorService.getOrgAdministrator(entity.getId());
}
map.put("entity", entity);
map.put("administrator", administrator);
map.put("editForm", editForm);
return new ModelAndView("admin/framework/system/organization/edit.html", map);
}
/**
* 跳转到权限管理页面
*/
@RequestMapping(value = "/power")
public ModelAndView power(SysOrganization entity) {
SysAdministratorRole orgAdminRole = sysOrgPowerService.getOrgPower(entity.getId());
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("userId", orgAdminRole.getUserId());
map.put("roleId", orgAdminRole.getRoleId());
return new ModelAndView("admin/framework/system/authorization/bind_module.html", map);
}
/**
* 查询机构树
*
* @return
*/
@RequestMapping(value = "/treeList")
@ResponseBody
public List<ExTreeNode> treeList(HttpServletRequest request) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
return sysOrganizationService.listTree(loginUser.getOrganizationId());
}
}
\ No newline at end of file
package com.app.admin.framework.system.organization.convert;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.framework.core.support.convert.ConvertTreeNodeUtils;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.view.tree.ExTreeNode;
public class SysOrganizationConvert extends ConvertTreeNodeUtils<SysOrganization, ExTreeNode> {
@Override
public void convert(SysOrganization entity, ExTreeNode node) {
node.setId(entity.getId().toString());
String text = entity.getName();
if (StateEnum.DISABLE.equalValue(entity.getState())) {
text = text + "[已禁用]";
} else if (StateEnum.DELETE.equalValue(entity.getState())) {
text = text + "[已删除]";
}
node.setName(text);
if (!entity.getParentId().equals(0L)) {
node.setParentId(entity.getParentId().toString());
}
}
}
\ No newline at end of file
package com.app.admin.framework.system.organization.dao;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface SysOrganizationDao extends CrudBaseMapper<SysOrganization> {
}
package com.app.admin.framework.system.organization.log;
import com.app.admin.framework.system.organization.controller.SysOrganizationController;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.framework.core.log.intercept.LogInterceptSupport;
import com.app.framework.core.log.result.LogResult;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* 组织机构日志记录
*/
@Component
public class SysOrganizationLogIntercept extends LogInterceptSupport<SysOrganizationController> {
public LogResult saveByEntity(HttpServletRequest request, SysOrganizationView entity){
LogResult result = new LogResult();
result.setOperType(entity.getId() == null ? "添加机构" : "修改机构");
result.addColumn("name", "机构名称", entity.getName());
return result;
}
public LogResult deleteById(HttpServletRequest request, Long oid) {
LogResult result = new LogResult();
result.setOperType("删除机构");
result.addColumn("id", "机构ID", oid);
return result;
}
public LogResult batchDelete(HttpServletRequest request, Long oids[]) {
LogResult result = new LogResult();
result.setOperType("删除机构");
result.addColumn("id", "机构ID", Arrays.toString(oids));
return result;
}
}
package com.app.admin.framework.system.organization.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* sys_organization
* @author
*/
@Data
@ToString
@TableName("sys_organization")
public class SysOrganization implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 组织机构ID/部门ID
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 上级ID,组织机构则为0
*/
private Long parentId;
/**
* 组织机构名称/部门名称
*/
private String name;
/**
* ID路径,用于查所有子部门(eg:1,2,3)
*/
private String path;
/**
* 状态(1:正常 2:禁用 3:删除)
*/
private Integer state;
/**
* 联系人姓名
*/
private String contactName;
/**
* 联系人电话
*/
private String contactMobile;
/**
* 创建时间
*/
private Date createTime;
/**
* 最后更新时间
*/
private Date updateTime;
}
\ No newline at end of file
package com.app.admin.framework.system.organization.service;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.framework.core.support.auth.LoginUser;
/**
* 机构权限管理
*/
public interface SysOrgPowerService {
void saveOrg(SysOrganizationView view, LoginUser loginUser);
/**
* 根据机构ID加载管理权限
*
* @param organizationId 机构ID
* @return
*/
SysAdministratorRole getOrgPower(Long organizationId);
}
package com.app.admin.framework.system.organization.service;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.service.CrudBaseService;
import com.app.framework.core.support.view.tree.ExTreeNode;
import java.util.List;
/**
* 组织机构管理
*/
public interface SysOrganizationService extends CrudBaseService<SysOrganization> {
/**
* 保存组织机构
*
* @param view 组织机构对象
*/
SysOrganization saveOrganization(SysOrganizationView view, LoginUser loginUser);
/**
* 查询机构树
*
* @param parentId
* @return
*/
List<ExTreeNode> listTree(Long parentId);
}
\ No newline at end of file
package com.app.admin.framework.system.organization.service.impl;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrgPowerService;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.admin.framework.system.permission.authorization.service.SysAdministratorRoleService;
import com.app.admin.framework.system.permission.role.model.SysRole;
import com.app.admin.framework.system.permission.role.service.SysRoleService;
import com.app.framework.core.support.auth.LoginUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 机构权限管理
*/
@Service
public class SysOrgPowerServiceImpl implements SysOrgPowerService {
@Resource
SysOrganizationService sysOrganizationService;
@Resource
SysAdministratorService sysAdministratorService;
@Resource
SysRoleService sysRoleService;
@Resource
SysAdministratorRoleService sysAdministratorRoleService;
public void saveOrg(SysOrganizationView view, LoginUser loginUser) {
//保存机构
SysOrganization organization = sysOrganizationService.saveOrganization(view, loginUser);
//保存管理员
SysAdministrator administrator = new SysAdministrator();
administrator.setRealName(view.getAdministratorRealName());
administrator.setUsername(view.getAdministratorUsername());
administrator.setPassword(view.getAdministratorPassword());
administrator.setOrganizationId(organization.getId());
administrator.setState(organization.getState());
administrator.setCreateUserId(loginUser.getId());
SysAdministrator orgAdministrator = sysAdministratorService.saveOrgAdministrator(administrator);
//保存管理员角色
SysRole orgAdminRole = sysRoleService.saveOrgAdminRole(organization.getId(), loginUser);
//保存管理员与角色关联
sysAdministratorRoleService.createIfAbsent(orgAdministrator.getOid(), orgAdminRole.getOid());
}
/**
* 根据机构ID加载管理权限
*
* @param organizationId 机构ID
* @return
*/
public SysAdministratorRole getOrgPower(Long organizationId) {
SysAdministrator administrator = sysAdministratorService.getOrgAdministrator(organizationId);
SysRole role = sysRoleService.getOrgAdminRole(organizationId);
return sysAdministratorRoleService.createIfAbsent(administrator.getOid(), role.getOid());
}
}
package com.app.admin.framework.system.organization.service.impl;
import cn.hutool.core.date.DateUtil;
import com.app.admin.framework.system.organization.convert.SysOrganizationConvert;
import com.app.admin.framework.system.organization.dao.SysOrganizationDao;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.support.view.tree.ExTreeNode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 组织机构管理
*/
@Service
public class SysOrganizationServiceImpl extends CrudBaseServiceSupport<SysOrganizationDao, SysOrganization> implements SysOrganizationService {
public List<SysOrganization> getPageList(SysOrganization view, Paging paging) {
LambdaQueryWrapper<SysOrganization> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysOrganization::getParentId, view.getParentId());
if (StringUtils.isNotBlank(view.getName())) {
wrapper.like(SysOrganization::getName, view.getName());
}
wrapper.orderByDesc(SysOrganization::getCreateTime);
return this.pageList(wrapper, paging);
}
/**
* 保存组织机构
*
* @param view 组织机构对象
*/
public SysOrganization saveOrganization(SysOrganizationView view, LoginUser loginUser) {
SysOrganization entity = new SysOrganization();
BeanUtils.copyProperties(view, entity);
if (entity.getId() == null) {
entity.setCreateTime(DateUtil.date());
this.save(entity);
//更新path字段
SysOrganization update = new SysOrganization();
update.setId(entity.getId());
update.setPath(new StringBuilder().append(entity.getId()).append(",").toString());
this.updateById(update);
} else {
if (StringUtils.isBlank(entity.getPath())) {
entity.setPath(new StringBuilder().append(entity.getId()).append(",").toString());
}
this.updateById(entity);
}
return entity;
}
/**
* 查询机构树
*
* @param parentId
* @return
*/
public List<ExTreeNode> listTree(Long parentId) {
LambdaQueryWrapper<SysOrganization> wrapper = new LambdaQueryWrapper<>();
wrapper.likeRight(SysOrganization::getPath, parentId + ",");
wrapper.eq(SysOrganization::getState, StateEnum.NORMAL.getValue());
wrapper.orderByDesc(SysOrganization::getCreateTime);
List<SysOrganization> list = this.list(wrapper);
return new SysOrganizationConvert().transStaticTree(list);
}
}
\ No newline at end of file
package com.app.admin.framework.system.organization.view;
import com.app.admin.framework.system.organization.model.SysOrganization;
/**
* 组织机构View
*/
public class SysOrganizationView extends SysOrganization {
private String administratorRealName;
private String administratorUsername;
private String administratorPassword;
public String getAdministratorRealName() {
return administratorRealName;
}
public void setAdministratorRealName(String administratorRealName) {
this.administratorRealName = administratorRealName;
}
public String getAdministratorUsername() {
return administratorUsername;
}
public void setAdministratorUsername(String administratorUsername) {
this.administratorUsername = administratorUsername;
}
public String getAdministratorPassword() {
return administratorPassword;
}
public void setAdministratorPassword(String administratorPassword) {
this.administratorPassword = administratorPassword;
}
}
package com.app.admin.framework.system.permission.authorization.controller;
import cn.hutool.json.JSONUtil;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.module.convert.SysModuleTreeConvert;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.module.service.SysModuleService;
import com.app.admin.framework.system.module.view.SysModuleTreeNode;
import com.app.admin.framework.system.permission.authorization.service.SysAuthorityService;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.log.constant.LogOpsType;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudControllerSupport;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 身份认证
*/
@Controller
@RequestMapping("/auth")
public class AuthController extends CrudControllerSupport {
/**
* 操作员菜单session名称
*/
private final String OPERATOR_CONTEXT_MODULES = "operator_context_modules";
@Resource
SysModuleService sysModuleService;
@Resource
SysAuthorityService sysAuthorityService;
/**
* 用户登录
*/
@RequestMapping(value = "/login")
@LogOps(type = LogOpsType.LOGIN)
@ResponseBody
public AjaxResult login(HttpServletRequest request, String username, String password) {
AjaxResult loginResult = sysAuthorityService.login(username, password);
if (loginResult.success()) {
SysAdministrator loginUser = (SysAdministrator) loginResult.getData();
//登录用户菜单
List<SysModule> list = sysAuthorityService.getLoginUserModule(loginUser, 1);
List<SysModuleTreeNode> loginUserModules = new SysModuleTreeConvert().transStaticTree(list);
//将登录的用户资源存入session
SessionUtil.setCurrentUser(request, loginUser);
SessionUtil.set(request, OPERATOR_CONTEXT_MODULES, loginUserModules);
return AjaxResult.wrap(true);
}
return loginResult;
}
/**
* 用户登录
* 支持shiro
*/
@RequestMapping(value = "/loginCheck")
@LogOps(type = LogOpsType.LOGIN)
@ResponseBody
public AjaxResult loginByShiro(HttpServletRequest request, String username, String password, String online) {
// boolean rememberMe = "on".equals(online) ? true : false;
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(false);
Subject subject = SecurityUtils.getSubject();
String msg = "登录失败";
try {
subject.login(token);
if (subject.isAuthenticated()) {
//登录用户信息
SysAdministrator loginUser = (SysAdministrator) subject.getPrincipal();
//登录用户菜单
List<SysModule> list = sysAuthorityService.getLoginUserModule(loginUser, 1);
List<SysModuleTreeNode> loginUserModules = new SysModuleTreeConvert().transStaticTree(list);
//将登录的用户资源存入session
SessionUtil.setCurrentUser(request, loginUser);
SessionUtil.set(request, OPERATOR_CONTEXT_MODULES, loginUserModules);
return AjaxResult.wrapSuccess("登录成功");
} else {
return AjaxResult.wrapError(msg);
}
} catch (IncorrectCredentialsException e) {
msg = "登录密码错误";
} catch (ExcessiveAttemptsException e) {
msg = "登录失败次数过多";
} catch (LockedAccountException e) {
msg = "帐号已被锁定";
} catch (DisabledAccountException e) {
msg = "帐号已被禁用";
} catch (ExpiredCredentialsException e) {
msg = "帐号已过期";
} catch (UnknownAccountException e) {
msg = e.getMessage();
if (StringUtils.isBlank(msg)) msg = "帐号不存在";
} catch (UnauthorizedException e) {
msg = "您没有得到相应的授权";
}
return AjaxResult.wrapError(msg);
}
/**
* 用户退出登录
*/
@RequestMapping(value = "/logout")
@LogOps(type = LogOpsType.LOGOUT)
public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
//Session注销
SessionUtil.removeCurrentUser(request);
SessionUtil.remove(request, OPERATOR_CONTEXT_MODULES);
//Shiro注销
SecurityUtils.getSubject().logout();
request.setAttribute("apiLoginUser", loginUser);
request.getRequestDispatcher("/login").forward(request, response);
}
/**
* 菜单点击跳转
*
* @param request
* @param response
*/
@RequestMapping(value = "jump")
public void jump(HttpServletRequest request, HttpServletResponse response,
Long moduleId, Integer tabIndex, String url) throws Exception {
Map<String, Object> params = new HashMap<>();
SysModule module = sysModuleService.getById(moduleId);
if (StringUtils.isNotBlank(module.getParams())) {
params = JSONUtil.parseObj(module.getParams());
}
//跳转
request.setAttribute("jumpUrl", url);
request.setAttribute("tabIndex", tabIndex);
request.setAttribute("module", module);
request.setAttribute("paramsMap", params);
request.getRequestDispatcher(url).forward(request, response);
}
/**
* 菜单点击跳转
*
* @param request
* @param response
*/
@RequestMapping(value = "jump_basic")
public void basic_jump(HttpServletRequest request, HttpServletResponse response,
Long moduleId, Integer tabIndex, String url) throws Exception {
SysModule module = sysModuleService.getById(moduleId);
//跳转
request.setAttribute("module", module);
request.setAttribute("tabIndex", tabIndex);
request.getRequestDispatcher(url).forward(request, response);//会同时携带参数
}
}
package com.app.admin.framework.system.permission.authorization.controller;
import com.app.admin.framework.system.module.view.SysModuleTreeNode;
import com.app.admin.framework.system.permission.authorization.service.SysAdministratorRoleService;
import com.app.admin.framework.system.permission.authorization.service.SysAuthorityService;
import com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView;
import com.app.admin.framework.system.permission.role.convert.SysRoleTreeConvert;
import com.app.admin.framework.system.permission.role.model.SysRole;
import com.app.admin.framework.system.permission.role.service.SysRoleService;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.tree.ZTreeNode;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 权限管理
*/
@Controller
@RequestMapping("/authoriz")
public class AuthorityController {
@Resource
SysRoleService sysRoleService;
@Resource
SysAdministratorRoleService sysAdministratorRoleService;
@Resource
SysAuthorityService sysAuthorityService;
/**
* 跳转到列表页面
*/
@RequestMapping(value = "/main")
public ModelAndView main(HttpServletRequest request) {
return new ModelAndView("admin/framework/system/authorization/main.html");
}
/**
* 根据角色id获取模块树
*/
@RequestMapping("/loadModuleTree")
public @ResponseBody List<SysModuleTreeNode> loadModuleTree(HttpServletRequest request, Long roleId) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
return sysAuthorityService.selectModuleByRoleId(loginUser, roleId);
}
/**
* 保存角色模块对应关系
*/
@RequestMapping("/saveRoleModuleRelation")
public @ResponseBody AjaxResult saveRoleModuleRelation(Long roleId, Long[] moduleIds) {
sysAuthorityService.saveRoleModuleRelation(roleId, moduleIds);
return AjaxResult.wrap(true);
}
/**
* 跳转到编辑页面
*/
@RequestMapping(value = "/editUserRole")
public ModelAndView editUserRole(HttpServletRequest request, Long userId) {
request.setAttribute("userId", userId);
return new ModelAndView("admin/framework/system/authorization/bind_role.html");
}
/**
* 根据用户id获取角色树
*/
@RequestMapping("/loadUserRoleTree")
public @ResponseBody List<ZTreeNode> loadUserRoleTree(HttpServletRequest request, Long userId) {
LoginUser loginUser = SessionUtil.getCurrentUser(request);
//查询用户已有角色
List<SysAdministratorRoleView> list = sysAdministratorRoleService.selectByUserId(userId, null);
List<Long> selectRoleIdList = new ArrayList<>(list.size());
for (Iterator<SysAdministratorRoleView> iterator = list.iterator(); iterator.hasNext(); ) {
SysAdministratorRoleView r = iterator.next();
selectRoleIdList.add(r.getRoleId());
}
//所有角色
List<SysRole> roleList = sysRoleService.selectByEnable(loginUser.getOrganizationId());
return new SysRoleTreeConvert().convertTree(roleList, selectRoleIdList);
}
/**
* 保存用户角色对应关系
*
* @param userId 用户ID
* @param roleIds 角色ID数组
*/
@RequestMapping("/saveUserRoleRelation")
public @ResponseBody AjaxResult saveUserRoleRelation(HttpServletRequest request, Long userId, Long[] roleIds) {
sysAuthorityService.saveUserRoleRelation(userId, roleIds);
return AjaxResult.wrap(true);
}
/**
* 保存角色用户对应关系
*
* @param roleId 角色ID
* @param userIds 用户ID数组
*/
@RequestMapping("/saveRoleUserRelation")
public @ResponseBody AjaxResult saveRoleUserRelation(HttpServletRequest request, Long roleId, Long[] userIds) {
sysAuthorityService.saveRoleUserRelation(roleId, userIds);
return AjaxResult.wrap(true);
}
/**
* 删除角色
* 同时删除与用户对应关系
* 同时删除角色模块关联关系
*
* @param roleId 角色ID
*/
@RequestMapping("/deleteRole")
public @ResponseBody AjaxResult deleteRole(Long roleId) {
sysAuthorityService.deleteRole(roleId);
return AjaxResult.wrap(true);
}
}
package com.app.admin.framework.system.permission.authorization.dao;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface SysAdministratorRoleDao extends CrudBaseMapper<SysAdministratorRole> {
List<SysAdministratorRoleView> selectByUserId(Map<String, Object> map);
List<String> getUsernameByRoleId(Long roleId);
}
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.dao;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.permission.authorization.model.SysRoleModule;
import com.app.framework.core.support.mapper.CrudBaseMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface SysRoleModuleDao extends CrudBaseMapper<SysRoleModule> {
List<SysModule> selectByRoleIds(Map<String, Object> map);
}
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.log;
import com.app.admin.framework.system.permission.authorization.controller.AuthController;
import com.app.framework.core.log.intercept.LogInterceptSupport;
import com.app.framework.core.log.result.LogResult;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用户认证日志记录器
*/
@Component
public class AuthLogIntercept extends LogInterceptSupport<AuthController> {
/**
* 用户登录
*/
public LogResult login(HttpServletRequest request, String username, String password) {
LogResult result = new LogResult();
result.setOperType("登录");
return result;
}
/**
* 用户登录
*/
public LogResult loginByShiro(HttpServletRequest request, String username, String password, String online) {
return this.login(request, username, password);
}
/**
* 退出登录
*/
public LogResult logout(HttpServletRequest request, HttpServletResponse response) {
LogResult result = new LogResult();
result.setOperType("退出登录");
return result;
}
}
<?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.app.admin.framework.system.permission.authorization.dao.SysAdministratorRoleDao">
<resultMap id="BaseResultMap" type="com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole">
<id column="oid" jdbcType="BIGINT" property="oid" />
<result column="user_id" jdbcType="BIGINT" property="userId" />
<result column="role_id" jdbcType="BIGINT" property="roleId" />
</resultMap>
<resultMap id="BaseViewResultMap" type="com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView" extends="BaseResultMap">
<result column="name" property="roleName" jdbcType="VARCHAR" />
</resultMap>
<select id="selectByUserId" resultMap="BaseViewResultMap" parameterType="map" >
select ur.*,r.name from SYS_PERMISSION_ADMINISTRATOR_ROLE ur left join SYS_PERMISSION_ROLE r on r.OID=ur.role_id
where ur.user_id = #{userId,jdbcType=BIGINT}
<if test="state != null" >
and r.STATE = #{state,jdbcType=INTEGER}
</if>
</select>
<select id="getUsernameByRoleId" resultType="string" parameterType="java.lang.Long" >
SELECT a.username FROM SYS_ADMINISTRATOR a LEFT JOIN SYS_PERMISSION_ADMINISTRATOR_ROLE ar ON ar.user_id=a.oid
WHERE ar.role_id = #{roleId,jdbcType=BIGINT}
</select>
</mapper>
\ No newline at end of file
<?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.app.admin.framework.system.permission.authorization.dao.SysRoleModuleDao">
<resultMap id="SysModuleResultMap" type="com.app.admin.framework.system.module.model.SysModule">
<id column="oid" jdbcType="BIGINT" property="oid" />
<result column="iconCls" jdbcType="VARCHAR" property="iconcls" />
<result column="mark" jdbcType="VARCHAR" property="mark" />
<result column="morder" jdbcType="INTEGER" property="morder" />
<result column="mtype" jdbcType="INTEGER" property="mtype" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="params" jdbcType="VARCHAR" property="params" />
<result column="PARENT_ID" jdbcType="BIGINT" property="parentId" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
<result column="visiturl" jdbcType="VARCHAR" property="visiturl" />
<result column="state" jdbcType="INTEGER" property="state" />
<result column="english_name" jdbcType="VARCHAR" property="englishName" />
</resultMap>
<select id="selectByRoleIds" resultMap="SysModuleResultMap" parameterType="map">
select distinct m.* from sys_permission_role_module r left join sys_module m on m.OID=r.module_id
where r.role_id in
<foreach item="item" index="index" collection="roleIds" open="(" separator="," close=")">
#{item}
</foreach>
<if test="mtype != null" >
and m.mtype = #{mtype,jdbcType=INTEGER}
</if>
order by m.morder asc
</select>
</mapper>
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* sys_permission_administrator_role
* @author
*/
@Data
@ToString
@TableName("sys_permission_administrator_role")
public class SysAdministratorRole implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.AUTO)
private Long oid;
private Long userId;
private Long roleId;
}
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* sys_permission_role_module
* @author
*/
@Data
@ToString
@TableName("sys_permission_role_module")
public class SysRoleModule implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID主键
*/
@TableId(type = IdType.AUTO)
private Long oid;
/**
* 资源ID
*/
private Long moduleId;
/**
* 角色ID
*/
private Long roleId;
}
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.service;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.admin.framework.system.permission.authorization.view.SysAdministratorRoleView;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.CrudBaseService;
import java.util.List;
/**
* 用户角色关联管理
*/
public interface SysAdministratorRoleService extends CrudBaseService<SysAdministratorRole> {
/**
* 查询用户所有角色
* @param userId 用户Id
* @param stateEnum 角色状态
*/
List<SysAdministratorRoleView> selectByUserId(Long userId, StateEnum stateEnum);
/**
* 根据角色Id删除权限
* @param roleId 角色Id
*/
boolean deleteByRoleId(Long roleId);
/**
* 根据用户Id删除权限
*
* @param userId 用户Id
*/
boolean deleteByUserId(Long userId);
/**
* 根据角色ID获取对应的用户
* @param roleId 角色Id
* @return List<用户名>
*/
List<String> getUsernameByRoleId(Long roleId);
/**
* 创建用户角色对应关系,不存在才创建
*
* @param userId 用户ID
* @param roleId 角色ID
*/
SysAdministratorRole createIfAbsent(Long userId, Long roleId);
}
\ No newline at end of file
package com.app.admin.framework.system.permission.authorization.service;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.module.view.SysModuleTreeNode;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.view.form.AjaxResult;
import java.util.List;
/**
* 权限管理
*/
public interface SysAuthorityService {
/**
* 用户登录
*
* @param username
* 用户名
* @param password
* 登录密码,标准md5加密
*/
AjaxResult login(String username, String password);
/**
* 获取登录用户的所有资源
* @param loginUser 登录用户
* @param moduleType 资源类型
*/
List<SysModule> getLoginUserModule(LoginUser loginUser, Integer moduleType);
/**
* 加载角色下的关联模块
*/
List<SysModuleTreeNode> selectModuleByRoleId(LoginUser loginUser, Long roleId);
/**
* 保存角色模块关联
* @param roleId
* @param moduleIds
*/
void saveRoleModuleRelation(Long roleId, Long[] moduleIds);
/**
* 删除角色
* 同时删除与用户对应关系
* 同时删除角色模块关联关系
* @param roleId 角色ID
*/
void deleteRole(Long roleId);
/**
* 保存用户角色对应关系
* @param userId 用户ID
* @param roleIds 角色ID数组
*/
void saveUserRoleRelation(Long userId, Long roleIds[]);
/**
* 保存角色用户对应关系
* @param roleId 角色ID
* @param userIds 用户ID数组
*/
void saveRoleUserRelation(Long roleId, Long userIds[]);
}
package com.app.admin.framework.system.permission.authorization.service;
import com.app.admin.framework.system.module.model.SysModule;
import com.app.admin.framework.system.permission.authorization.model.SysRoleModule;
import com.app.framework.core.support.service.CrudBaseService;
import java.util.List;
import java.util.Set;
/**
* 角色资源关联管理
*/
public interface SysRoleModuleService extends CrudBaseService<SysRoleModule> {
boolean deleteByRoleId(Long roleId);
List<SysRoleModule> listByRoleId(Long roleId);
List<SysModule> selectByRoleIds(Integer mtype, Set<Long> roleIds);
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment