换成maven构建工具

This commit is contained in:
liwen
2020-12-29 21:48:00 +08:00
parent df481557b6
commit 4110bc5d20
301 changed files with 668 additions and 749 deletions

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server;
import com.epri.fx.server.util.DBLog;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@MapperScan("com.epri.fx.server.mapper")
@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ServerApplication {
public static void main(String[] args) {
DBLog.getInstance().start();
SpringApplication.run(ServerApplication.class, args);
}
}

View File

@@ -0,0 +1,42 @@
package com.epri.fx.server.config;
import com.epri.fx.server.filter.ReplaceStreamFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
/**
* @author 01
* @program wrapper-demo
* @description 过滤器配置类
* @create 2018-12-24 21:06
* @since 1.0
**/
@Configuration
public class FilterConfig {
/**
* 注册过滤器
*
* @return FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(replaceStreamFilter());
registration.addUrlPatterns("/*");
registration.setName("streamFilter");
return registration;
}
/**
* 实例化StreamFilter
*
* @return Filter
*/
@Bean(name = "replaceStreamFilter")
public Filter replaceStreamFilter() {
return new ReplaceStreamFilter();
}
}

View File

@@ -0,0 +1,18 @@
package com.epri.fx.server.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @author ace
* @create 2017/12/17.
*/
@Configuration
@Data
public class KeyConfiguration {
@Value("${jwt.rsa-secret}")
private String userSecret;
private byte[] userPubKey;
private byte[] userPriKey;
}

View File

@@ -0,0 +1,42 @@
package com.epri.fx.server.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
/**
* @Description:
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:55 上午
*/
@Configuration
public class UserAuthConfig {
@Value("${auth.user.token-header}")
private String tokenHeader;
private byte[] pubKeyByte;
public String getTokenHeader() {
return tokenHeader;
}
public void setTokenHeader(String tokenHeader) {
this.tokenHeader = tokenHeader;
}
public String getToken(HttpServletRequest request) {
return request.getHeader(this.getTokenHeader());
}
public byte[] getPubKeyByte() {
return pubKeyByte;
}
public void setPubKeyByte(byte[] pubKeyByte) {
this.pubKeyByte = pubKeyByte;
}
}

View File

@@ -0,0 +1,16 @@
package com.epri.fx.server.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @author ace
* @create 2017/12/26.
*/
@Configuration
@Data
public class UserConfiguration {
@Value("${jwt.token-header}")
private String userTokenHeader;
}

View File

@@ -0,0 +1,63 @@
package com.epri.fx.server.config;
import com.epri.fx.server.handler.GlobalExceptionHandler;
import com.epri.fx.server.interceptor.LogInterceptor;
import com.epri.fx.server.interceptor.UserAuthRestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author ace
* @date 2017/9/8
*/
@Configuration("admimWebConfig")
@Primary
public class WebConfiguration implements WebMvcConfigurer {
@Bean
GlobalExceptionHandler getGlobalExceptionHandler() {
return new GlobalExceptionHandler();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getUserAuthRestInterceptor()).addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getLogInterceptor()).addPathPatterns(getIncludePathPatterns());
}
@Bean
UserAuthRestInterceptor getUserAuthRestInterceptor() {
return new UserAuthRestInterceptor();
}
@Bean
LogInterceptor getLogInterceptor() {
return new LogInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
*/
private ArrayList<String> getIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/element/**",
"/gateLog/**",
"/group/**",
"/groupType/**",
"/menu/**",
"/user/**",
"/api/permissions"
};
Collections.addAll(list, urls);
return list;
}
}

View File

@@ -0,0 +1,41 @@
package com.epri.fx.server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
//@Configuration
//@EnableWebSecurity//开启Spring安全
//@EnableGlobalMethodSecurity(prePostEnabled=true)//开启Spring方法级安全
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*
* 配置为从内存中进行加载认证信息.
* 这里配置了两个用户 admin和user
*/
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("admin");
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("123456"))
.roles("normal");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@@ -0,0 +1,36 @@
package com.epri.fx.server.constant;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/7/2 12:40 下午
*/
public class AdminCommonConstant {
public final static int ROOT = -1;
public final static int DEFAULT_GROUP_TYPE = 0;
/**
* 权限关联类型
*/
public final static String AUTHORITY_TYPE_GROUP = "group";
/**
* 权限资源类型
*/
public final static String RESOURCE_TYPE_MENU = "menu";
public final static String RESOURCE_TYPE_BTN = "button";
public final static String RESOURCE_REQUEST_METHOD_GET = "GET";
public final static String RESOURCE_REQUEST_METHOD_PUT = "PUT";
public final static String RESOURCE_REQUEST_METHOD_DELETE = "DELETE";
public final static String RESOURCE_REQUEST_METHOD_POST = "POST";
public final static String RESOURCE_ACTION_VISIT = "访问";
public final static String BOOLEAN_NUMBER_FALSE = "0";
public final static String BOOLEAN_NUMBER_TRUE = "1";
}

View File

@@ -0,0 +1,28 @@
package com.epri.fx.server.constant;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:55 上午
*/
public class CommonConstants {
public final static String RESOURCE_TYPE_MENU = "menu";
public final static String RESOURCE_TYPE_BTN = "button";
// 用户token异常
public static final Integer EX_USER_INVALID_CODE = 40101;
public static final Integer EX_USER_PASS_INVALID_CODE = 40001;
// 客户端token异常
public static final Integer EX_CLIENT_INVALID_CODE = 40301;
public static final Integer EX_CLIENT_FORBIDDEN_CODE = 40331;
public static final Integer EX_OTHER_CODE = 500;
public static final String CONTEXT_KEY_USER_ID = "currentUserId";
public static final String CONTEXT_KEY_USERNAME = "currentUserName";
public static final String CONTEXT_KEY_USER_NAME = "currentUser";
public static final String CONTEXT_KEY_USER_TOKEN = "currentUserToken";
public static final String JWT_KEY_USER_ID = "userId";
public static final String JWT_KEY_NAME = "name";
}

View File

@@ -0,0 +1,16 @@
package com.epri.fx.server.constant;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:55 上午
*/
public class RestCodeConstants {
public static final int TOKEN_ERROR_CODE = 40101;
public static final int TOKEN_FORBIDDEN_CODE = 40301;
}

View File

@@ -0,0 +1,11 @@
package com.epri.fx.server.constant;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-14 8:36
*/
public class UserConstant {
public static int PW_ENCORDER_SALT = 12;
}

View File

@@ -0,0 +1,89 @@
package com.epri.fx.server.context;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:55 上午
*/
public class BaseContextHandler {
public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();
public static void set(String key, Object value) {
Map<String, Object> map = threadLocal.get();
if (map == null) {
map = new HashMap<String, Object>();
threadLocal.set(map);
}
map.put(key, value);
}
public static Object get(String key) {
Map<String, Object> map = threadLocal.get();
if (map == null) {
map = new HashMap<String, Object>();
threadLocal.set(map);
}
return map.get(key);
}
public static String getUserID() {
Object value = get(CommonConstants.CONTEXT_KEY_USER_ID);
return returnObjectValue(value);
}
public static String getUsername() {
Object value = get(CommonConstants.CONTEXT_KEY_USERNAME);
return returnObjectValue(value);
}
public static String getName() {
Object value = get(CommonConstants.CONTEXT_KEY_USER_NAME);
return StringHelper.getObjectValue(value);
}
public static String getToken() {
Object value = get(CommonConstants.CONTEXT_KEY_USER_TOKEN);
return StringHelper.getObjectValue(value);
}
public static void setToken(String token) {
set(CommonConstants.CONTEXT_KEY_USER_TOKEN, token);
}
public static void setName(String name) {
set(CommonConstants.CONTEXT_KEY_USER_NAME, name);
}
public static void setUserID(String userID) {
set(CommonConstants.CONTEXT_KEY_USER_ID, userID);
}
public static void setUsername(String username) {
set(CommonConstants.CONTEXT_KEY_USERNAME, username);
}
private static String returnObjectValue(Object value) {
return value == null ? null : value.toString();
}
public static void remove() {
threadLocal.remove();
}
}

View File

@@ -0,0 +1,58 @@
package com.epri.fx.server.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class Element implements Serializable {
private Integer id;
private String code;
private String type;
private String name;
private String uri;
private String menuId;
private String parentId;
private String path;
private String method;
private String description;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private static final long serialVersionUID = 1L;
public Element() {
}
}

View File

@@ -0,0 +1,248 @@
package com.epri.fx.server.entity;
import java.io.Serializable;
import java.util.Date;
public class Group implements Serializable {
private Integer id;
private String code;
private String name;
private Integer parentId;
private String path;
private String type;
private Integer groupType;
private String description;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private Date updTime;
private String updUser;
private String updName;
private String updHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public Integer getGroupType() {
return groupType;
}
public void setGroupType(Integer groupType) {
this.groupType = groupType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public Date getCrtTime() {
return crtTime;
}
public void setCrtTime(Date crtTime) {
this.crtTime = crtTime;
}
public String getCrtUser() {
return crtUser;
}
public void setCrtUser(String crtUser) {
this.crtUser = crtUser == null ? null : crtUser.trim();
}
public String getCrtName() {
return crtName;
}
public void setCrtName(String crtName) {
this.crtName = crtName == null ? null : crtName.trim();
}
public String getCrtHost() {
return crtHost;
}
public void setCrtHost(String crtHost) {
this.crtHost = crtHost == null ? null : crtHost.trim();
}
public Date getUpdTime() {
return updTime;
}
public void setUpdTime(Date updTime) {
this.updTime = updTime;
}
public String getUpdUser() {
return updUser;
}
public void setUpdUser(String updUser) {
this.updUser = updUser == null ? null : updUser.trim();
}
public String getUpdName() {
return updName;
}
public void setUpdName(String updName) {
this.updName = updName == null ? null : updName.trim();
}
public String getUpdHost() {
return updHost;
}
public void setUpdHost(String updHost) {
this.updHost = updHost == null ? null : updHost.trim();
}
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1 == null ? null : attr1.trim();
}
public String getAttr2() {
return attr2;
}
public void setAttr2(String attr2) {
this.attr2 = attr2 == null ? null : attr2.trim();
}
public String getAttr3() {
return attr3;
}
public void setAttr3(String attr3) {
this.attr3 = attr3 == null ? null : attr3.trim();
}
public String getAttr4() {
return attr4;
}
public void setAttr4(String attr4) {
this.attr4 = attr4 == null ? null : attr4.trim();
}
public String getAttr5() {
return attr5;
}
public void setAttr5(String attr5) {
this.attr5 = attr5 == null ? null : attr5.trim();
}
public String getAttr6() {
return attr6;
}
public void setAttr6(String attr6) {
this.attr6 = attr6 == null ? null : attr6.trim();
}
public String getAttr7() {
return attr7;
}
public void setAttr7(String attr7) {
this.attr7 = attr7 == null ? null : attr7.trim();
}
public String getAttr8() {
return attr8;
}
public void setAttr8(String attr8) {
this.attr8 = attr8 == null ? null : attr8.trim();
}
}

View File

@@ -0,0 +1,208 @@
package com.epri.fx.server.entity;
import java.io.Serializable;
import java.util.Date;
public class GroupType implements Serializable {
private Integer id;
private String code;
private String name;
private String description;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private Date updTime;
private String updUser;
private String updName;
private String updHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public Date getCrtTime() {
return crtTime;
}
public void setCrtTime(Date crtTime) {
this.crtTime = crtTime;
}
public String getCrtUser() {
return crtUser;
}
public void setCrtUser(String crtUser) {
this.crtUser = crtUser == null ? null : crtUser.trim();
}
public String getCrtName() {
return crtName;
}
public void setCrtName(String crtName) {
this.crtName = crtName == null ? null : crtName.trim();
}
public String getCrtHost() {
return crtHost;
}
public void setCrtHost(String crtHost) {
this.crtHost = crtHost == null ? null : crtHost.trim();
}
public Date getUpdTime() {
return updTime;
}
public void setUpdTime(Date updTime) {
this.updTime = updTime;
}
public String getUpdUser() {
return updUser;
}
public void setUpdUser(String updUser) {
this.updUser = updUser == null ? null : updUser.trim();
}
public String getUpdName() {
return updName;
}
public void setUpdName(String updName) {
this.updName = updName == null ? null : updName.trim();
}
public String getUpdHost() {
return updHost;
}
public void setUpdHost(String updHost) {
this.updHost = updHost == null ? null : updHost.trim();
}
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1 == null ? null : attr1.trim();
}
public String getAttr2() {
return attr2;
}
public void setAttr2(String attr2) {
this.attr2 = attr2 == null ? null : attr2.trim();
}
public String getAttr3() {
return attr3;
}
public void setAttr3(String attr3) {
this.attr3 = attr3 == null ? null : attr3.trim();
}
public String getAttr4() {
return attr4;
}
public void setAttr4(String attr4) {
this.attr4 = attr4 == null ? null : attr4.trim();
}
public String getAttr5() {
return attr5;
}
public void setAttr5(String attr5) {
this.attr5 = attr5 == null ? null : attr5.trim();
}
public String getAttr6() {
return attr6;
}
public void setAttr6(String attr6) {
this.attr6 = attr6 == null ? null : attr6.trim();
}
public String getAttr7() {
return attr7;
}
public void setAttr7(String attr7) {
this.attr7 = attr7 == null ? null : attr7.trim();
}
public String getAttr8() {
return attr8;
}
public void setAttr8(String attr8) {
this.attr8 = attr8 == null ? null : attr8.trim();
}
}

View File

@@ -0,0 +1,71 @@
package com.epri.fx.server.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Data
public class Menu implements Serializable {
private Integer id;
private String code;
private String title;
private Integer parentId;
private String href;
private String icon;
private String type;
private Integer orderNum;
private String description;
private String path;
private String enabled;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private Date updTime;
private String updUser;
private String updName;
private String updHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private List<Element> elementList;
private static final long serialVersionUID = 1L;
public Menu() {
}
}

View File

@@ -0,0 +1,216 @@
package com.epri.fx.server.entity;
import java.io.Serializable;
import java.util.Date;
public class ResourceAuthority implements Serializable {
private Integer id;
private String authorityId;
private String authorityType;
private String resourceId;
private String resourceType;
private String parentId;
private String path;
private String description;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private static final long serialVersionUID = 1L;
public ResourceAuthority() {
}
public ResourceAuthority(String authorityType, String resourceType) {
this.authorityType = authorityType;
this.resourceType = resourceType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthorityId() {
return authorityId;
}
public void setAuthorityId(String authorityId) {
this.authorityId = authorityId == null ? null : authorityId.trim();
}
public String getAuthorityType() {
return authorityType;
}
public void setAuthorityType(String authorityType) {
this.authorityType = authorityType == null ? null : authorityType.trim();
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId == null ? null : resourceId.trim();
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType == null ? null : resourceType.trim();
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId == null ? null : parentId.trim();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public Date getCrtTime() {
return crtTime;
}
public void setCrtTime(Date crtTime) {
this.crtTime = crtTime;
}
public String getCrtUser() {
return crtUser;
}
public void setCrtUser(String crtUser) {
this.crtUser = crtUser == null ? null : crtUser.trim();
}
public String getCrtName() {
return crtName;
}
public void setCrtName(String crtName) {
this.crtName = crtName == null ? null : crtName.trim();
}
public String getCrtHost() {
return crtHost;
}
public void setCrtHost(String crtHost) {
this.crtHost = crtHost == null ? null : crtHost.trim();
}
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1 == null ? null : attr1.trim();
}
public String getAttr2() {
return attr2;
}
public void setAttr2(String attr2) {
this.attr2 = attr2 == null ? null : attr2.trim();
}
public String getAttr3() {
return attr3;
}
public void setAttr3(String attr3) {
this.attr3 = attr3 == null ? null : attr3.trim();
}
public String getAttr4() {
return attr4;
}
public void setAttr4(String attr4) {
this.attr4 = attr4 == null ? null : attr4.trim();
}
public String getAttr5() {
return attr5;
}
public void setAttr5(String attr5) {
this.attr5 = attr5 == null ? null : attr5.trim();
}
public String getAttr6() {
return attr6;
}
public void setAttr6(String attr6) {
this.attr6 = attr6 == null ? null : attr6.trim();
}
public String getAttr7() {
return attr7;
}
public void setAttr7(String attr7) {
this.attr7 = attr7 == null ? null : attr7.trim();
}
public String getAttr8() {
return attr8;
}
public void setAttr8(String attr8) {
this.attr8 = attr8 == null ? null : attr8.trim();
}
}

View File

@@ -0,0 +1,15 @@
package com.epri.fx.server.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class RsaKey implements Serializable {
private String key;
private String value;
private static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,74 @@
package com.epri.fx.server.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private String name;
private String birthday;
private String address;
private String mobilePhone;
private String telPhone;
private String email;
private String sex;
private String type;
private String status;
private String description;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private Date updTime;
private String updUser;
private String updName;
private String updHost;
private String attr1;
private String attr2;
private String attr3;
private String attr4;
private String attr5;
private String attr6;
private String attr7;
private String attr8;
private static final long serialVersionUID = 1L;
@Override
public String toString() {
return name;
}
}

View File

@@ -0,0 +1,68 @@
package com.epri.fx.server.entity;
import java.io.Serializable;
import java.util.Date;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-21 8:12
*/
public class UserInfo implements Serializable{
public String id;
public String username;
public String password;
public String name;
private String description;
public Date getUpdTime() {
return updTime;
}
public void setUpdTime(Date updTime) {
this.updTime = updTime;
}
private Date updTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@@ -0,0 +1,32 @@
package com.epri.fx.server.entity.log;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* gate_log
* @author
*/
@Data
public class GateLog implements Serializable {
private Integer id;
private String menu;
private String opt;
private String uri;
private Date crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private String body;
private static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,115 @@
package com.epri.fx.server.entity.log;
import java.io.Serializable;
import java.util.Date;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-07-01 11:18
*/
public class LogInfo implements Serializable{
private String id;
private String menu;
private String opt;
private String uri;
private Long crtTime;
private String crtUser;
private String crtName;
private String crtHost;
private String body;
public LogInfo(String menu, String option, String uri, Date crtTime, String crtUser, String crtName, String crtHost, String body) {
this.menu = menu;
this.opt = option;
this.uri = uri;
this.crtTime = crtTime.getTime();
this.crtUser = crtUser;
this.crtName = crtName;
this.crtHost = crtHost;
this.body = body;
}
public LogInfo() {
}
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
public String getOpt() {
return opt;
}
public void setOpt(String option) {
this.opt = option;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Long getCrtTime() {
return crtTime;
}
public void setCrtTime(Date crtTime) {
this.crtTime = crtTime.getTime();
}
public String getCrtUser() {
return crtUser;
}
public void setCrtUser(String crtUser) {
this.crtUser = crtUser;
}
public String getCrtName() {
return crtName;
}
public void setCrtName(String crtName) {
this.crtName = crtName;
}
public String getCrtHost() {
return crtHost;
}
public void setCrtHost(String crtHost) {
this.crtHost = crtHost;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

View File

@@ -0,0 +1,46 @@
package com.epri.fx.server.exception;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class BaseException extends RuntimeException {
private int status = 200;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public BaseException() {
}
public BaseException(String message,int status) {
super(message);
this.status = status;
}
public BaseException(String message) {
super(message);
}
public BaseException(String message, Throwable cause) {
super(message, cause);
}
public BaseException(Throwable cause) {
super(cause);
}
public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,21 @@
package com.epri.fx.server.exception.auth;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class ClientForbiddenException extends BaseException {
public ClientForbiddenException(String message) {
super(message, CommonConstants.EX_CLIENT_FORBIDDEN_CODE);
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.exception.auth;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class ClientInvalidException extends BaseException {
public ClientInvalidException(String message) {
super(message, CommonConstants.EX_CLIENT_INVALID_CODE);
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.exception.auth;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class ClientTokenException extends BaseException {
public ClientTokenException(String message) {
super(message, CommonConstants.EX_CLIENT_INVALID_CODE);
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.exception.auth;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class UserInvalidException extends BaseException {
public UserInvalidException(String message) {
super(message, CommonConstants.EX_USER_PASS_INVALID_CODE);
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.exception.auth;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class UserTokenException extends BaseException {
public UserTokenException(String message) {
super(message, CommonConstants.EX_USER_INVALID_CODE);
}
}

View File

@@ -0,0 +1,33 @@
package com.epri.fx.server.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author 01
* @program wrapper-demo
* @description 替换HttpServletRequest
* @create 2018-12-24 21:04
* @since 1.0
**/
@Slf4j
public class ReplaceStreamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("StreamFilter初始化...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
log.info("StreamFilter销毁...");
}
}

View File

@@ -0,0 +1,124 @@
package com.epri.fx.server.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
/**
* @author 01
* @program wrapper-demo
* @description 包装HttpServletRequest目的是让其输入流可重复读
* @create 2018-12-24 20:48
* @since 1.0
**/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 存储body数据的容器
*/
private final byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
// 将body数据存储起来
String bodyStr = getBodyString(request);
body = bodyStr.getBytes(Charset.defaultCharset());
}
/**
* 获取请求Body
*
* @param request request
* @return String
*/
public String getBodyString(final ServletRequest request) {
try {
return inputStream2String(request.getInputStream());
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
}
}
/**
* 获取请求Body
*
* @return String
*/
public String getBodyString() {
final InputStream inputStream = new ByteArrayInputStream(body);
return inputStream2String(inputStream);
}
/**
* 将inputStream里的数据读取出来并转换成字符串
*
* @param inputStream inputStream
* @return String
*/
private String inputStream2String(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error("", e);
}
}
}
return sb.toString();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}

View File

@@ -0,0 +1,61 @@
package com.epri.fx.server.handler;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.exception.BaseException;
import com.epri.fx.server.exception.auth.ClientTokenException;
import com.epri.fx.server.exception.auth.UserInvalidException;
import com.epri.fx.server.exception.auth.UserTokenException;
import com.epri.fx.server.msg.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
/**
* Created by ace on 2017/9/8.
*/
@ControllerAdvice("com.epri.fx.server")
@ResponseBody
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(ClientTokenException.class)
public BaseResponse clientTokenExceptionHandler(HttpServletResponse response, ClientTokenException ex) {
response.setStatus(403);
logger.error(ex.getMessage(),ex);
return new BaseResponse(ex.getStatus(), ex.getMessage());
}
@ExceptionHandler(UserTokenException.class)
public BaseResponse userTokenExceptionHandler(HttpServletResponse response, UserTokenException ex) {
response.setStatus(200);
logger.error(ex.getMessage(),ex);
return new BaseResponse(ex.getStatus(), ex.getMessage());
}
@ExceptionHandler(UserInvalidException.class)
public BaseResponse userInvalidExceptionHandler(HttpServletResponse response, UserInvalidException ex) {
response.setStatus(200);
logger.error(ex.getMessage(),ex);
return new BaseResponse(ex.getStatus(), ex.getMessage());
}
@ExceptionHandler(BaseException.class)
public BaseResponse baseExceptionHandler(HttpServletResponse response, BaseException ex) {
logger.error(ex.getMessage(),ex);
response.setStatus(500);
return new BaseResponse(ex.getStatus(), ex.getMessage());
}
@ExceptionHandler(Exception.class)
public BaseResponse otherExceptionHandler(HttpServletResponse response, Exception ex) {
response.setStatus(500);
logger.error(ex.getMessage(),ex);
return new BaseResponse(CommonConstants.EX_OTHER_CODE, ex.getMessage());
}
}

View File

@@ -0,0 +1,149 @@
package com.epri.fx.server.interceptor;
import com.epri.fx.server.config.UserConfiguration;
import com.epri.fx.server.context.BaseContextHandler;
import com.epri.fx.server.entity.log.LogInfo;
import com.epri.fx.server.filter.RequestWrapper;
import com.epri.fx.server.jwt.IJWTInfo;
import com.epri.fx.server.service.PermissionService;
import com.epri.fx.server.service.log.GateLogService;
import com.epri.fx.server.util.DBLog;
import com.epri.fx.server.util.user.JwtTokenUtil;
import com.epri.fx.server.vo.PermissionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by ace on 2017/9/10.
*/
public class LogInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserConfiguration userConfiguration;
@Autowired
private GateLogService gateLogService;
@Autowired
private PermissionService permissionService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String token = request.getHeader(userConfiguration.getUserTokenHeader());
IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
HttpServletRequest requestWrapper = null;
//遇到post方法才对request进行包装
String methodType = request.getMethod();
List<PermissionInfo> permissionIfs = permissionService.getAllPermission();
// 判断资源是否启用权限约束
Stream<PermissionInfo> stream = getPermissionIfs(request.getRequestURI(), request.getMethod().toString(), permissionIfs);
List<PermissionInfo> result = stream.collect(Collectors.toList());
PermissionInfo[] permissions = result.toArray(new PermissionInfo[]{});
if (permissions.length > 0) {
checkUserPermission(permissions, request, infoFromToken);
}
return super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
BaseContextHandler.remove();
super.afterCompletion(request, response, handler, ex);
}
private boolean checkUserPermission(PermissionInfo[] permissions, HttpServletRequest ctx, IJWTInfo user) {
List<PermissionInfo> permissionInfos = permissionService.getPermissionByUsername(user.getUniqueName());
PermissionInfo current = null;
for (PermissionInfo info : permissions) {
boolean anyMatch = permissionInfos.parallelStream().anyMatch(permissionInfo -> permissionInfo.getCode().equals(info.getCode()));
if (anyMatch) {
current = info;
break;
}
}
if (current == null) {
return true;
} else {
if (!RequestMethod.GET.toString().equals(current.getMethod())) {
setCurrentUserInfoAndLog(ctx, user, current);
}
return false;
}
}
private void setCurrentUserInfoAndLog(HttpServletRequest request, IJWTInfo user, PermissionInfo pm) {
String host = request.getRemoteHost();
if (isJson(request)) {
// 获取json字符串
String jsonParam = null;
try {
jsonParam = new RequestWrapper(request).getBodyString();
LogInfo logInfo = new LogInfo(pm.getMenu(), pm.getName(), pm.getUri(), new Date(), user.getId(), user.getName(), host, jsonParam);
DBLog.getInstance().setLogService(gateLogService).offerQueue(logInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取目标权限资源
*
* @param requestUri
* @param method
* @param serviceInfo
* @return
*/
private Stream<PermissionInfo> getPermissionIfs(final String requestUri, final String method, List<PermissionInfo> serviceInfo) {
return serviceInfo.parallelStream().filter(permissionInfo -> {
String uri = permissionInfo.getUri();
if (uri.indexOf("{") > 0) {
uri = uri.replaceAll("\\{\\*\\}", "[a-zA-Z\\\\d]+");
}
String regEx = "^" + uri + "$";
return (Pattern.compile(regEx).matcher(requestUri).find())
&& method.equals(permissionInfo.getMethod());
});
}
/**
* 判断本次请求的数据类型是否为json
*
* @param request request
* @return boolean
*/
private boolean isJson(HttpServletRequest request) {
if (request.getContentType() != null) {
return request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE);
}
return false;
}
}

View File

@@ -0,0 +1,51 @@
package com.epri.fx.server.interceptor;
import com.epri.fx.server.config.UserConfiguration;
import com.epri.fx.server.context.BaseContextHandler;
import com.epri.fx.server.jwt.IJWTInfo;
import com.epri.fx.server.service.PermissionService;
import com.epri.fx.server.service.log.GateLogService;
import com.epri.fx.server.util.user.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by ace on 2017/9/10.
*/
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(UserAuthRestInterceptor.class);
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserConfiguration userConfiguration;
@Autowired
private GateLogService gateLogService;
@Autowired
private PermissionService permissionService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String token = request.getHeader(userConfiguration.getUserTokenHeader());
IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
BaseContextHandler.setUsername(infoFromToken.getUniqueName());
BaseContextHandler.setName(infoFromToken.getName());
BaseContextHandler.setUserID(infoFromToken.getId());
return super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
BaseContextHandler.remove();
super.afterCompletion(request, response, handler, ex);
}
}

View File

@@ -0,0 +1,30 @@
package com.epri.fx.server.jwt;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:55 上午
*/
public interface IJWTInfo {
/**
* 获取用户名
* @return
*/
String getUniqueName();
/**
* 获取用户ID
* @return
*/
String getId();
/**
* 获取名称
* @return
*/
String getName();
}

View File

@@ -0,0 +1,111 @@
package com.epri.fx.server.jwt;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.util.StringHelper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 11:08 上午
*/
public class JWTHelper {
private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();
/**
* 密钥加密token
*
* @param jwtInfo
* @param priKeyPath
* @param expire
* @return
* @throws Exception
*/
public static String generateToken(IJWTInfo jwtInfo, String priKeyPath, int expire) throws Exception {
String compactJws = Jwts.builder()
.setSubject(jwtInfo.getUniqueName())
.claim(CommonConstants.JWT_KEY_USER_ID, jwtInfo.getId())
.claim(CommonConstants.JWT_KEY_NAME, jwtInfo.getName())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
.compact();
return compactJws;
}
/**
* 密钥加密token
*
* @param jwtInfo
* @param priKey
* @param expire
* @return
* @throws Exception
*/
public static String generateToken(IJWTInfo jwtInfo, byte priKey[], int expire) throws Exception {
String compactJws = Jwts.builder()
.setSubject(jwtInfo.getUniqueName())
.claim(CommonConstants.JWT_KEY_USER_ID, jwtInfo.getId())
.claim(CommonConstants.JWT_KEY_NAME, jwtInfo.getName())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKey))
.compact();
return compactJws;
}
/**
* 公钥解析token
*
* @param token
* @return
* @throws Exception
*/
public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
return claimsJws;
}
/**
* 公钥解析token
*
* @param token
* @return
* @throws Exception
*/
public static Jws<Claims> parserToken(String token, byte[] pubKey) throws Exception {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKey)).parseClaimsJws(token);
return claimsJws;
}
/**
* 获取token中的用户信息
*
* @param token
* @param pubKeyPath
* @return
* @throws Exception
*/
public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
Claims body = claimsJws.getBody();
return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_NAME)));
}
/**
* 获取token中的用户信息
*
* @param token
* @param pubKey
* @return
* @throws Exception
*/
public static IJWTInfo getInfoFromToken(String token, byte[] pubKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, pubKey);
Claims body = claimsJws.getBody();
return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_NAME)));
}
}

View File

@@ -0,0 +1,76 @@
package com.epri.fx.server.jwt;
import java.io.Serializable;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class JWTInfo implements Serializable, IJWTInfo {
private String username;
private String userId;
private String name;
public JWTInfo(String username, String userId, String name) {
this.username = username;
this.userId = userId;
this.name = name;
}
@Override
public String getUniqueName() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JWTInfo jwtInfo = (JWTInfo) o;
if (username != null ? !username.equals(jwtInfo.username) : jwtInfo.username != null) {
return false;
}
return userId != null ? userId.equals(jwtInfo.userId) : jwtInfo.userId == null;
}
@Override
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}

View File

@@ -0,0 +1,174 @@
package com.epri.fx.server.jwt;
import org.apache.commons.codec.binary.Base64;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class RsaKeyHelper {
/**
* 获取公钥
*
* @param filename
* @return
* @throws Exception
*/
public PublicKey getPublicKey(String filename) throws Exception {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filename);
DataInputStream dis = new DataInputStream(resourceAsStream);
byte[] keyBytes = new byte[resourceAsStream.available()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* 获取密钥
*
* @param filename
* @return
* @throws Exception
*/
public PrivateKey getPrivateKey(String filename) throws Exception {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filename);
DataInputStream dis = new DataInputStream(resourceAsStream);
byte[] keyBytes = new byte[resourceAsStream.available()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
/**
* 获取公钥
*
* @param publicKey
* @return
* @throws Exception
*/
public PublicKey getPublicKey(byte[] publicKey) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* 获取密钥
*
* @param privateKey
* @return
* @throws Exception
*/
public PrivateKey getPrivateKey(byte[] privateKey) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
/**
* 生存rsa公钥和密钥
*
* @param publicKeyFilename
* @param privateKeyFilename
* @param password
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public void generateKey(String publicKeyFilename, String privateKeyFilename, String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
FileOutputStream fos = new FileOutputStream(publicKeyFilename);
fos.write(publicKeyBytes);
fos.close();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
fos = new FileOutputStream(privateKeyFilename);
fos.write(privateKeyBytes);
fos.close();
}
/**
* 生存rsa公钥
*
* @param password
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static byte[] generatePublicKey(String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair.getPublic().getEncoded();
}
/**
* 生存rsa公钥
*
* @param password
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static byte[] generatePrivateKey(String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair.getPrivate().getEncoded();
}
public static Map<String, byte[]> generateKey(String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
Map<String, byte[]> map = new HashMap<String, byte[]>();
map.put("pub", publicKeyBytes);
map.put("pri", privateKeyBytes);
return map;
}
public static String toHexString(byte[] b) {
return Base64.encodeBase64String(b);
}
public static final byte[] toBytes(String s) throws IOException {
return Base64.decodeBase64(s);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom("123".getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
System.out.println(keyPair.getPublic().getEncoded());
}
}

View File

@@ -0,0 +1,34 @@
package com.epri.fx.server.jwt;
import com.epri.fx.server.config.UserAuthConfig;
import com.epri.fx.server.exception.auth.UserTokenException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
@Configuration
public class UserAuthUtil {
@Autowired
private UserAuthConfig userAuthConfig;
public IJWTInfo getInfoFromToken(String token) throws Exception {
try {
return JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());
}catch (ExpiredJwtException ex){
throw new UserTokenException("User token expired!");
}catch (SignatureException ex){
throw new UserTokenException("User token signature error!");
}catch (IllegalArgumentException ex){
throw new UserTokenException("User token is null or empty!");
}
}
}

View File

@@ -0,0 +1,28 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.Element;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ElementMapper {
int deleteByPrimaryKey(Integer id);
int deleteByMenuId(Integer menuId);
int insert(Element record);
int insertSelective(Element record);
Element selectByPrimaryKey(Integer id);
List<Element> selectElementList(Integer menuId);
int updateByPrimaryKeySelective(Element record);
int updateByPrimaryKey(Element record);
List<Element> selectAllElementPermissions();
List<Element> selectAuthorityElementByUserId(@Param("userId") String userId);
}

View File

@@ -0,0 +1,23 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.User;
import com.epri.fx.server.entity.log.GateLog;
import java.util.List;
public interface GateLogMapper {
int deleteByPrimaryKey(Integer id);
int insert(GateLog record);
int insertSelective(GateLog record);
GateLog selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(GateLog record);
int updateByPrimaryKey(GateLog record);
List<GateLog> selectPage(String keyId);
}

View File

@@ -0,0 +1,35 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.Group;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface GroupMapper {
int deleteByPrimaryKey(Integer id);
int deleteChilder(Integer id);
int insert(Group record);
int insertSelective(Group record);
Group selectByPrimaryKey(Integer id);
List<Group> selectGroupList(Integer groupType);
int updateByPrimaryKeySelective(Group record);
int updateByPrimaryKey(Group record);
int deleteGroupMembersById(@Param("groupId") int groupId);
int deleteGroupLeadersById(@Param("groupId") int groupId);
int insertGroupMembersById(@Param("groupId") int groupId, @Param("userId") int userId);
int insertGroupLeadersById(@Param("groupId") int groupId, @Param("userId") int userId);
List<Group> selectUserGroupList(Integer userId);
}

View File

@@ -0,0 +1,21 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.GroupType;
import java.util.List;
public interface GroupTypeMapper {
int deleteByPrimaryKey(Integer id);
int insert(GroupType record);
int insertSelective(GroupType record);
GroupType selectByPrimaryKey(Integer id);
List<GroupType> selectListAll();
int updateByPrimaryKeySelective(GroupType record);
int updateByPrimaryKey(GroupType record);
}

View File

@@ -0,0 +1,29 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.Menu;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface MenuMapper {
int deleteByPrimaryKey(Integer id);
int deleteAllChild(Integer parentId);
int insert(Menu record);
int insertSelective(Menu record);
Menu selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Menu record);
int updateByPrimaryKey(Menu record);
List<Menu> selectMenuAll();
List<Menu> selectMenuByAuthorityId(@Param("authorityId") String authorityId,@Param("authorityType") String authorityType);
List<Menu> selectAuthorityMenuByUserId (@Param("userId") int userId);
}

View File

@@ -0,0 +1,27 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.ResourceAuthority;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ResourceAuthorityMapper {
int deleteByPrimaryKey(Integer id);
int insert(ResourceAuthority record);
int insertSelective(ResourceAuthority record);
ResourceAuthority selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(ResourceAuthority record);
int updateByPrimaryKey(ResourceAuthority record);
List<ResourceAuthority> select(ResourceAuthority record);
int deleteByAuthorityIdAndResourceType(@Param("authorityId")String authorityId);
int deleteByresourceIdAndResourceType(@Param("resourceId")String resourceId,@Param("resourceType")String resourceType);
int deleteByAuthorityIdAndResourceId(@Param("authorityId")String authorityId,@Param("resourceId") String resourceId);
}

View File

@@ -0,0 +1,17 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.RsaKey;
public interface RsaKeyMapper {
int deleteByPrimaryKey(String key);
int insert(RsaKey record);
int insertSelective(RsaKey record);
RsaKey selectByPrimaryKey(String key);
int updateByPrimaryKeySelective(RsaKey record);
int updateByPrimaryKey(RsaKey record);
}

View File

@@ -0,0 +1,29 @@
package com.epri.fx.server.mapper;
import com.epri.fx.server.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
User selectOne(String username );
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAll();
List<User> selectPage(String keyId);
public List<User> selectMemberByGroupId(@Param("groupId") int groupId);
public List<User> selectLeaderByGroupId(@Param("groupId") int groupId);
}

View File

@@ -0,0 +1,41 @@
package com.epri.fx.server.msg;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class BaseResponse {
private int status = 200;
private String message;
public BaseResponse(int status, String message) {
this.status = status;
this.message = message;
}
public BaseResponse() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}

View File

@@ -0,0 +1,60 @@
package com.epri.fx.server.msg;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-09 7:32
*/
public class ListRestResponse<T> {
String msg;
T result;
int count;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public ListRestResponse count(int count) {
this.setCount(count);
return this;
}
public ListRestResponse count(Long count) {
this.setCount(count.intValue());
return this;
}
public ListRestResponse msg(String msg) {
this.setMsg(msg);
return this;
}
public ListRestResponse result(T result) {
this.setResult(result);
return this;
}
}

View File

@@ -0,0 +1,45 @@
package com.epri.fx.server.msg;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:57 上午
*/
public class ObjectRestResponse<T> extends BaseResponse {
T data;
boolean rel;
public boolean isRel() {
return rel;
}
public void setRel(boolean rel) {
this.rel = rel;
}
public ObjectRestResponse rel(boolean rel) {
this.setRel(rel);
return this;
}
public ObjectRestResponse data(T data) {
this.setData(data);
return this;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@@ -0,0 +1,39 @@
package com.epri.fx.server.msg;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-14 22:40
*/
public class TableResultResponse<T> extends BaseResponse {
private long total;
private List<T> datas;
public TableResultResponse(long total, List<T> rows) {
this.total = total;
this.datas = rows;
}
public TableResultResponse() {
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getDatas() {
return datas;
}
public void setDatas(List<T> datas) {
this.datas = datas;
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.msg.auth;
import com.epri.fx.server.constant.RestCodeConstants;
import com.epri.fx.server.msg.BaseResponse;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class TokenErrorResponse extends BaseResponse {
public TokenErrorResponse(String message) {
super(RestCodeConstants.TOKEN_ERROR_CODE, message);
}
}

View File

@@ -0,0 +1,20 @@
package com.epri.fx.server.msg.auth;
import com.epri.fx.server.constant.RestCodeConstants;
import com.epri.fx.server.msg.BaseResponse;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class TokenForbiddenResponse extends BaseResponse {
public TokenForbiddenResponse(String message) {
super(RestCodeConstants.TOKEN_FORBIDDEN_CODE, message);
}
}

View File

@@ -0,0 +1,47 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.msg.ObjectRestResponse;
import com.epri.fx.server.service.security.auth.AuthService;
import com.epri.fx.server.util.user.JwtAuthenticationRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {
@Value("${jwt.token-header}")
private String tokenHeader;
@Autowired
private AuthService authService;
@RequestMapping(value = "token", method = RequestMethod.POST)
public ObjectRestResponse<String> createAuthenticationToken(
@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
log.info(authenticationRequest.getUsername()+" require logging...");
final String token = authService.login(authenticationRequest);
return new ObjectRestResponse<>().data(token);
}
@RequestMapping(value = "refresh", method = RequestMethod.GET)
public ObjectRestResponse<String> refreshAndGetAuthenticationToken(
HttpServletRequest request) throws Exception {
String token = request.getHeader(tokenHeader);
String refreshedToken = authService.refresh(token);
return new ObjectRestResponse<>().data(refreshedToken);
}
@RequestMapping(value = "verify", method = RequestMethod.GET)
public ObjectRestResponse<?> verify(String token) throws Exception {
authService.validate(token);
return new ObjectRestResponse<>();
}
}

View File

@@ -0,0 +1,49 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.entity.Element;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.service.ElementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @description:
* @className: ElementController
* @author: liwen
* @date: 2020/7/19 12:44
*/
@RestController
@RequestMapping("element")
public class ElementController {
@Autowired
private ElementService elementService;
@GetMapping(value = "/list/{menuId}")
@ResponseBody
public TableResultResponse<Element> getElement(@PathVariable Integer menuId) {
return elementService.getElement(menuId);
}
@PostMapping(value = "")
@ResponseBody
public Integer addElement(@RequestBody Element element) {
return elementService.addElement(element);
}
@PutMapping(value = "")
@ResponseBody
public Integer updateElement(@RequestBody Element element) {
return elementService.updateElement(element);
}
@DeleteMapping(value = "/{id}")
@ResponseBody
public Integer deleteElement(@PathVariable Integer id) {
return elementService.deleteElement(id);
}
}

View File

@@ -0,0 +1,93 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.service.GroupService;
import com.epri.fx.server.vo.GroupUsers;
import com.epri.fx.server.vo.GroupVO;
import com.epri.fx.server.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-12 8:49
*/
@Controller
@RequestMapping("group")
public class GroupController {
@Autowired
private GroupService groupService;
@GetMapping("/{groupId}/authority/menu")
@ResponseBody
public List<MenuVO> getAuthorityMenuElementAll(@PathVariable Integer groupId) {
return groupService.getAuthorityMenuElementAll(groupId);
}
@GetMapping(value = "/treeList/{groupTypeId}")
@ResponseBody
public List<GroupVO> getGroupList(@PathVariable Integer groupTypeId) {
return groupService.getGroupList(groupTypeId);
}
@PostMapping(value = "")
@ResponseBody
public Integer addGroup(@RequestBody GroupVO groupVO) {
return groupService.addGroup(groupVO);
}
@PutMapping(value = "")
@ResponseBody
public Integer updateGroup(@RequestBody GroupVO groupVO) {
return groupService.updateGroup(groupVO);
}
@DeleteMapping(value = "")
@ResponseBody
public Integer deleteGroup(@RequestBody GroupVO groupVO) {
return groupService.deleteGroup(groupVO);
}
@RequestMapping(value = "/{id}/authority/element", method = RequestMethod.GET)
@ResponseBody
public List<Integer> getElementAuthority(@PathVariable int id) {
return groupService.getAuthorityElement(id);
}
@PutMapping(value = "/{groupId}/authority/menu")
@ResponseBody
public Integer modifyMenuAuthority(@PathVariable int groupId, @RequestBody List<MenuVO> menuVOList) {
return groupService.modifyAuthorityMenu(groupId, menuVOList);
}
@RequestMapping(value = "/{id}/user", method = RequestMethod.PUT)
@ResponseBody
public Integer modifiyUsers(@PathVariable int id, String members, String leaders) {
return groupService.modifyGroupUsers(id, members, leaders);
}
@RequestMapping(value = "/{id}/user", method = RequestMethod.GET)
@ResponseBody
public GroupUsers getUsers(@PathVariable int id) {
return groupService.getGroupUsers(id);
}
}

View File

@@ -0,0 +1,54 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.service.GroupTypeService;
import com.epri.fx.server.vo.GroupTypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-12 8:49
*/
@RestController
@RequestMapping("groupType")
public class GroupTypeController {
@Autowired
private GroupTypeService groupTypeService;
@GetMapping(value = "/all")
@ResponseBody
public List<GroupTypeVO> getAllGroupTypes() {
return groupTypeService.getAllGroupTypes();
}
@PostMapping(value = "")
@ResponseBody
public Integer addGroupType(@RequestBody GroupTypeVO groupTypeVO) {
return groupTypeService.addGroupType(groupTypeVO);
}
@PutMapping(value = "")
@ResponseBody
public Integer updateGroupType(@RequestBody GroupTypeVO groupTypeVO) {
return groupTypeService.updateGroupType(groupTypeVO);
}
@DeleteMapping(value = "/{groupTypeId}")
@ResponseBody
public Integer deleteGroupType(@PathVariable int groupTypeId) {
return groupTypeService.deleteGroupType(groupTypeId);
}
}

View File

@@ -0,0 +1,35 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private MenuService menuService;
@GetMapping
public String getWelcomeMsg() {
return "Hello,Spring Security";
}
@GetMapping("/helloAdmin")
@PreAuthorize("hasAnyRole('admin')")
public String helloAdmin() {
return menuService.getMenuAll().toString();
}
@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('user','normal')")
public String helloUser() {
return "Hello,user";
}
}

View File

@@ -0,0 +1,53 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.entity.User;
import com.epri.fx.server.entity.UserInfo;
import com.epri.fx.server.entity.log.GateLog;
import com.epri.fx.server.entity.log.LogInfo;
import com.epri.fx.server.msg.ObjectRestResponse;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.service.PermissionService;
import com.epri.fx.server.service.UserService;
import com.epri.fx.server.service.log.GateLogService;
import com.epri.fx.server.vo.FrontUser;
import com.epri.fx.server.vo.MenuVO;
import com.epri.fx.server.vo.PermissionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @Description:
* @param:
* @return:
* @auther: liwen
* @date: 2020/9/11 9:28 上午
*/
@RestController
@RequestMapping("log")
public class LogController {
@Autowired
private GateLogService gateLogService;
@GetMapping(value = "/page")
@ResponseBody
public TableResultResponse<GateLog> getPageList(@RequestParam Map<String, Object> params) {
return gateLogService.getPageList(params);
}
@DeleteMapping("/{id}")
@ResponseBody
public ObjectRestResponse<Integer> add(@PathVariable Integer id) {
return gateLogService.remove(id);
}
}

View File

@@ -0,0 +1,13 @@
package com.epri.fx.server.rest;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @className: LoginController
* @author: liwen
* @date: 2020/8/1 19:59
*/
@RestController
public class LoginController {
}

View File

@@ -0,0 +1,56 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.entity.Menu;
import com.epri.fx.server.service.MenuService;
import com.epri.fx.server.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-12 8:49
*/
@Controller
@RequestMapping("menu")
public class MenuController {
@Autowired
private MenuService service;
@GetMapping("/all")
@ResponseBody
public List<MenuVO> getMenuAll() {
return service.getMenuAll();
}
@PostMapping("")
@ResponseBody
public Integer addMenu(@RequestBody MenuVO menuVO) {
return service.addMenu(menuVO);
}
@PutMapping("")
@ResponseBody
public Integer updateMenu(@RequestBody MenuVO menuVO) {
return service.updateMenu(menuVO);
}
@DeleteMapping("")
@ResponseBody
public Integer deleteMenu(@RequestBody MenuVO menuVO) {
return service.deleteMenu(menuVO);
}
}

View File

@@ -0,0 +1,110 @@
package com.epri.fx.server.rest;
import com.epri.fx.server.entity.User;
import com.epri.fx.server.entity.UserInfo;
import com.epri.fx.server.msg.ObjectRestResponse;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.service.PermissionService;
import com.epri.fx.server.service.UserService;
import com.epri.fx.server.vo.FrontUser;
import com.epri.fx.server.vo.MenuVO;
import com.epri.fx.server.vo.PermissionInfo;
import com.epri.fx.server.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/9/11 9:28 上午
*/
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private PermissionService permissionService;
@GetMapping(value = "/page")
@ResponseBody
public TableResultResponse<User> getPageList(@RequestParam Map<String, Object> params) {
return userService.getPageList(params);
}
@PutMapping("/{id}")
@ResponseBody
public ObjectRestResponse<Integer> update(@PathVariable int id, @RequestBody User entity) {
return userService.update(entity);
}
@PutMapping("/password/{id}")
@ResponseBody
public ObjectRestResponse<Integer> restPasswrod(@PathVariable Integer id) {
return userService.restPassword(id);
}
@PostMapping("")
@ResponseBody
public ObjectRestResponse<Integer> add(@RequestBody User entity) {
return userService.add(entity);
}
@DeleteMapping("/{id}")
@ResponseBody
public ObjectRestResponse<Integer> add(@PathVariable Integer id) {
return userService.remove(id);
}
@RequestMapping(value = "/permissions", method = RequestMethod.GET)
@ResponseBody
public List<PermissionInfo> getAllPermission() {
return permissionService.getAllPermission();
}
@RequestMapping(value = "/user/un/{username}/permissions", method = RequestMethod.GET)
@ResponseBody
public List<PermissionInfo> getPermissionByUsername(@PathVariable("username") String username) {
return permissionService.getPermissionByUsername(username);
}
@RequestMapping(value = "/user/validate", method = RequestMethod.POST)
@ResponseBody
public UserInfo validate(@RequestBody Map<String, String> body) {
return permissionService.validate(body.get("username"), body.get("password"));
}
@GetMapping(value = "/front/info/{token}")
@ResponseBody
public ObjectRestResponse<FrontUser> getUserInfo(@PathVariable String token) throws Exception {
FrontUser userInfo = permissionService.getUserInfo(token);
return new ObjectRestResponse<FrontUser>().data(userInfo).rel(true);
}
@RequestMapping(value = "/front/menus/{token}", method = RequestMethod.GET)
public @ResponseBody
List<MenuVO> getMenusByUsername(@PathVariable String token) throws Exception {
return permissionService.getMenusByUsername(token);
}
}

View File

@@ -0,0 +1,51 @@
package com.epri.fx.server.runner;
import com.epri.fx.server.config.KeyConfiguration;
import com.epri.fx.server.config.UserAuthConfig;
import com.epri.fx.server.entity.RsaKey;
import com.epri.fx.server.jwt.RsaKeyHelper;
import com.epri.fx.server.service.RsaKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Map;
/**
* @author ace
* @create 2017/12/17.
*/
@Configuration
public class AuthServerRunner implements CommandLineRunner {
@Autowired
private RsaKeyService rsaKeyService;
private static final String REDIS_USER_PRI_KEY = "IPSM:AUTH:JWT:PRI";
private static final String REDIS_USER_PUB_KEY = "IPSM:AUTH:JWT:PUB";
@Autowired
private KeyConfiguration keyConfiguration;
@Autowired
private UserAuthConfig userAuthConfig;
@Override
public void run(String... args) throws Exception {
if (rsaKeyService.hasKey(REDIS_USER_PRI_KEY) && rsaKeyService.hasKey(REDIS_USER_PUB_KEY)) {
keyConfiguration.setUserPriKey(RsaKeyHelper.toBytes(rsaKeyService.get(REDIS_USER_PRI_KEY)));
keyConfiguration.setUserPubKey(RsaKeyHelper.toBytes(rsaKeyService.get(REDIS_USER_PUB_KEY)));
} else {
Map<String, byte[]> keyMap = RsaKeyHelper.generateKey(keyConfiguration.getUserSecret());
keyConfiguration.setUserPriKey(keyMap.get("pri"));
keyConfiguration.setUserPubKey(keyMap.get("pub"));
rsaKeyService.set(REDIS_USER_PRI_KEY, RsaKeyHelper.toHexString(keyMap.get("pri")));
rsaKeyService.set(REDIS_USER_PUB_KEY, RsaKeyHelper.toHexString(keyMap.get("pub")));
}
refreshUserPubKey();
}
@Scheduled(cron = "0 0/1 * * * ?")
public void refreshUserPubKey() {
this.userAuthConfig.setPubKeyByte(keyConfiguration.getUserPubKey());
}
}

View File

@@ -0,0 +1,51 @@
package com.epri.fx.server.service;
import com.epri.fx.server.entity.Element;
import com.epri.fx.server.mapper.ElementMapper;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @description:
* @className: ElementService
* @author: liwen
* @date: 2020/7/19 12:44
*/
@Service
public class ElementService {
@Autowired
private ElementMapper elementMapper;
public TableResultResponse<Element> getElement(Integer menuId) {
List<Element> elementList = elementMapper.selectElementList(menuId);
return new TableResultResponse<Element>(elementList.size(), elementList);
}
public Integer addElement(Element element) {
EntityUtils.setCreatAndUpdatInfo(element);
return elementMapper.insertSelective(element);
}
public Integer updateElement(Element element) {
EntityUtils.setCreatAndUpdatInfo(element);
return elementMapper.updateByPrimaryKeySelective(element);
}
public Integer deleteElement(Integer id) {
return elementMapper.deleteByPrimaryKey(id);
}
public List<Element> getAllElementPermissions(){
return elementMapper.selectAllElementPermissions();
}
public List<Element> getAuthorityElementByUserId(String userId){
return elementMapper.selectAuthorityElementByUserId(userId);
}
}

View File

@@ -0,0 +1,228 @@
package com.epri.fx.server.service;
import com.epri.fx.server.constant.AdminCommonConstant;
import com.epri.fx.server.entity.Element;
import com.epri.fx.server.entity.Group;
import com.epri.fx.server.entity.Menu;
import com.epri.fx.server.entity.ResourceAuthority;
import com.epri.fx.server.mapper.*;
import com.epri.fx.server.util.EntityUtils;
import com.epri.fx.server.vo.ElementVO;
import com.epri.fx.server.vo.GroupUsers;
import com.epri.fx.server.vo.GroupVO;
import com.epri.fx.server.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @description:
* @className: GroupTypeService
* @author: liwen
* @date: 2020/6/30 21:58
*/
@Service
public class GroupService {
@Autowired
private GroupMapper groupMapper;
@Autowired
private MenuMapper menuMapper;
@Autowired
private ResourceAuthorityMapper resourceAuthorityMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private ElementMapper elementMapper;
public List<GroupVO> getGroupList(Integer groupTypeId) {
List<Group> groupList = groupMapper.selectGroupList(groupTypeId);
List<GroupVO> groupVOList = new ArrayList<>();
for (Group group : groupList) {
GroupVO groupVO = new GroupVO();
BeanUtils.copyProperties(group, groupVO);
groupVOList.add(groupVO);
}
return groupVOList;
}
public Integer addGroup(GroupVO groupVO) {
Group group = new Group();
BeanUtils.copyProperties(groupVO, group);
group.setId(null);
EntityUtils.setCreatAndUpdatInfo(group);
return groupMapper.insertSelective(group);
}
public Integer updateGroup(GroupVO groupVO) {
Group group = new Group();
BeanUtils.copyProperties(groupVO, group);
EntityUtils.setCreatAndUpdatInfo(group);
return groupMapper.updateByPrimaryKeySelective(group);
}
public Integer deleteGroup(GroupVO groupVO) {
int result = -1;
result = groupMapper.deleteByPrimaryKey(groupVO.getId());
result = groupMapper.deleteChilder(groupVO.getId());
return result;
}
public List<MenuVO> getAuthorityMenuElementAll(Integer groupId) {
List<Menu> menus = menuMapper.selectMenuAll();
List<MenuVO> menuVOList = new ArrayList<>();
Map<Integer, Menu> authorityMenuMap = getAuthorityMenu(groupId).stream().collect(Collectors.toMap(Menu::getId, a -> a, (k1, k2) -> k1));
List<Integer> authorityElementList = getAuthorityElement(groupId);
for (Menu menu : menus) {
boolean sel = authorityMenuMap.get(menu.getId()) != null;
List<Element> elements = elementMapper.selectElementList(menu.getId());
menu.setElementList(elements);
MenuVO menuVO = new MenuVO();
BeanUtils.copyProperties(menu, menuVO);
List<ElementVO> elementVOList = new ArrayList<>();
for (Element element : elements) {
ElementVO elementVO = new ElementVO();
BeanUtils.copyProperties(element, elementVO);
elementVO.setSel(authorityElementList.contains(element.getId()));
elementVOList.add(elementVO);
}
menuVO.setSel(sel);
menuVOList.add(menuVO);
menuVO.getElementVOS().addAll(elementVOList);
}
return menuVOList;
}
/**
* 获取群主关联的菜单
*
* @param groupId
* @return
*/
public List<Menu> getAuthorityMenu(int groupId) {
List<Menu> menus = menuMapper.selectMenuByAuthorityId(String.valueOf(groupId), AdminCommonConstant.AUTHORITY_TYPE_GROUP);
return menus;
}
/**
* 获取群组关联的资源
*
* @param groupId
* @return
*/
public List<Integer> getAuthorityElement(int groupId) {
ResourceAuthority authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_BTN);
authority.setAuthorityId(groupId + "");
List<ResourceAuthority> authorities = resourceAuthorityMapper.select(authority);
List<Integer> ids = new ArrayList<Integer>();
for (ResourceAuthority auth : authorities) {
ids.add(Integer.parseInt(auth.getResourceId()));
}
return ids;
}
/**
* 变更群组关联的菜单
*
* @param groupId
* @param menus
*/
public Integer modifyAuthorityMenu(int groupId, List<MenuVO> menus) {
int result = -1;
resourceAuthorityMapper.deleteByAuthorityIdAndResourceType(groupId + "");
ResourceAuthority authority = null;
for (MenuVO menu : menus) {
for (ElementVO element : menu.getElementVOS()) {
authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_BTN);
authority.setAuthorityId(groupId + "");
authority.setResourceId(element.getId() + "");
authority.setParentId("-1");
resourceAuthorityMapper.insertSelective(authority);
}
authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_MENU);
authority.setAuthorityId(groupId + "");
authority.setResourceId(menu.getId() + "");
authority.setParentId("-1");
result = resourceAuthorityMapper.insertSelective(authority);
}
return result;
}
/**
* 获取群组关联用户
*
* @param groupId
* @return
*/
public GroupUsers getGroupUsers(int groupId) {
return new GroupUsers(userMapper.selectMemberByGroupId(groupId), userMapper.selectLeaderByGroupId(groupId), userMapper.selectAll());
}
/**
* 获取用户关联群组
*
* @param userId
* @return
*/
public List<GroupVO> getUserGroups(int userId) {
List<Group> groups = groupMapper.selectUserGroupList(userId);
List<GroupVO> groupVOList = new ArrayList<>();
for (Group group : groups) {
GroupVO groupVO = new GroupVO();
BeanUtils.copyProperties(group, groupVO);
groupVOList.add(groupVO);
}
return groupVOList;
}
/**
* 变更群主所分配用户
*
* @param groupId
* @param members
* @param leaders
*/
public Integer modifyGroupUsers(int groupId, String members, String leaders) {
int result = -1;
result = groupMapper.deleteGroupLeadersById(groupId);
result = groupMapper.deleteGroupMembersById(groupId);
if (!StringUtils.isEmpty(members)) {
members = members.replace("[", "").replace("]", "");
String[] mem = members.split(",");
for (String m : mem) {
result = groupMapper.insertGroupMembersById(groupId, Integer.parseInt(m.trim()));
}
}
if (!StringUtils.isEmpty(leaders)) {
leaders = leaders.replace("[", "").replace("]", "");
String[] mem = leaders.split(",");
for (String m : mem) {
result = groupMapper.insertGroupLeadersById(groupId, Integer.parseInt(m));
}
}
return result;
}
}

View File

@@ -0,0 +1,57 @@
package com.epri.fx.server.service;
import com.epri.fx.server.entity.GroupType;
import com.epri.fx.server.mapper.GroupTypeMapper;
import com.epri.fx.server.util.EntityUtils;
import com.epri.fx.server.vo.GroupTypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @description:
* @className: GroupTypeService
* @author: liwen
* @date: 2020/6/30 21:58
*/
@Service
public class GroupTypeService {
@Autowired
private GroupTypeMapper groupTypeMapper;
public List<GroupTypeVO> getAllGroupTypes() {
List<GroupType> groupTypeList = groupTypeMapper.selectListAll();
List<GroupTypeVO> groupTypeVOList = new ArrayList<>();
for (GroupType type : groupTypeList) {
GroupTypeVO groupTypeVO = new GroupTypeVO();
BeanUtils.copyProperties(type, groupTypeVO);
groupTypeVOList.add(groupTypeVO);
}
return groupTypeVOList;
}
public Integer addGroupType(GroupTypeVO groupTypeVO) {
GroupType groupType = new GroupType();
BeanUtils.copyProperties(groupTypeVO, groupType);
EntityUtils.setCreatAndUpdatInfo(groupType);
groupType.setId(null);
return groupTypeMapper.insertSelective(groupType);
}
public Integer updateGroupType(GroupTypeVO groupTypeVO) {
GroupType groupType = new GroupType();
BeanUtils.copyProperties(groupTypeVO, groupType);
EntityUtils.setUpdatedInfo(groupType);
return groupTypeMapper.updateByPrimaryKeySelective(groupType);
}
public Integer deleteGroupType(int groupTypeId) {
return groupTypeMapper.deleteByPrimaryKey(groupTypeId);
}
}

View File

@@ -0,0 +1,104 @@
package com.epri.fx.server.service;
import com.epri.fx.server.constant.AdminCommonConstant;
import com.epri.fx.server.entity.Element;
import com.epri.fx.server.entity.Menu;
import com.epri.fx.server.entity.ResourceAuthority;
import com.epri.fx.server.mapper.ElementMapper;
import com.epri.fx.server.mapper.MenuMapper;
import com.epri.fx.server.mapper.ResourceAuthorityMapper;
import com.epri.fx.server.util.EntityUtils;
import com.epri.fx.server.vo.ElementVO;
import com.epri.fx.server.vo.GroupVO;
import com.epri.fx.server.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @description:
* @className: MenuServer
* @author: liwen
* @date: 2020/6/30 21:58
*/
@Service
public class MenuService {
@Autowired
private MenuMapper menuMapper;
@Autowired
private ElementMapper elementMapper;
@Autowired
private ResourceAuthorityMapper resourceAuthorityMapper;
public List<MenuVO> getMenuAll() {
List<Menu> menus = menuMapper.selectMenuAll();
List<MenuVO> menuVOList = new ArrayList<>();
for (Menu menu : menus) {
MenuVO menuVO = new MenuVO();
BeanUtils.copyProperties(menu, menuVO);
menuVOList.add(menuVO);
}
return menuVOList;
}
public List<Menu> selectListAll() {
return menuMapper.selectMenuAll();
}
public Integer addMenu(MenuVO menuVO) {
Menu menu = new Menu();
BeanUtils.copyProperties(menuVO, menu);
menu.setId(null);
EntityUtils.setCreatAndUpdatInfo(menu);
return menuMapper.insertSelective(menu);
}
public Integer updateMenu(MenuVO menuVO) {
Menu menu = new Menu();
BeanUtils.copyProperties(menuVO, menu);
EntityUtils.setCreatAndUpdatInfo(menu);
return menuMapper.updateByPrimaryKeySelective(menu);
}
public Integer deleteMenu(MenuVO menuVO) {
int result = menuMapper.deleteByPrimaryKey(menuVO.getId());
result = menuMapper.deleteAllChild(menuVO.getId());
result = resourceAuthorityMapper.deleteByresourceIdAndResourceType(menuVO.getId() + "",AdminCommonConstant.RESOURCE_TYPE_MENU);
result = elementMapper.deleteByMenuId(menuVO.getId() );
List<ElementVO> list = menuVO.getElementVOS();
if (list != null) {
for (ElementVO element : menuVO.getElementVOS()) {
result = resourceAuthorityMapper.deleteByresourceIdAndResourceType(element.getId() + "",AdminCommonConstant.RESOURCE_TYPE_BTN);
}
}
return result;
}
/**
* 获取用户可以访问的菜单
*
* @param id
* @return
*/
public List<Menu> getUserAuthorityMenuByUserId(int id) {
return menuMapper.selectAuthorityMenuByUserId(id);
}
}

View File

@@ -0,0 +1,173 @@
package com.epri.fx.server.service;
import com.epri.fx.server.constant.AdminCommonConstant;
import com.epri.fx.server.constant.CommonConstants;
import com.epri.fx.server.entity.Element;
import com.epri.fx.server.entity.Menu;
import com.epri.fx.server.entity.User;
import com.epri.fx.server.entity.UserInfo;
import com.epri.fx.server.jwt.UserAuthUtil;
import com.epri.fx.server.util.EncryptUtil;
import com.epri.fx.server.vo.FrontUser;
import com.epri.fx.server.vo.GroupVO;
import com.epri.fx.server.vo.MenuVO;
import com.epri.fx.server.vo.PermissionInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description:
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
@Service
public class PermissionService {
@Autowired
private UserService userService;
@Autowired
private MenuService menuService;
@Autowired
private ElementService elementService;
@Autowired
private UserAuthUtil userAuthUtil;
@Autowired
private GroupService groupService;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
public UserInfo getUserByUsername(String username) {
UserInfo info = new UserInfo();
User user = userService.getUserByUsername(username);
BeanUtils.copyProperties(user, info);
info.setId(user.getId().toString());
return info;
}
public UserInfo validate(String username, String password) {
UserInfo info = new UserInfo();
User user = userService.getUserByUsername(username);
String pwd = "";
try {
pwd = EncryptUtil.getInstance().Base64Decode(password);
} catch (Exception e) {
e.printStackTrace();
}
if (user != null && encoder.matches(pwd, user.getPassword())) {
BeanUtils.copyProperties(user, info);
info.setId(user.getId().toString());
}
return info;
}
public List<PermissionInfo> getAllPermission() {
List<Menu> menus = menuService.selectListAll();
List<PermissionInfo> result = new ArrayList<PermissionInfo>();
PermissionInfo info = null;
menu2permission(menus, result);
List<Element> elements = elementService.getAllElementPermissions();
element2permission(result, elements);
return result;
}
private void menu2permission(List<Menu> menus, List<PermissionInfo> result) {
PermissionInfo info;
for (Menu menu : menus) {
if (StringUtils.isBlank(menu.getHref())) {
menu.setHref("/" + menu.getCode());
}
info = new PermissionInfo();
info.setCode(menu.getCode());
info.setType(AdminCommonConstant.RESOURCE_TYPE_MENU);
info.setName(AdminCommonConstant.RESOURCE_ACTION_VISIT);
String uri = menu.getHref();
if (!uri.startsWith("/")) {
uri = "/" + uri;
}
info.setUri(uri);
info.setMethod(AdminCommonConstant.RESOURCE_REQUEST_METHOD_GET);
result.add(info
);
info.setMenu(menu.getTitle());
}
}
public List<PermissionInfo> getPermissionByUsername(String username) {
User user = userService.getUserByUsername(username);
List<Menu> menus = menuService.getUserAuthorityMenuByUserId(user.getId());
List<PermissionInfo> result = new ArrayList<PermissionInfo>();
PermissionInfo info = null;
menu2permission(menus, result);
List<Element> elements = elementService.getAuthorityElementByUserId(user.getId() + "");
element2permission(result, elements);
return result;
}
private void element2permission(List<PermissionInfo> result, List<Element> elements) {
PermissionInfo info;
for (Element element : elements) {
info = new PermissionInfo();
info.setCode(element.getCode());
info.setType(element.getType());
info.setUri(element.getUri());
info.setMethod(element.getMethod());
info.setName(element.getName());
info.setMenu(element.getMenuId());
result.add(info);
}
}
public FrontUser getUserInfo(String token) throws Exception {
String username = userAuthUtil.getInfoFromToken(token).getUniqueName();
if (username == null) {
return null;
}
UserInfo user = this.getUserByUsername(username);
FrontUser frontUser = new FrontUser();
BeanUtils.copyProperties(user, frontUser);
List<PermissionInfo> permissionInfos = this.getPermissionByUsername(username);
Stream<PermissionInfo> menus = permissionInfos.parallelStream().filter((permission) -> {
return permission.getType().equals(CommonConstants.RESOURCE_TYPE_MENU);
});
frontUser.setMenus(menus.collect(Collectors.toList()));
Stream<PermissionInfo> elements = permissionInfos.parallelStream().filter((permission) -> {
return !permission.getType().equals(CommonConstants.RESOURCE_TYPE_MENU);
});
frontUser.setElements(elements.collect(Collectors.toList()));
List<GroupVO> groupVOList= groupService.getUserGroups(Integer.parseInt(user.getId()));
frontUser.setRoles(groupVOList);
return frontUser;
}
public List<MenuVO> getMenusByUsername(String token) throws Exception {
String username = userAuthUtil.getInfoFromToken(token).getUniqueName();
if (username == null) {
return null;
}
User user = userService.getUserByUsername(username);
List<Menu> menus = menuService.getUserAuthorityMenuByUserId(user.getId());
List<MenuVO> menuVOS = new ArrayList<>();
for (Menu menu : menus) {
MenuVO menuVO = new MenuVO();
BeanUtils.copyProperties(menu, menuVO);
menuVOS.add(menuVO);
}
return menuVOS;
}
}

View File

@@ -0,0 +1,35 @@
package com.epri.fx.server.service;
import com.epri.fx.server.entity.RsaKey;
import com.epri.fx.server.mapper.RsaKeyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @description:
* @className: RsaKeyService
* @author: liwen
* @date: 2020/8/2 11:12
*/
@Service
public class RsaKeyService {
@Autowired
private RsaKeyMapper rsaKeyMapper;
public boolean hasKey(String key) {
return rsaKeyMapper.selectByPrimaryKey(key) != null;
}
public String get(String key) {
RsaKey rsaKey = rsaKeyMapper.selectByPrimaryKey(key);
return rsaKey == null ? "" : rsaKey.getValue();
}
public int set(String key, String value) {
RsaKey rsaKey = new RsaKey();
rsaKey.setKey(key);
rsaKey.setValue(value);
return rsaKeyMapper.insert(rsaKey);
}
}

View File

@@ -0,0 +1,99 @@
package com.epri.fx.server.service;
import com.alibaba.druid.util.StringUtils;
import com.epri.fx.server.constant.UserConstant;
import com.epri.fx.server.entity.Menu;
import com.epri.fx.server.entity.User;
import com.epri.fx.server.entity.UserInfo;
import com.epri.fx.server.mapper.MenuMapper;
import com.epri.fx.server.mapper.UserMapper;
import com.epri.fx.server.msg.ObjectRestResponse;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.util.EntityUtils;
import com.epri.fx.server.util.Query;
import com.epri.fx.server.util.user.JwtAuthenticationRequest;
import com.epri.fx.server.vo.UserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/**
* @description:
* @className: MenuServer
* @author: liwen
* @date: 2020/6/30 21:58
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private PermissionService permissionService;
public TableResultResponse<User> getPageList(Map<String, Object> params) {
Query query = new Query(params);
Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
String keyId = (String) params.get("keyId");
List<User> list = userMapper.selectPage(StringUtils.isEmpty(keyId) ? null : keyId);
int total = (int) Math.ceil(page.getTotal() / (float) query.getLimit());
return new TableResultResponse<User>(total == 0 ? 1 : total, list);
}
public ObjectRestResponse<Integer> update(User user) {
EntityUtils.setCreatAndUpdatInfo(user);
userMapper.updateByPrimaryKeySelective(user);
return new ObjectRestResponse<Integer>().rel(true);
}
public ObjectRestResponse<Integer> restPassword(Integer id) {
User user = new User();
user.setId(id);
EntityUtils.setUpdatedInfo(user);
String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode("111111");
user.setPassword(password);
userMapper.updateByPrimaryKeySelective(user);
return new ObjectRestResponse<Integer>().rel(true);
}
public ObjectRestResponse<Integer> add(User user) {
String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(user.getPassword());
user.setPassword(password);
EntityUtils.setCreatAndUpdatInfo(user);
userMapper.insertSelective(user);
return new ObjectRestResponse<Integer>().rel(true);
}
public ObjectRestResponse<Integer> remove(Integer id) {
userMapper.deleteByPrimaryKey(id);
return new ObjectRestResponse<Integer>().rel(true);
}
/**
* 根据用户名获取用户信息
* @param username
* @return
*/
public User getUserByUsername(String username){
User user = new User();
user.setUsername(username);
return userMapper.selectOne(username);
}
public UserInfo validate(JwtAuthenticationRequest authenticationRequest){
return permissionService.validate(authenticationRequest.getUsername(),authenticationRequest.getPassword());
}
}

View File

@@ -0,0 +1,55 @@
package com.epri.fx.server.service.log;
import com.alibaba.druid.util.StringUtils;
import com.epri.fx.server.entity.log.GateLog;
import com.epri.fx.server.entity.log.LogInfo;
import com.epri.fx.server.mapper.GateLogMapper;
import com.epri.fx.server.msg.ObjectRestResponse;
import com.epri.fx.server.msg.TableResultResponse;
import com.epri.fx.server.util.Query;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @description:
* @className: GateLogService
* @author: liwen
* @date: 2020/12/3 10:33
*/
@Service
public class GateLogService {
@Autowired
private GateLogMapper gateLogMapper;
public void saveLog(LogInfo info){
GateLog log = new GateLog();
BeanUtils.copyProperties(info,log);
log.setCrtTime(new Date(info.getCrtTime()));
gateLogMapper.insertSelective(log);
}
public TableResultResponse<GateLog> getPageList(Map<String, Object> params) {
Query query = new Query(params);
Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
String keyId = (String) params.get("keyId");
List<GateLog> list = gateLogMapper.selectPage(StringUtils.isEmpty(keyId) ? null : keyId);
int total = (int) Math.ceil(page.getTotal() / (float) query.getLimit());
return new TableResultResponse<GateLog>(total == 0 ? 1 : total, list);
}
public ObjectRestResponse<Integer> remove(Integer id) {
gateLogMapper.deleteByPrimaryKey(id);
return new ObjectRestResponse<Integer>().rel(true);
}
}

View File

@@ -0,0 +1,10 @@
package com.epri.fx.server.service.security.auth;
import com.epri.fx.server.util.user.JwtAuthenticationRequest;
public interface AuthService {
String login(JwtAuthenticationRequest authenticationRequest) throws Exception;
String refresh(String oldToken) throws Exception;
void validate(String token) throws Exception;
}

View File

@@ -0,0 +1,46 @@
package com.epri.fx.server.service.security.auth.impl;
import com.epri.fx.server.entity.UserInfo;
import com.epri.fx.server.exception.auth.UserInvalidException;
import com.epri.fx.server.jwt.JWTInfo;
import com.epri.fx.server.service.security.auth.AuthService;
import com.epri.fx.server.service.UserService;
import com.epri.fx.server.util.user.JwtAuthenticationRequest;
import com.epri.fx.server.util.user.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class AuthServiceImpl implements AuthService {
private JwtTokenUtil jwtTokenUtil;
private UserService userService;
@Autowired
public AuthServiceImpl(
JwtTokenUtil jwtTokenUtil,
UserService userService) {
this.jwtTokenUtil = jwtTokenUtil;
this.userService = userService;
}
@Override
public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
UserInfo info = userService.validate(authenticationRequest);
if (!StringUtils.isEmpty(info.getId())) {
return jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getName()));
}
throw new UserInvalidException("用户不存在或账户密码错误!");
}
@Override
public void validate(String token) throws Exception {
jwtTokenUtil.getInfoFromToken(token);
}
@Override
public String refresh(String oldToken) throws Exception {
return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
}
}

View File

@@ -0,0 +1,24 @@
package com.epri.fx.server.util;
import javax.servlet.http.HttpServletRequest;
public class ClientUtil {
/**
* 获取客户端真实ip
* @param request
* @return
*/
public static String getClientIp(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}

View File

@@ -0,0 +1,86 @@
package com.epri.fx.server.util;
import com.epri.fx.server.entity.log.LogInfo;
import com.epri.fx.server.service.log.GateLogService;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-07-01 15:28
*/
@Slf4j
public class DBLog extends Thread {
private static DBLog dblog = null;
private static BlockingQueue<LogInfo> logInfoQueue = new LinkedBlockingQueue<LogInfo>(1024);
public GateLogService get() {
return logService;
}
public DBLog setLogService(GateLogService logService) {
if (this.logService == null) {
this.logService = logService;
}
return this;
}
private GateLogService logService;
public static synchronized DBLog getInstance() {
if (dblog == null) {
dblog = new DBLog();
}
return dblog;
}
private DBLog() {
super("CLogOracleWriterThread");
}
public void offerQueue(LogInfo logInfo) {
try {
logInfoQueue.offer(logInfo);
} catch (Exception e) {
log.error("日志写入失败", e);
}
}
@Override
public void run() {
List<LogInfo> bufferedLogList = new ArrayList<LogInfo>(); // 缓冲队列
while (true) {
try {
bufferedLogList.add(logInfoQueue.take());
logInfoQueue.drainTo(bufferedLogList);
if (bufferedLogList != null && bufferedLogList.size() > 0) {
// 写入日志
for (LogInfo log : bufferedLogList) {
logService.saveLog(log);
}
}
} catch (Exception e) {
e.printStackTrace();
// 防止缓冲队列填充数据出现异常时不断刷屏
try {
Thread.sleep(1000);
} catch (Exception eee) {
}
} finally {
if (bufferedLogList != null && bufferedLogList.size() > 0) {
try {
bufferedLogList.clear();
} catch (Exception e) {
}
}
}
}
}
}

View File

@@ -0,0 +1,23 @@
package com.epri.fx.server.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
/** 时间格式(yyyy-MM-dd) */
public final static String DATE_PATTERN = "yyyy-MM-dd";
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
public static String format(Date date, String pattern) {
if(date != null){
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
}

View File

@@ -0,0 +1,319 @@
package com.epri.fx.server.util;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
public class EncryptUtil {
public static final String MD5 = "MD5";
public static final String SHA1 = "SHA1";
public static final String HmacMD5 = "HmacMD5";
public static final String HmacSHA1 = "HmacSHA1";
public static final String DES = "DES";
public static final String AES = "AES";
/**
* 编码格式默认使用uft-8
*/
public String charset = "utf-8";
/**
* DES
*/
public int keysizeDES = 0;
/**
* AES
*/
public int keysizeAES = 128;
public static EncryptUtil me;
private EncryptUtil() {
//单例
}
//双重锁
public static EncryptUtil getInstance() {
if (me == null) {
synchronized (EncryptUtil.class) {
if (me == null) {
me = new EncryptUtil();
}
}
}
return me;
}
/**
* 使用MessageDigest进行单向加密无密码
*
* @param res 被加密的文本
* @param algorithm 加密算法名称
* @return
*/
private String messageDigest(String res, String algorithm) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
return base64(md.digest(resBytes));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用KeyGenerator进行单向/双向加密(可设密码)
*
* @param res 被加密的原文
* @param algorithm 加密使用的算法名称
* @param key 加密使用的秘钥
* @return
*/
private String keyGeneratorMac(String res, String algorithm, String key) {
try {
SecretKey sk = null;
if (key == null) {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
sk = kg.generateKey();
} else {
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
sk = new SecretKeySpec(keyBytes, algorithm);
}
Mac mac = Mac.getInstance(algorithm);
mac.init(sk);
byte[] result = mac.doFinal(res.getBytes());
return base64(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用KeyGenerator双向加密DES/AES注意这里转化为字符串的时候是将2进制转为16进制格式的字符串不是直接转因为会出错
*
* @param res 加密的原文
* @param algorithm 加密使用的算法名称
* @param key 加密的秘钥
* @param keysize
* @param isEncode
* @return
*/
private String keyGeneratorES(String res, String algorithm, String key, int keysize, boolean isEncode) {
try {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
if (keysize == 0) {
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
kg.init(new SecureRandom(keyBytes));
} else if (key == null) {
kg.init(keysize);
} else {
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
kg.init(keysize, new SecureRandom(keyBytes));
}
SecretKey sk = kg.generateKey();
SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
if (isEncode) {
cipher.init(Cipher.ENCRYPT_MODE, sks);
byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
return parseByte2HexStr(cipher.doFinal(resBytes));
} else {
cipher.init(Cipher.DECRYPT_MODE, sks);
return new String(cipher.doFinal(parseHexStr2Byte(res)));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String base64(byte[] res) {
return Base64.encode(res);
}
/**
* 将二进制转换成16进制
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* md5加密算法进行加密不可逆
*
* @param res 需要加密的原文
* @return
*/
public String MD5(String res) {
return messageDigest(res, MD5);
}
/**
* md5加密算法进行加密不可逆
*
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String MD5(String res, String key) {
return keyGeneratorMac(res, HmacMD5, key);
}
/**
* 使用SHA1加密算法进行加密不可逆
*
* @param res 需要加密的原文
* @return
*/
public String SHA1(String res) {
return messageDigest(res, SHA1);
}
/**
* 使用SHA1加密算法进行加密不可逆
*
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String SHA1(String res, String key) {
return keyGeneratorMac(res, HmacSHA1, key);
}
/**
* 使用DES加密算法进行加密可逆
*
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String DESencode(String res, String key) {
return keyGeneratorES(res, DES, key, keysizeDES, true);
}
/**
* 对使用DES加密算法的密文进行解密可逆
*
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String DESdecode(String res, String key) {
return keyGeneratorES(res, DES, key, keysizeDES, false);
}
/**
* 使用AES加密算法经行加密可逆
*
* @param res 需要加密的密文
* @param key 秘钥
* @return
*/
public String AESencode(String res, String key) {
return keyGeneratorES(res, AES, key, keysizeAES, true);
}
/**
* 对使用AES加密算法的密文进行解密
*
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String AESdecode(String res, String key) {
return keyGeneratorES(res, AES, key, keysizeAES, false);
}
/**
* 使用异或进行加密
*
* @param res 需要加密的密文
* @param key 秘钥
* @return
*/
public String XORencode(String res, String key) {
byte[] bs = res.getBytes();
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
}
return parseByte2HexStr(bs);
}
/**
* 使用异或进行解密
*
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String XORdecode(String res, String key) {
byte[] bs = parseHexStr2Byte(res);
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
}
return new String(bs);
}
/**
* 直接使用异或(第一调用加密,第二次调用解密)
*
* @param res 密文
* @param key 秘钥
* @return
*/
public int XOR(int res, String key) {
return res ^ key.hashCode();
}
/**
* 使用Base64进行加密
*
* @param res 密文
* @return
*/
public String Base64Encode(String res) {
return Base64.encode(res.getBytes());
}
/**
* 使用Base64进行解密
*
* @param res
* @return
*/
public String Base64Decode(String res) {
return new String(Base64.decode(res));
}
}

View File

@@ -0,0 +1,143 @@
package com.epri.fx.server.util;
import com.epri.fx.server.context.BaseContextHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.Date;
/**
* @Description: 实体类相关工具类
* 解决问题: 1、快速对实体的常驻字段crtUser、crtHost、updUser等值快速注入
* @param:
* @return:
* @auther: liwen
* @date: 2020/7/2 12:38 下午
*/
public class EntityUtils {
/**
* @Description: 快速将bean的crtUser、crtHost、crtTime、updUser、updHost、updTime附上相关值
* @param: [entity]
* @return: void
* @auther: liwen
* @date: 2020/7/2 12:38 下午
*/
public static <T> void setCreatAndUpdatInfo(T entity) {
setCreateInfo(entity);
setUpdatedInfo(entity);
}
/**
* @Description: 快速将bean的crtUser、crtHost、crtTime附上相关值
* @param: [entity]
* @return: void
* @auther: liwen
* @date: 2020/7/2 12:39 下午
*/
public static <T> void setCreateInfo(T entity) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String hostIp = "";
String name = "";
String id = "";
if (request != null) {
hostIp = StringUtils.defaultIfBlank(request.getHeader("userHost"), ClientUtil.getClientIp(request));
name = StringUtils.trimToEmpty(request.getHeader("userName"));
name = URLDecoder.decode(name);
id = StringUtils.trimToEmpty(request.getHeader("userId"));
}
if (StringUtils.isBlank(name)) {
name = BaseContextHandler.getUsername();
}
if (StringUtils.isBlank(id)) {
id = BaseContextHandler.getUserID();
}
// 默认属性
String[] fields = {"crtName", "crtUser", "crtHost", "crtTime"};
Field field = ReflectionUtils.getAccessibleField(entity, "crtTime");
// 默认值
Object[] value = null;
if (field != null && field.getType().equals(Date.class)) {
value = new Object[]{name, id, hostIp, new Date()};
}
// 填充默认属性值
setDefaultValues(entity, fields, value);
}
/**
* 快速将bean的updUser、updHost、updTime附上相关值
*
* @param entity 实体bean
* @author liwen
*/
public static <T> void setUpdatedInfo(T entity) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String hostIp = "";
String name = "";
String id = "";
if (request != null) {
hostIp = StringUtils.defaultIfBlank(request.getHeader("userHost"), ClientUtil.getClientIp(request));
name = StringUtils.trimToEmpty(request.getHeader("userName"));
name = URLDecoder.decode(name);
id = StringUtils.trimToEmpty(request.getHeader("userId"));
}
if (StringUtils.isBlank(name)) {
name = BaseContextHandler.getUsername();
}
if (StringUtils.isBlank(id)) {
id = BaseContextHandler.getUserID();
}
// 默认属性
String[] fields = {"updName", "updUser", "updHost", "updTime"};
Field field = ReflectionUtils.getAccessibleField(entity, "updTime");
Object[] value = null;
if (field != null && field.getType().equals(Date.class)) {
value = new Object[]{name, id, hostIp, new Date()};
}
// 填充默认属性值
setDefaultValues(entity, fields, value);
}
/**
* 依据对象的属性数组和值数组对对象的属性进行赋值
*
* @param entity 对象
* @param fields 属性数组
* @param value 值数组
* @author liwen
*/
private static <T> void setDefaultValues(T entity, String[] fields, Object[] value) {
for (int i = 0; i < fields.length; i++) {
String field = fields[i];
if (ReflectionUtils.hasField(entity, field)) {
ReflectionUtils.invokeSetter(entity, field, value[i]);
}
}
}
/**
* 根据主键属性,判断主键是否值为空
*
* @param entity
* @param field
* @return 主键为空则返回false主键有值返回true
* @author liwen
* @date 2016年4月28日
*/
public static <T> boolean isPKNotNull(T entity, String field) {
if (!ReflectionUtils.hasField(entity, field)) {
return false;
}
Object value = ReflectionUtils.getFieldValue(entity, field);
return value != null && !"".equals(value);
}
}

View File

@@ -0,0 +1,46 @@
package com.epri.fx.server.util;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 查询参数
*/
public class Query extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
//当前页码
private int page = 1;
//每页条数
private int limit = 10;
public Query(Map<String, Object> params){
this.putAll(params);
//分页参数
if(params.get("page")!=null) {
this.page = Integer.parseInt(params.get("page").toString());
}
if(params.get("limit")!=null) {
this.limit = Integer.parseInt(params.get("limit").toString());
}
this.remove("page");
this.remove("limit");
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
}

View File

@@ -0,0 +1,341 @@
package com.epri.fx.server.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.lang.reflect.*;
/**
* 反射工具类.
* 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings("rawtypes")
public class ReflectionUtils {
private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get";
private static final String CGLIB_CLASS_SEPARATOR = "$$";
private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
/**
* 调用Getter方法.
* 支持多级,如:对象名.对象名.方法
*/
public static Object invokeGetter(Object obj, String propertyName) {
Object object = obj;
for (String name : StringUtils.split(propertyName, ".")){
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
}
return object;
}
/**
* 调用Setter方法, 仅匹配方法名。
* 支持多级,如:对象名.对象名.方法
*/
public static void invokeSetter(Object obj, String propertyName, Object value) {
Object object = obj;
String[] names = StringUtils.split(propertyName, ".");
for (int i=0; i<names.length; i++){
if(i<names.length-1){
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
}else{
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
invokeMethodByName(object, setterMethodName, new Object[] { value });
}
}
}
/**
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
*/
public static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
}
/**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
logger.error("Could not find field [" + fieldName + "] on target [" + obj + "]");
return;
//throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, convert(value, field.getType()));
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e.getMessage());
}
}
public static Object convert(Object object, Class<?> type) {
if (object instanceof Number) {
Number number = (Number) object;
if (type.equals(byte.class) || type.equals(Byte.class)) {
return number.byteValue();
}
if (type.equals(short.class) || type.equals(Short.class)) {
return number.shortValue();
}
if (type.equals(int.class) || type.equals(Integer.class)) {
return number.intValue();
}
if (type.equals(long.class) || type.equals(Long.class)) {
return number.longValue();
}
if (type.equals(float.class) || type.equals(Float.class)) {
return number.floatValue();
}
if (type.equals(double.class) || type.equals(Double.class)) {
return number.doubleValue();
}
}
if(type.equals(String.class)){
return object==null?"":object.toString();
}
return object;
}
/**
* 直接调用对象方法, 无视private/protected修饰符.
* 用于一次性调用的情况否则应使用getAccessibleMethod()函数获得Method后反复调用.
* 同时匹配方法名+参数类型,
*/
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 直接调用对象方法, 无视private/protected修饰符
* 用于一次性调用的情况否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
* 只匹配函数名,如果有多个同名函数调用第一个。
*/
public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
Method method = getAccessibleMethodByName(obj, methodName);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
*
* 如向上转型到Object仍无法找到, 返回null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field);
return field;
} catch (NoSuchFieldException e) {//NOSONAR
// Field不在当前类定义,继续向上转型
continue;// new add
}
}
return null;
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
* 匹配函数名+参数类型。
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
try {
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
} catch (NoSuchMethodException e) {
// Method不在当前类定义,继续向上转型
continue;// new add
}
}
return null;
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
* 只匹配函数名。
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
makeAccessible(method);
return method;
}
}
}
return null;
}
/**
* 改变private/protected的方法为public尽量不调用实际改动的语句避免JDK的SecurityManager抱怨。
*/
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
/**
* 改变private/protected的成员变量为public尽量不调用实际改动的语句避免JDK的SecurityManager抱怨。
*/
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
/**
* 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
* 如无法找到, 返回Object.class.
* eg.
* public UserDao extends HibernateDao<User>
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassGenricType(final Class clazz) {
return getClassGenricType(clazz, 0);
}
/**
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
* 如无法找到, 返回Object.class.
*
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be determined
*/
public static Class getClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
public static Class<?> getUserClass(Object instance) {
Assert.notNull(instance, "Instance must not be null");
Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) {
return superClass;
}
}
return clazz;
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException(e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}
/**
* 判断某个对象是否拥有某个属性
*
* @param obj 对象
* @param fieldName 属性名
* @return 有属性返回true
* 无属性返回false
*/
public static boolean hasField(final Object obj, final String fieldName){
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,16 @@
package com.epri.fx.server.util;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class StringHelper {
public static String getObjectValue(Object obj){
return obj==null?"":obj.toString();
}
}

View File

@@ -0,0 +1,75 @@
package com.epri.fx.server.util;
import com.epri.fx.server.vo.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ace on 2017/6/12.
*/
public class TreeUtil {
/**
* 两层循环实现建树
*
* @param treeNodes 传入的树节点列表
* @return
*/
public static <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<T>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(treeNode);
}
for (T it : treeNodes) {
if (it.getParentId() == treeNode.getId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.add(it);
}
}
}
return trees;
}
/**
* 使用递归方法建树
*
* @param treeNodes
* @return
*/
public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes,Object root) {
List<T> trees = new ArrayList<T>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
}
return trees;
}
/**
* 递归查找子节点
*
* @param treeNodes
* @return
*/
public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
for (T it : treeNodes) {
if (treeNode.getId() == it.getParentId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.add(findChildren(it, treeNodes));
}
}
return treeNode;
}
}

View File

@@ -0,0 +1,34 @@
package com.epri.fx.server.util;
import java.util.UUID;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class UUIDUtils {
public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
public static String generateShortUuid() {
StringBuffer shortBuffer = new StringBuffer();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]);
}
return shortBuffer.toString();
}
}

View File

@@ -0,0 +1,37 @@
package com.epri.fx.server.util.user;
import java.io.Serializable;
public class JwtAuthenticationRequest implements Serializable {
private static final long serialVersionUID = -8445943548965154778L;
private String username;
private String password;
public JwtAuthenticationRequest(String username, String password) {
this.username = username;
this.password = password;
}
public JwtAuthenticationRequest() {
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}

View File

@@ -0,0 +1,17 @@
package com.epri.fx.server.util.user;
import java.io.Serializable;
public class JwtAuthenticationResponse implements Serializable {
private static final long serialVersionUID = 1250166508152483573L;
private final String token;
public JwtAuthenticationResponse(String token) {
this.token = token;
}
public String getToken() {
return this.token;
}
}

View File

@@ -0,0 +1,38 @@
package com.epri.fx.server.util.user;
import com.epri.fx.server.config.KeyConfiguration;
import com.epri.fx.server.jwt.IJWTInfo;
import com.epri.fx.server.jwt.JWTHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
@Component
public class JwtTokenUtil {
@Value("${jwt.expire}")
private int expire;
@Autowired
private KeyConfiguration keyConfiguration;
public String generateToken(IJWTInfo jwtInfo) throws Exception {
return JWTHelper.generateToken(jwtInfo, keyConfiguration.getUserPriKey(),expire);
}
public IJWTInfo getInfoFromToken(String token) throws Exception {
return JWTHelper.getInfoFromToken(token, keyConfiguration.getUserPubKey());
}
}

View File

@@ -0,0 +1,179 @@
package com.epri.fx.server.vo;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class ElementVO {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty code = new SimpleStringProperty();
private SimpleStringProperty type = new SimpleStringProperty();
private SimpleStringProperty name = new SimpleStringProperty();
private SimpleStringProperty uri = new SimpleStringProperty();
private SimpleStringProperty menuId = new SimpleStringProperty();
private SimpleStringProperty parentId = new SimpleStringProperty();
private SimpleStringProperty path = new SimpleStringProperty();
private SimpleStringProperty method = new SimpleStringProperty();
private SimpleStringProperty description = new SimpleStringProperty();
private SimpleBooleanProperty sel = new SimpleBooleanProperty(false);
public ElementVO() {
}
public ElementVO(Integer id, String code, String type, String name, String uri, String menuId, String parentId, String path, String method, String description) {
this.id.set(id);
this.code.set(code);
this.type.set(type);
this.name.set(name);
this.uri.set(uri);
this.menuId.set(menuId);
this.parentId.set(parentId);
this.path.set(path);
this.method.set(method);
this.description.set(description);
}
public String getCode() {
return code.get();
}
public SimpleStringProperty codeProperty() {
return code;
}
public void setCode(String code) {
this.code.set(code);
}
public String getType() {
return type.get();
}
public SimpleStringProperty typeProperty() {
return type;
}
public void setType(String type) {
this.type.set(type);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getUri() {
return uri.get();
}
public SimpleStringProperty uriProperty() {
return uri;
}
public void setUri(String uri) {
this.uri.set(uri);
}
public String getMenuId() {
return menuId.get();
}
public SimpleStringProperty menuIdProperty() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId.set(menuId);
}
public String getParentId() {
return parentId.get();
}
public SimpleStringProperty parentIdProperty() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId.set(parentId);
}
public String getPath() {
return path.get();
}
public SimpleStringProperty pathProperty() {
return path;
}
public void setPath(String path) {
this.path.set(path);
}
public String getMethod() {
return method.get();
}
public SimpleStringProperty methodProperty() {
return method;
}
public void setMethod(String method) {
this.method.set(method);
}
public String getDescription() {
return description.get();
}
public SimpleStringProperty descriptionProperty() {
return description;
}
public void setDescription(String description) {
this.description.set(description);
}
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
public boolean isSel() {
return sel.get();
}
public SimpleBooleanProperty selProperty() {
return sel;
}
public void setSel(boolean sel) {
this.sel.set(sel);
}
}

View File

@@ -0,0 +1,86 @@
package com.epri.fx.server.vo;
import java.util.List;
/**
* @Description:
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class FrontUser {
public String id;
public String username;
public String name;
private String description;
private String image;
private List<PermissionInfo> menus;
private List<PermissionInfo> elements;
private List<GroupVO> roles;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<PermissionInfo> getMenus() {
return menus;
}
public void setMenus(List<PermissionInfo> menus) {
this.menus = menus;
}
public List<PermissionInfo> getElements() {
return elements;
}
public void setElements(List<PermissionInfo> elements) {
this.elements = elements;
}
public List<GroupVO> getRoles() {
return roles;
}
public void setRoles(List<GroupVO> roles) {
this.roles = roles;
}
}

View File

@@ -0,0 +1,33 @@
package com.epri.fx.server.vo;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-17 15:21
*/
public class GroupTree {
int id;
int parentId;
String label;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,102 @@
package com.epri.fx.server.vo;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import java.io.Serializable;
import java.util.Date;
public class GroupTypeVO implements Serializable {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty code = new SimpleStringProperty();
private SimpleStringProperty name = new SimpleStringProperty();
private SimpleStringProperty description = new SimpleStringProperty();
private SimpleObjectProperty updTime = new SimpleObjectProperty();
private SimpleStringProperty updHost = new SimpleStringProperty();
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
public String getCode() {
return code.get();
}
public SimpleStringProperty codeProperty() {
return code;
}
public void setCode(String code) {
this.code.set(code);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getDescription() {
return description.get();
}
public SimpleStringProperty descriptionProperty() {
return description;
}
public void setDescription(String description) {
this.description.set(description);
}
public Object getUpdTime() {
return updTime.get();
}
public SimpleObjectProperty updTimeProperty() {
return updTime;
}
public void setUpdTime(Object updTime) {
this.updTime.set(updTime);
}
public String getUpdHost() {
return updHost.get();
}
public SimpleStringProperty updHostProperty() {
return updHost;
}
public void setUpdHost(String updHost) {
this.updHost.set(updHost);
}
@Override
public String toString() {
return getName();
}
}

View File

@@ -0,0 +1,54 @@
package com.epri.fx.server.vo;
import com.epri.fx.server.entity.User;
import java.util.List;
/**
*
* @Description:
*
* @param:
* @return:
* @auther: liwen
* @date: 2020/8/2 10:56 上午
*/
public class GroupUsers {
List<User> members;
List<User> leaders;
List<User> users;
public GroupUsers() {
}
public GroupUsers(List<User> members, List<User> leaders, List<User> users) {
this.members = members;
this.leaders = leaders;
this.users = users;
}
public List<User> getMembers() {
return members;
}
public void setMembers(List<User> members) {
this.members = members;
}
public List<User> getLeaders() {
return leaders;
}
public void setLeaders(List<User> leaders) {
this.leaders = leaders;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}

View File

@@ -0,0 +1,109 @@
package com.epri.fx.server.vo;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import java.io.Serializable;
/**
* @description:
* @className: GroupVO
* @author: liwen
* @date: 2020/7/23 09:54
*/
public class GroupVO implements Serializable {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty code = new SimpleStringProperty();
private SimpleStringProperty name = new SimpleStringProperty();
private SimpleIntegerProperty parentId = new SimpleIntegerProperty();
private SimpleIntegerProperty groupType = new SimpleIntegerProperty();
private SimpleStringProperty description = new SimpleStringProperty();
public GroupVO() {
}
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
public String getCode() {
return code.get();
}
public SimpleStringProperty codeProperty() {
return code;
}
public void setCode(String code) {
this.code.set(code);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public int getParentId() {
return parentId.get();
}
public SimpleIntegerProperty parentIdProperty() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId.set(parentId);
}
public int getGroupType() {
return groupType.get();
}
public SimpleIntegerProperty groupTypeProperty() {
return groupType;
}
public void setGroupType(int groupType) {
this.groupType.set(groupType);
}
public String getDescription() {
return description.get();
}
public SimpleStringProperty descriptionProperty() {
return description;
}
public void setDescription(String description) {
this.description.set(description);
}
@Override
public String toString() {
return getName();
}
}

View File

@@ -0,0 +1,213 @@
package com.epri.fx.server.vo;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MenuVO implements Serializable {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty code = new SimpleStringProperty();
private SimpleStringProperty title = new SimpleStringProperty();
private SimpleIntegerProperty parentId = new SimpleIntegerProperty();
private SimpleStringProperty href = new SimpleStringProperty();
private SimpleStringProperty icon = new SimpleStringProperty();
private SimpleStringProperty type = new SimpleStringProperty();
private SimpleIntegerProperty orderNum = new SimpleIntegerProperty();
private SimpleStringProperty description = new SimpleStringProperty();
private SimpleStringProperty path = new SimpleStringProperty();
private SimpleStringProperty enabled = new SimpleStringProperty();
private SimpleStringProperty node = new SimpleStringProperty();
private SimpleBooleanProperty sel = new SimpleBooleanProperty(false);
private List<ElementVO> elementVOS;
public MenuVO() {
}
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
public String getCode() {
return code.get();
}
public SimpleStringProperty codeProperty() {
return code;
}
public void setCode(String code) {
this.code.set(code);
}
public String getTitle() {
return title.get();
}
public SimpleStringProperty titleProperty() {
return title;
}
public void setTitle(String title) {
this.title.set(title);
}
public int getParentId() {
return parentId.get();
}
public SimpleIntegerProperty parentIdProperty() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId.set(parentId);
}
public String getHref() {
return href.get();
}
public SimpleStringProperty hrefProperty() {
return href;
}
public void setHref(String href) {
this.href.set(href);
}
public String getIcon() {
return icon.get();
}
public SimpleStringProperty iconProperty() {
return icon;
}
public void setIcon(String icon) {
this.icon.set(icon);
}
public String getType() {
return type.get();
}
public SimpleStringProperty typeProperty() {
return type;
}
public void setType(String type) {
this.type.set(type);
}
public Integer getOrderNum() {
return orderNum.get();
}
public SimpleIntegerProperty orderNumProperty() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum.set(orderNum);
}
public String getDescription() {
return description.get();
}
public SimpleStringProperty descriptionProperty() {
return description;
}
public void setDescription(String description) {
this.description.set(description);
}
public String getPath() {
return path.get();
}
public SimpleStringProperty pathProperty() {
return path;
}
public void setPath(String path) {
this.path.set(path);
}
public String getEnabled() {
return enabled.get();
}
public SimpleStringProperty enabledProperty() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled.set(enabled);
}
public String getNode() {
return node.get();
}
public SimpleStringProperty nodeProperty() {
return node;
}
public void setNode(String node) {
this.node.set(node);
}
public boolean isSel() {
return sel.get();
}
public SimpleBooleanProperty selProperty() {
return sel;
}
public void setSel(boolean sel) {
this.sel.set(sel);
}
public List<ElementVO> getElementVOS() {
if (elementVOS == null) {
elementVOS = new ArrayList<>();
}
return elementVOS;
}
@Override
public String toString() {
return getTitle();
}
}

View File

@@ -0,0 +1,68 @@
package com.epri.fx.server.vo;
import java.io.Serializable;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-22 15:19
*/
public class PermissionInfo implements Serializable{
private String code;
private String type;
private String uri;
private String method;
private String name;
private String menu;
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}

View File

@@ -0,0 +1,43 @@
package com.epri.fx.server.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ace on 2017/6/12.
*/
public class TreeNode implements Serializable {
protected int id;
protected int parentId;
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
List<TreeNode> children = new ArrayList<TreeNode>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public void add(TreeNode node){
children.add(node);
}
}

View File

@@ -0,0 +1,118 @@
package com.epri.fx.server.vo;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class UserVO {
private SimpleStringProperty name = new SimpleStringProperty();
private SimpleStringProperty userName = new SimpleStringProperty();
private SimpleStringProperty description = new SimpleStringProperty();
private SimpleStringProperty updTime = new SimpleStringProperty();
private SimpleStringProperty updUser = new SimpleStringProperty();
private SimpleStringProperty sex = new SimpleStringProperty();
private SimpleIntegerProperty id = new SimpleIntegerProperty();
public UserVO() {
}
public UserVO(Integer id, String name, String userName, String updTime, String updUser, String sex, String description) {
this.name = new SimpleStringProperty(name);
this.userName = new SimpleStringProperty(userName);
this.description = new SimpleStringProperty(description);
this.updTime = new SimpleStringProperty(updTime);
this.updUser = new SimpleStringProperty(updUser);
this.sex = new SimpleStringProperty(sex);
this.id = new SimpleIntegerProperty(id);
;
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getUserName() {
return userName.get();
}
public SimpleStringProperty userNameProperty() {
return userName;
}
public void setUserName(String userName) {
this.userName.set(userName);
}
public String getDescription() {
return description.get();
}
public SimpleStringProperty descriptionProperty() {
return description;
}
public void setDescription(String description) {
this.description.set(description);
}
public String getUpdTime() {
return updTime.get();
}
public SimpleStringProperty updTimeProperty() {
return updTime;
}
public void setUpdTime(String updTime) {
this.updTime.set(updTime);
}
public String getUpdUser() {
return updUser.get();
}
public SimpleStringProperty updUserProperty() {
return updUser;
}
public void setUpdUser(String updUser) {
this.updUser.set(updUser);
}
public String getSex() {
return sex.get();
}
public SimpleStringProperty sexProperty() {
return sex;
}
public void setSex(String sex) {
this.sex.set(sex);
}
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
@Override
public String toString() {
return getUserName();
}
}

View File

@@ -0,0 +1,49 @@
server:
port: 8080
spring:
datasource:
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
#url: jdbc:dm://10.105.73.121:12345/EMSHIS
url: jdbc:dm://192.168.1.210:12345/EMSHIS
username: IPSM_DBA
password: IPSM_DBA
driver-class-name: dm.jdbc.driver.DmDriver
# 连接池的配置信息
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters去掉后监控界面sql无法统计'wall'用于防火墙
filters: stat
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
mybatis:
basepackage: com.wlkj.ipsm.realtime.mapper
xmlLocation: classpath:mapper/**/*.xml
mapper-locations: "classpath*:mapper/*.xml"
#分页控件配置
pagehelper:
helper-dialect: dm
reasonable: true
support-methods-arguments: true
params: countSql

View File

@@ -0,0 +1,48 @@
server:
port: 8080
spring:
datasource:
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://${MYSQL_HOST:10.211.55.3}:${MYSQL_PORT:3306}/ipsm_dba?serverTimezone=Asia/Shanghai
username: root
password: Root@12345
driver-class-name: com.mysql.cj.jdbc.Driver
# 连接池的配置信息
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT "x"
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters去掉后监控界面sql无法统计'wall'用于防火墙
filters: stat
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
mybatis:
basepackage: com.epri.fx.server.mapper
xmlLocation: classpath:mapper/*.xml
mapper-locations: "classpath*:mapper/*.xml"
#分页控件配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: countSql

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,17 @@
spring:
profiles:
active: mysql
#日志输出
logging:
level:
com.epri.fx.server: debug
jwt:
token-header: Authorization
expire: 14400
rsa-secret: xx1WET12^%3^(WE45
auth:
user:
token-header: Authorization

View File

@@ -0,0 +1,324 @@
<?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.epri.fx.server.mapper.ElementMapper">
<resultMap id="BaseResultMap" type="com.epri.fx.server.entity.Element">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="code" jdbcType="VARCHAR" property="code"/>
<result column="type" jdbcType="VARCHAR" property="type"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="uri" jdbcType="VARCHAR" property="uri"/>
<result column="menu_id" jdbcType="VARCHAR" property="menuId"/>
<result column="parent_id" jdbcType="VARCHAR" property="parentId"/>
<result column="path" jdbcType="VARCHAR" property="path"/>
<result column="method" jdbcType="VARCHAR" property="method"/>
<result column="description" jdbcType="VARCHAR" property="description"/>
<result column="crt_time" jdbcType="TIMESTAMP" property="crtTime"/>
<result column="crt_user" jdbcType="VARCHAR" property="crtUser"/>
<result column="crt_name" jdbcType="VARCHAR" property="crtName"/>
<result column="crt_host" jdbcType="VARCHAR" property="crtHost"/>
<result column="attr1" jdbcType="VARCHAR" property="attr1"/>
<result column="attr2" jdbcType="VARCHAR" property="attr2"/>
<result column="attr3" jdbcType="VARCHAR" property="attr3"/>
<result column="attr4" jdbcType="VARCHAR" property="attr4"/>
<result column="attr5" jdbcType="VARCHAR" property="attr5"/>
<result column="attr6" jdbcType="VARCHAR" property="attr6"/>
<result column="attr7" jdbcType="VARCHAR" property="attr7"/>
<result column="attr8" jdbcType="VARCHAR" property="attr8"/>
</resultMap>
<sql id="Base_Column_List">
id, code, type, name, uri, menu_id, parent_id, path, method, description, crt_time,
crt_user, crt_name, crt_host, attr1, attr2, attr3, attr4, attr5, attr6, attr7, attr8
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_element
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from base_element
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.epri.fx.server.entity.Element">
insert into base_element (id, code, type,
name, uri, menu_id,
parent_id, path, method,
description, crt_time, crt_user,
crt_name, crt_host, attr1,
attr2, attr3, attr4,
attr5, attr6, attr7,
attr8)
values (#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR}, #{uri,jdbcType=VARCHAR}, #{menuId,jdbcType=VARCHAR},
#{parentId,jdbcType=VARCHAR}, #{path,jdbcType=VARCHAR}, #{method,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}, #{crtTime,jdbcType=TIMESTAMP}, #{crtUser,jdbcType=VARCHAR},
#{crtName,jdbcType=VARCHAR}, #{crtHost,jdbcType=VARCHAR}, #{attr1,jdbcType=VARCHAR},
#{attr2,jdbcType=VARCHAR}, #{attr3,jdbcType=VARCHAR}, #{attr4,jdbcType=VARCHAR},
#{attr5,jdbcType=VARCHAR}, #{attr6,jdbcType=VARCHAR}, #{attr7,jdbcType=VARCHAR},
#{attr8,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.epri.fx.server.entity.Element">
insert into base_element
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="code != null">
code,
</if>
<if test="type != null">
type,
</if>
<if test="name != null">
name,
</if>
<if test="uri != null">
uri,
</if>
<if test="menuId != null">
menu_id,
</if>
<if test="parentId != null">
parent_id,
</if>
<if test="path != null">
path,
</if>
<if test="method != null">
method,
</if>
<if test="description != null">
description,
</if>
<if test="crtTime != null">
crt_time,
</if>
<if test="crtUser != null">
crt_user,
</if>
<if test="crtName != null">
crt_name,
</if>
<if test="crtHost != null">
crt_host,
</if>
<if test="attr1 != null">
attr1,
</if>
<if test="attr2 != null">
attr2,
</if>
<if test="attr3 != null">
attr3,
</if>
<if test="attr4 != null">
attr4,
</if>
<if test="attr5 != null">
attr5,
</if>
<if test="attr6 != null">
attr6,
</if>
<if test="attr7 != null">
attr7,
</if>
<if test="attr8 != null">
attr8,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="code != null">
#{code,jdbcType=VARCHAR},
</if>
<if test="type != null">
#{type,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="uri != null">
#{uri,jdbcType=VARCHAR},
</if>
<if test="menuId != null">
#{menuId,jdbcType=VARCHAR},
</if>
<if test="parentId != null">
#{parentId,jdbcType=VARCHAR},
</if>
<if test="path != null">
#{path,jdbcType=VARCHAR},
</if>
<if test="method != null">
#{method,jdbcType=VARCHAR},
</if>
<if test="description != null">
#{description,jdbcType=VARCHAR},
</if>
<if test="crtTime != null">
#{crtTime,jdbcType=TIMESTAMP},
</if>
<if test="crtUser != null">
#{crtUser,jdbcType=VARCHAR},
</if>
<if test="crtName != null">
#{crtName,jdbcType=VARCHAR},
</if>
<if test="crtHost != null">
#{crtHost,jdbcType=VARCHAR},
</if>
<if test="attr1 != null">
#{attr1,jdbcType=VARCHAR},
</if>
<if test="attr2 != null">
#{attr2,jdbcType=VARCHAR},
</if>
<if test="attr3 != null">
#{attr3,jdbcType=VARCHAR},
</if>
<if test="attr4 != null">
#{attr4,jdbcType=VARCHAR},
</if>
<if test="attr5 != null">
#{attr5,jdbcType=VARCHAR},
</if>
<if test="attr6 != null">
#{attr6,jdbcType=VARCHAR},
</if>
<if test="attr7 != null">
#{attr7,jdbcType=VARCHAR},
</if>
<if test="attr8 != null">
#{attr8,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.epri.fx.server.entity.Element">
update base_element
<set>
<if test="code != null">
code = #{code,jdbcType=VARCHAR},
</if>
<if test="type != null">
type = #{type,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="uri != null">
uri = #{uri,jdbcType=VARCHAR},
</if>
<if test="menuId != null">
menu_id = #{menuId,jdbcType=VARCHAR},
</if>
<if test="parentId != null">
parent_id = #{parentId,jdbcType=VARCHAR},
</if>
<if test="path != null">
path = #{path,jdbcType=VARCHAR},
</if>
<if test="method != null">
method = #{method,jdbcType=VARCHAR},
</if>
<if test="description != null">
description = #{description,jdbcType=VARCHAR},
</if>
<if test="crtTime != null">
crt_time = #{crtTime,jdbcType=TIMESTAMP},
</if>
<if test="crtUser != null">
crt_user = #{crtUser,jdbcType=VARCHAR},
</if>
<if test="crtName != null">
crt_name = #{crtName,jdbcType=VARCHAR},
</if>
<if test="crtHost != null">
crt_host = #{crtHost,jdbcType=VARCHAR},
</if>
<if test="attr1 != null">
attr1 = #{attr1,jdbcType=VARCHAR},
</if>
<if test="attr2 != null">
attr2 = #{attr2,jdbcType=VARCHAR},
</if>
<if test="attr3 != null">
attr3 = #{attr3,jdbcType=VARCHAR},
</if>
<if test="attr4 != null">
attr4 = #{attr4,jdbcType=VARCHAR},
</if>
<if test="attr5 != null">
attr5 = #{attr5,jdbcType=VARCHAR},
</if>
<if test="attr6 != null">
attr6 = #{attr6,jdbcType=VARCHAR},
</if>
<if test="attr7 != null">
attr7 = #{attr7,jdbcType=VARCHAR},
</if>
<if test="attr8 != null">
attr8 = #{attr8,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.epri.fx.server.entity.Element">
update base_element
set code = #{code,jdbcType=VARCHAR},
type = #{type,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
uri = #{uri,jdbcType=VARCHAR},
menu_id = #{menuId,jdbcType=VARCHAR},
parent_id = #{parentId,jdbcType=VARCHAR},
path = #{path,jdbcType=VARCHAR},
method = #{method,jdbcType=VARCHAR},
description = #{description,jdbcType=VARCHAR},
crt_time = #{crtTime,jdbcType=TIMESTAMP},
crt_user = #{crtUser,jdbcType=VARCHAR},
crt_name = #{crtName,jdbcType=VARCHAR},
crt_host = #{crtHost,jdbcType=VARCHAR},
attr1 = #{attr1,jdbcType=VARCHAR},
attr2 = #{attr2,jdbcType=VARCHAR},
attr3 = #{attr3,jdbcType=VARCHAR},
attr4 = #{attr4,jdbcType=VARCHAR},
attr5 = #{attr5,jdbcType=VARCHAR},
attr6 = #{attr6,jdbcType=VARCHAR},
attr7 = #{attr7,jdbcType=VARCHAR},
attr8 = #{attr8,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectElementList" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from base_element
where menu_id = #{menuId,jdbcType=INTEGER}
</select>
<select id="selectAllElementPermissions" resultMap="BaseResultMap">
select distinct t.code,t.type,t.name,t.uri,t.method,m.title as menu_id from base_element t
inner join base_menu m
on t.menu_id = m.id
</select>
<select id="selectAuthorityElementByUserId" resultMap="BaseResultMap">
select distinct t.code,t.type,t.name,t.uri,t.method,m.title as menu_id from base_resource_authority ra
inner join base_element t
on ra.resource_id = t.id
and ra.authority_id in (
select group_id from base_group_member where user_id = #{userId}
union select group_id from base_group_leader where user_id = #{userId}
)
and ra.authority_type = 'group'
and ra.resource_type = 'button'
inner join base_menu m
on t.menu_id = m.id
</select>
<delete id="deleteByMenuId" parameterType="java.lang.Integer">
delete from base_element
where menu_id = #{menuId,jdbcType=INTEGER}
</delete>
</mapper>

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