Commit 85d566a0 authored by ma's avatar ma

Merge branch 'for-yx' of http://120.77.240.215:9701/tianlai3/ioc_sixiang_license into for-yx

parents 920b3d16 c897a5ba
# 注意事项
##### 2023.1版本
> 1. 执行update.2023.1.sql
> 2. 原来的root账号要换成邮箱,包括user_name和notify字段,两个都填超管账号邮箱。
\ No newline at end of file
-----BEGIN CERTIFICATE-----
MIIDHjCCAgYCCQCTGGHg/dGQXjANBgkqhkiG9w0BAQUFADBRMQswCQYDVQQGEwJD
TjELMAkGA1UECAwCR0QxCzAJBgNVBAcMAkdaMQswCQYDVQQKDAJTUjELMAkGA1UE
CwwCU1IxDjAMBgNVBAMMBVNSLUNBMB4XDTIzMDIwMzA5NTQ0MVoXDTMzMDEzMTA5
NTQ0MVowUTELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAkdEMQswCQYDVQQHDAJHWjEL
MAkGA1UECgwCU1IxCzAJBgNVBAsMAlNSMQ4wDAYDVQQDDAVTUi1DQTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAOGm68efDJou2ElrzrEUpDGSp5oOqn+6
0UbFKquObbH1sfnkpJeJYsTLT9EkZYEt1um76St2+4VJAyeLC6KEW4j8q8QoIoDD
wYa85+uwEgNAj8AJikBidCboFjdgtHJLqwmrdJGHYtqnFnIdyvzLZe7GrxsbDhZ3
99qEaxvYmwGRI7ZkT5v9lPpw9RqfPysaS829zn6W1mUCeVPPMSbCtgSqsYjRPDHu
zi15GygEnsMMFTozSvLm5xrpSbY9jNvXo5weUy/OCaIkiVmiL2dUVMf10y4Pphxv
zGnnX78dJ7iuo1as+V0zs6CngVdiMWmmt1yX2TyTsm2tbZHH5w+wknkCAwEAATAN
BgkqhkiG9w0BAQUFAAOCAQEAFO/2fvXzpJzFcBAxMPLh5HrGXim+E3WOaRjfzskk
GYj9o7re/nJIhTEY/YngNGdoRLMvKtA4uHjiv4ca0ecSiOJX7y+AqtwbLorSHwot
CmGBTOPiG5KkL8bo+OarLWve9WLwaK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xAJRCRS9e0ECpra3AB+MbP
GjFCi0Pqksq1qsu1QtgfzBDDx4w9w+Hwrlp9EqAgj9hFE844rU0aPEbrAuVEvYW4
4/LJjwVqjnO4rAOIupn2QxH/
-----END PRIVATE KEY-----
# 1.生成服务器端私钥
openssl genrsa -out server.key 2048
# 2.生成服务器端公钥
openssl rsa -in server.key -pubout -out server.pem
# 3.生成客户端私钥
openssl genrsa -out client.key 2048
# 4.生成客户端公钥
openssl rsa -in client.key -pubout -out client.pem
# 5.生成 CA 私钥
openssl genrsa -out ca.key 2048
# 6.生成CA的csr文件,保存必要信息
openssl req -new -key ca.key -out ca.csr
# 7.生成CA的证书文件crt文件
openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt -days 3650
# 8.生成服务器端的csr文件,为生成服务器证书做准备
openssl req -new -key server.key -out server.csr
# 9.生成服务器端证书crt文件
openssl x509 -req -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.crt -days 3650
# 10.生成client 端csr文件,为生成client证书做准备
openssl req -new -key client.key -out client.csr
# 11.生成client 端证书crt文件
openssl x509 -req -CA ca.crt -CAkey ca.key -CAcreateserial -in client.csr -out client.crt -days 3650
# 将key文件进行PKCS8编码
openssl pkcs8 -topk8 -in server.key -out server.pkcs8.key -nocrypt
openssl pkcs8 -topk8 -in client.key -out client.pkcs8.key -nocrypt
# 注意生成的 Common Name不能一样,否则客户端会出错
\ No newline at end of file
-----BEGIN CERTIFICATE-----
MIIDIjCCAgoCCQC4HC3Atwq+1zANBgkqhkiG9w0BAQUFADBRMQswCQYDVQQGEwJD
TjELMAkGA1UECAwCR0QxCzAJBgNVBAcMAkdaMQswCQYDVQQKDAJTUjELMAkGA1UE
CwwCU1IxDjAMBgNVBAMMBVNSLUNBMB4XDTIzMDIwMzA5NTUxOVoXDTMzMDEzMTA5
NTUxOVowVTELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAkdEMQswCQYDVQQHDAJHWjEL
MAkGA1UECgwCU1IxCzAJBgNVBAs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/k
031BnWwN9GSwF+Ybi+clK9XwdkZ48fL6YnRtrzYPzWLrTqtqFRM5Y1q2GtNOXqW0
NjesBdv7z1ojvUOcUDZnHuHTUvRrk5k2ngDws58AvDyuu/aJwL/hGEc+OXsw8sEA
hQzxGsuou5osqIml3CjtBp0=
-----END PRIVATE KEY-----
# -------------------- 平台应用相关,以pms开头 -------------------- -------------------- 平台应用相关,以pms开头 --------------------
DROP TABLE IF EXISTS `pms_use_log`; DROP TABLE IF EXISTS `pms_use_log`;
CREATE TABLE `pms_use_log` CREATE TABLE `pms_use_log`
( (
......
ALTER TABLE `user`
ADD COLUMN `notify` varchar(50) NULL DEFAULT NULL COMMENT '报警的邮箱,注册的时候用户名是邮箱则这里自动填那个邮箱,可以修改' AFTER `company`,
ADD COLUMN `parent` int(11) NULL COMMENT '父账号标识,空则表示超管,一级' AFTER `notify`,
ADD COLUMN `level` int(1) NULL COMMENT '账号等级(共有三级),空则表示二级' AFTER `parent`;
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission`
(
`id` int(10) NOT NULL AUTO_INCREMENT,
`description` varchar(50) DEFAULT NULL COMMENT '权限说明',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`deleted` int(1) DEFAULT '0' COMMENT '逻辑删除标识 1:删除,0:未删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT ='权限表';
CREATE TABLE `user_permission`
(
`id` int(10) NOT NULL AUTO_INCREMENT,
`permission` int(10) NOT NULL COMMENT '权限标识',
`user` int(11) NOT NULL COMMENT '用户标识',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`deleted` int(1) DEFAULT '0' COMMENT '逻辑删除标识 1:删除,0:未删除',
UNIQUE KEY `user_permission_unique_key` (`permission`,`user`),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT ='用户权限表';
-- 添加权限 --
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (1, '邀请注册', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (2, '删除用户', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (3, '应用管理', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (4, '设备管理', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (5, '运维管理', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (6, '日志管理', NULL, NULL, 0);
INSERT INTO `permission` (`id`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (7, '安全报警', NULL, NULL, 0);
-- 报警类型表 --
DROP TABLE IF EXISTS `report_type`;
CREATE TABLE `report_type`
(
`id` int(10) NOT NULL AUTO_INCREMENT,
`category` int(1) DEFAULT NULL COMMENT '报警大类 1:系统,0:设备',
`description` varchar(100) DEFAULT NULL COMMENT '说明',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`deleted` int(1) DEFAULT '0' COMMENT '逻辑删除标识 1:删除,0:未删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT ='报警类型表';
-- 报警表 --
DROP TABLE IF EXISTS `report`;
CREATE TABLE `report`
(
`id` int(10) NOT NULL AUTO_INCREMENT,
`category` int(1) DEFAULT NULL COMMENT '报警大类 1:系统,0:设备',
`type` int(3) DEFAULT NULL COMMENT '报警类型',
`sn` varchar(50) DEFAULT NULL COMMENT '设备编码(系统报警该值为空)',
`description` varchar(100) DEFAULT NULL COMMENT '报警说明',
`user_name` varchar(50) DEFAULT NULL COMMENT '报警账户',
`user_company` varchar(50) DEFAULT NULL COMMENT '报警公司',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`deleted` int(1) DEFAULT '0' COMMENT '逻辑删除标识 1:删除,0:未删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT ='报警表';
-- 新增报警类型 --
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (1, 1, '系统故障', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (2, 1, '系统超负荷', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (3, 1, '系统连接失败', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (4, 0, '数据请求失败', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (5, 0, '卡交互失败', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (6, 0, '鉴权失败', NULL, NULL, 0);
INSERT INTO `report_type` (`id`, `category`, `description`, `create_time`, `update_time`, `deleted`)
VALUES (7, 0, '解码失败', NULL, NULL, 0);
...@@ -115,22 +115,10 @@ ...@@ -115,22 +115,10 @@
<artifactId>bcprov-jdk15to18</artifactId> <artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version> <version>1.69</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.2</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.owasp.antisamy</groupId> <groupId>org.owasp.antisamy</groupId>
......
...@@ -46,7 +46,7 @@ public class AuthManager { ...@@ -46,7 +46,7 @@ public class AuthManager {
public void initApps() { public void initApps() {
allApply = new HashMap<>(); allApply = new HashMap<>();
PageInfoModel<AppVo> records = applyService.getAppList(1, 10000, ""); PageInfoModel<AppVo> records = applyService.getAppList(1, 10000, "", null);
List<AppVo> appList = records.getResult(); List<AppVo> appList = records.getResult();
for (Apply apply : appList) { for (Apply apply : appList) {
String appId = apply.getAppId(); String appId = apply.getAppId();
......
...@@ -5,7 +5,11 @@ import lombok.extern.slf4j.Slf4j; ...@@ -5,7 +5,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
...@@ -41,4 +45,5 @@ public class CorsConfig implements WebMvcConfigurer { ...@@ -41,4 +45,5 @@ public class CorsConfig implements WebMvcConfigurer {
registry.addInterceptor(authenticationInterceptor) registry.addInterceptor(authenticationInterceptor)
.addPathPatterns("/**"); .addPathPatterns("/**");
} }
} }
...@@ -21,10 +21,22 @@ import java.util.concurrent.ThreadPoolExecutor; ...@@ -21,10 +21,22 @@ import java.util.concurrent.ThreadPoolExecutor;
@Configuration @Configuration
@EnableAsync @EnableAsync
public class ThreadPoolConfig { public class ThreadPoolConfig {
private static final int corePoolSize = 1; // 核心线程数(默认线程数) /**
private static final int maxPoolSize = 2; // 最大线程数 * 核心线程数(默认线程数)
private static final int keepAliveTime = 10; // 允许线程空闲时间(单位:默认为秒) */
private static final int queueCapacity = 2; // 缓冲队列数 private static final int CORE_POOL_SIZE = 1;
/**
* 最大线程数
*/
private static final int MAX_POOL_SIZE = 2;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int KEEP_ALIVE_TIME = 10;
/**
* 缓冲队列数
*/
private static final int QUEUE_CAPACITY = 2;
/** /**
* 默认异步线程池 * 默认异步线程池
...@@ -35,13 +47,26 @@ public class ThreadPoolConfig { ...@@ -35,13 +47,26 @@ public class ThreadPoolConfig {
public Executor taskExecutor() { public Executor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setThreadNamePrefix("threadPoll-"); pool.setThreadNamePrefix("threadPoll-");
pool.setCorePoolSize(corePoolSize); pool.setCorePoolSize(CORE_POOL_SIZE);
pool.setMaxPoolSize(maxPoolSize); pool.setMaxPoolSize(MAX_POOL_SIZE);
pool.setKeepAliveSeconds(keepAliveTime); pool.setKeepAliveSeconds(KEEP_ALIVE_TIME);
pool.setQueueCapacity(queueCapacity); pool.setQueueCapacity(QUEUE_CAPACITY);
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化 // 初始化
pool.initialize(); pool.initialize();
return pool; return pool;
} }
@Bean("mailExecutor")
public Executor mailExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("threadPoll-mail-");
threadPoolTaskExecutor.setCorePoolSize(3);
threadPoolTaskExecutor.setMaxPoolSize(10);
threadPoolTaskExecutor.setKeepAliveSeconds(3);
threadPoolTaskExecutor.setQueueCapacity(1000);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
} }
...@@ -9,6 +9,8 @@ import io.swagger.annotations.Api; ...@@ -9,6 +9,8 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.log.BusinessType; import iot.sixiang.license.log.BusinessType;
import iot.sixiang.license.log.MyLog; import iot.sixiang.license.log.MyLog;
import iot.sixiang.license.model.BaseResult; import iot.sixiang.license.model.BaseResult;
...@@ -16,12 +18,15 @@ import iot.sixiang.license.model.PageInfoModel; ...@@ -16,12 +18,15 @@ import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.PageResult; import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.vo.AppVo; import iot.sixiang.license.model.vo.AppVo;
import iot.sixiang.license.service.ApplyService; import iot.sixiang.license.service.ApplyService;
import iot.sixiang.license.util.TreeUtil;
import iot.sixiang.license.xss.XssUtil; import iot.sixiang.license.xss.XssUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
...@@ -90,7 +95,14 @@ public class ApplyController { ...@@ -90,7 +95,14 @@ public class ApplyController {
@RequestParam(value = "pageSize", defaultValue = "0") int pageSize, @RequestParam(value = "pageSize", defaultValue = "0") int pageSize,
@RequestParam(value = "appName", required = false) String appName) { @RequestParam(value = "appName", required = false) String appName) {
appName = XssUtil.checkXSS(appName); appName = XssUtil.checkXSS(appName);
PageInfoModel<AppVo> records = applyService.getAppList(pageNo, pageSize, appName); String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
throw new IotLicenseException(403, "请重新登录");
}
List<Integer> userIds = new ArrayList<>();
List<Integer> userChildIds = TreeUtil.getUserChildIds(Integer.parseInt(userId), userIds);
userChildIds.add(Integer.parseInt(userId));
PageInfoModel<AppVo> records = applyService.getAppList(pageNo, pageSize, appName, userChildIds);
int total = records.getTotal(); int total = records.getTotal();
int pages = total / pageSize;//pages为总页数 int pages = total / pageSize;//pages为总页数
int mod = total % pageSize; int mod = total % pageSize;
......
...@@ -11,6 +11,8 @@ import io.swagger.annotations.ApiImplicitParams; ...@@ -11,6 +11,8 @@ import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import iot.sixiang.license.device.DeviceManager; import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.entity.DeviceBlack; import iot.sixiang.license.entity.DeviceBlack;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.log.BusinessType; import iot.sixiang.license.log.BusinessType;
import iot.sixiang.license.log.MyLog; import iot.sixiang.license.log.MyLog;
import iot.sixiang.license.model.BaseResult; import iot.sixiang.license.model.BaseResult;
...@@ -20,7 +22,9 @@ import iot.sixiang.license.model.vo.DeviceDetailVo; ...@@ -20,7 +22,9 @@ import iot.sixiang.license.model.vo.DeviceDetailVo;
import iot.sixiang.license.model.vo.DeviceVo; import iot.sixiang.license.model.vo.DeviceVo;
import iot.sixiang.license.service.DeviceBlackService; import iot.sixiang.license.service.DeviceBlackService;
import iot.sixiang.license.service.DeviceService; import iot.sixiang.license.service.DeviceService;
import iot.sixiang.license.util.TreeUtil;
import iot.sixiang.license.xss.XssUtil; import iot.sixiang.license.xss.XssUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
...@@ -31,6 +35,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -31,6 +35,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
...@@ -108,7 +113,14 @@ public class DeviceController { ...@@ -108,7 +113,14 @@ public class DeviceController {
@RequestParam(value = "status", required = false) Integer status) { @RequestParam(value = "status", required = false) Integer status) {
appName = XssUtil.checkXSS(appName); appName = XssUtil.checkXSS(appName);
userName = XssUtil.checkXSS(userName); userName = XssUtil.checkXSS(userName);
PageInfoModel<DeviceVo> records = deviceService.getDeviceList(pageNo, pageSize, appName, userName, sn, status); String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
throw new IotLicenseException(403, "请重新登录");
}
List<Integer> userIds = new ArrayList<>();
List<Integer> userChildIds = TreeUtil.getUserChildIds(Integer.parseInt(userId), userIds);
userChildIds.add(Integer.parseInt(userId));
PageInfoModel<DeviceVo> records = deviceService.getDeviceList(pageNo, pageSize, appName, userName, sn, status, userChildIds);
int total = records.getTotal(); int total = records.getTotal();
int pages = total / pageSize;//pages为总页数 int pages = total / pageSize;//pages为总页数
int mod = total % pageSize; int mod = total % pageSize;
......
package iot.sixiang.license.controller; package iot.sixiang.license.controller;
import cn.hutool.core.lang.Validator;
import com.acc.secret.util.RSAUtil; import com.acc.secret.util.RSAUtil;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
...@@ -28,6 +29,7 @@ import org.springframework.web.bind.annotation.PostMapping; ...@@ -28,6 +29,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
...@@ -50,9 +52,11 @@ public class LoginController { ...@@ -50,9 +52,11 @@ public class LoginController {
UserMapper userMapper; UserMapper userMapper;
@Resource @Resource
UserService userService; UserService userService;
//@Resource
//UserPermissionService userPermissionService;
@Value("${spring.mail.to}") // @Value("${spring.mail.to}")
private String account; // private String account;
@Value("${rsa.private_key}") @Value("${rsa.private_key}")
private String PRIVATE_KRY; private String PRIVATE_KRY;
@Value("${other.error_count.forget_pwd}") @Value("${other.error_count.forget_pwd}")
...@@ -62,78 +66,69 @@ public class LoginController { ...@@ -62,78 +66,69 @@ public class LoginController {
@Value("${other.code_exp_time}") @Value("${other.code_exp_time}")
private Integer codeExpTimeStr; private Integer codeExpTimeStr;
private static final String USER_NAME = "root";
private static final String OPERATION_CHECK = "check"; private static final String OPERATION_CHECK = "check";
private static final String OPERATION_RESET = "reset"; private static final String OPERATION_RESET = "reset";
/** /**
* 模拟用户登录 * 用户登录
*
* @return
*/ */
@ApiOperation(value = "登录接口", notes = "登录接口") @ApiOperation(value = "登录接口", notes = "登录接口")
@PostMapping("login") @PostMapping("login")
@MyLog(title = "登录", businessType = BusinessType.OTHER) @MyLog(title = "登录", businessType = BusinessType.OTHER)
public ResResult<LoginVo> login(@RequestBody LoginReqVo loginReqVo) { public ResResult login(@RequestBody LoginReqVo loginReqVo) {
String userName = loginReqVo.getUserName(); String userName = loginReqVo.getUserName();
String password = loginReqVo.getPassword();
String code = loginReqVo.getCode(); String code = loginReqVo.getCode();
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)) { // String password = loginReqVo.getPassword();
// if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)) {
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(code)) {
return ResResult.validate_failed().setMsgValue("参数不能为空"); return ResResult.validate_failed().setMsgValue("参数不能为空");
} }
User user = userMapper.getUserByUserName(USER_NAME); User user = userMapper.getUserByUserName(userName);
String name = USER_NAME; if (user == null) {
String pwd = user.getPassword(); return ResResult.validate_failed().setMsgValue("没有权限!");
LoginUser dbUser = new LoginUser(String.valueOf(user.getUserId()), user.getUserName(), user.getPassword());
if (name.equals(userName) && RSAUtil.getDecryptString(password, PRIVATE_KRY).equals(pwd)) {
// 登录错误次数
Integer errCnt = UserUtils.getErrCnt(userName);
Date countFreezeDate = UserUtils.getCountFreezeDate(userName);
Date curDate = new Date();
if (errCnt != null && errCnt >= 3 && countFreezeDate != null && curDate.before(countFreezeDate)) {
return ResResult.failed().setMsgValue("用户名或密码错误次数达到三次,请三分钟后再重试");
} else {
Date curCodeDate = new Date();
if (code.equals(UserUtils.getEmailCode(account)) && curCodeDate.before(UserUtils.getEmailCodeExpTime(account))) {
//if (code.equals("123456")) {
String token = JwtUtil.createToken(dbUser);
LoginVo loginVo = new LoginVo();
loginVo.setAuthorization(token);
loginVo.setUpdateTime(user.getUpdateTime());
UserUtils.setToken(dbUser.getUserId(), token);
UserUtils.setTokenExp(dbUser.getUserId(), JwtUtil.getTokenExp());
UserUtils.removeErrCnt(userName);
UserUtils.removeCountFreezeDate(userName);
UserUtils.removeEmailCode(account);
UserUtils.removeEmailCodeExpTime(account);
log.info("登录成功!生成token!");
return ResResult.success().goRecord(loginVo);
} else {
return ResResult.failed().setMsgValue("验证码错误或已过期");
}
}
} }
LoginUser dbUser = new LoginUser(String.valueOf(user.getUserId()), user.getUserName(), user.getPassword());
// if (RSAUtil.getDecryptString(password, PRIVATE_KRY).equals(pwd)) {
// 登录错误次数
Integer errCnt = UserUtils.getErrCnt(userName); Integer errCnt = UserUtils.getErrCnt(userName);
if (errCnt == null) { Date countFreezeDate = UserUtils.getCountFreezeDate(userName);
UserUtils.setErrCnt(userName, 1); Date curDate = new Date();
if (errCnt != null && errCnt >= 3 && countFreezeDate != null && curDate.before(countFreezeDate)) {
return ResResult.failed().setMsgValue("用户名或密码错误次数达到三次,请三分钟后再重试");
} else { } else {
if (errCnt == 1) { Date curCodeDate = new Date();
UserUtils.setErrCnt(userName, ++errCnt); if (code.equals(UserUtils.getEmailCode(userName)) && curCodeDate.before(UserUtils.getEmailCodeExpTime(userName))) {
} else if (errCnt == 2) { //if (code.equals("123456")) {
UserUtils.setErrCnt(userName, ++errCnt); String token = JwtUtil.createToken(dbUser);
Date freezeDate = new Date(System.currentTimeMillis() + 3 * 60 * 1000); LoginVo loginVo = new LoginVo();
UserUtils.setCountFreezeDate(userName, freezeDate); loginVo.setAuthorization(token);
loginVo.setUpdateTime(user.getUpdateTime());
UserUtils.setToken(dbUser.getUserId(), token);
UserUtils.setTokenExp(dbUser.getUserId(), JwtUtil.getTokenExp());
UserUtils.removeErrCnt(userName);
UserUtils.removeCountFreezeDate(userName);
UserUtils.removeEmailCode(userName);
UserUtils.removeEmailCodeExpTime(userName);
log.info("登录成功!生成token!");
return ResResult.success().goRecord(loginVo);
} else { } else {
Date countFreezeDate = UserUtils.getCountFreezeDate(userName); if (errCnt == null || errCnt == 3) {
Date curDate = new Date();
if (curDate.before(countFreezeDate)) {
return ResResult.failed().setMsgValue("用户名或密码错误次数达到三次,请三分钟后再重试");
} else {
UserUtils.setErrCnt(userName, 1); UserUtils.setErrCnt(userName, 1);
Date freezeDate = new Date(System.currentTimeMillis() + 3 * 60 * 1000); } else {
UserUtils.setCountFreezeDate(userName, freezeDate); if (errCnt == 1) {
UserUtils.setErrCnt(userName, ++errCnt);
}
if (errCnt == 2) {
UserUtils.setErrCnt(userName, ++errCnt);
Date freezeDate = new Date(System.currentTimeMillis() + 3 * 60 * 1000);
UserUtils.setCountFreezeDate(userName, freezeDate);
}
} }
return ResResult.failed().setMsgValue("验证码错误或已过期");
} }
} }
return ResResult.failed().setMsgValue("用户名或密码错误");
} }
//public static void main(String[] args) { //public static void main(String[] args) {
...@@ -160,7 +155,10 @@ public class LoginController { ...@@ -160,7 +155,10 @@ public class LoginController {
@ApiOperation(value = "发送验证码", notes = "发送验证码到邮箱") @ApiOperation(value = "发送验证码", notes = "发送验证码到邮箱")
@GetMapping("send_code") @GetMapping("send_code")
public BaseResult sendCode() { public BaseResult sendCode(@RequestParam("account") String account) {
if (StringUtils.isEmpty(account) || !Validator.isEmail(account)) {
return BaseResult.validate_failed().setMsgValue("请输入正确的邮箱账号");
}
Date emailCodeExpTime = UserUtils.getEmailCodeExpTime(account); Date emailCodeExpTime = UserUtils.getEmailCodeExpTime(account);
if (emailCodeExpTime != null && emailCodeExpTime.after(new Date())) { if (emailCodeExpTime != null && emailCodeExpTime.after(new Date())) {
return BaseResult.failed().setMsgValue("验证码还在有效期内"); return BaseResult.failed().setMsgValue("验证码还在有效期内");
...@@ -176,7 +174,7 @@ public class LoginController { ...@@ -176,7 +174,7 @@ public class LoginController {
@ApiOperation(value = "发送修改密码验证码", notes = "发送修改密码验证码到邮箱") @ApiOperation(value = "发送修改密码验证码", notes = "发送修改密码验证码到邮箱")
@GetMapping("send_code/change_pwd") @GetMapping("send_code/change_pwd")
public BaseResult sendChangePwdCode() { public BaseResult sendChangePwdCode(@RequestParam("account") String account) {
Date emailCodeExpTime = UserUtils.getEmailCodeExpTime(account + OPERATION_CHECK); Date emailCodeExpTime = UserUtils.getEmailCodeExpTime(account + OPERATION_CHECK);
if (emailCodeExpTime != null && emailCodeExpTime.after(new Date())) { if (emailCodeExpTime != null && emailCodeExpTime.after(new Date())) {
return BaseResult.failed().setMsgValue("验证码还在有效期内"); return BaseResult.failed().setMsgValue("验证码还在有效期内");
...@@ -194,6 +192,10 @@ public class LoginController { ...@@ -194,6 +192,10 @@ public class LoginController {
@PostMapping("check_code") @PostMapping("check_code")
public BaseResult checkCode(@RequestBody CheckCodeDto checkCodeDto) { public BaseResult checkCode(@RequestBody CheckCodeDto checkCodeDto) {
String code = checkCodeDto.getCode(); String code = checkCodeDto.getCode();
String account = checkCodeDto.getAccount();
if (StringUtils.isEmpty(account) || StringUtils.isEmpty(code)) {
return BaseResult.validate_failed();
}
String emailCode = UserUtils.getEmailCode(account + OPERATION_CHECK); String emailCode = UserUtils.getEmailCode(account + OPERATION_CHECK);
String codeFreezeTimeStr = UserUtils.getCodeFreezeTimeMap(account + OPERATION_CHECK); String codeFreezeTimeStr = UserUtils.getCodeFreezeTimeMap(account + OPERATION_CHECK);
// codeFreezeTimeStr不为空且冻结时间是今天直接报错,不是今天的话清空数据 // codeFreezeTimeStr不为空且冻结时间是今天直接报错,不是今天的话清空数据
...@@ -238,6 +240,10 @@ public class LoginController { ...@@ -238,6 +240,10 @@ public class LoginController {
@PostMapping("reset_pwd") @PostMapping("reset_pwd")
@MyLog(title = "重置密码", businessType = BusinessType.UPDATE) @MyLog(title = "重置密码", businessType = BusinessType.UPDATE)
public BaseResult resetPwd(@RequestBody UserResetPwdVo userResetPwdVo) { public BaseResult resetPwd(@RequestBody UserResetPwdVo userResetPwdVo) {
String account = userResetPwdVo.getAccount();
if (StringUtils.isEmpty(account)) {
return BaseResult.validate_failed();
}
String errCntTimeMap = UserUtils.getErrCntTimeMap(account + OPERATION_RESET); String errCntTimeMap = UserUtils.getErrCntTimeMap(account + OPERATION_RESET);
if (!StringUtils.isEmpty(errCntTimeMap)) { if (!StringUtils.isEmpty(errCntTimeMap)) {
if (errCntTimeMap.equals(CommonUtil.getCurDateStr())) { if (errCntTimeMap.equals(CommonUtil.getCurDateStr())) {
...@@ -256,21 +262,24 @@ public class LoginController { ...@@ -256,21 +262,24 @@ public class LoginController {
if (errCnt == null) { if (errCnt == null) {
errCnt = 0; errCnt = 0;
} }
User user = userService.getUserByName(USER_NAME); User user = userService.getUserByName(account);
if (user == null) {
return BaseResult.failed().setMsgValue("没有权限!");
}
if (newPassWord.length() < 8) { if (newPassWord.length() < 8) {
computeResetPwdErrCnt(errCnt); computeResetPwdErrCnt(errCnt, account);
return BaseResult.failed().setMsgValue("密码不得小于8位"); return BaseResult.failed().setMsgValue("密码不得小于8位");
} }
if (CommonUtil.verifyPasswordContainAccount(newPassWord, user.getUserName())) { if (CommonUtil.verifyPasswordContainAccount(newPassWord, user.getUserName())) {
computeResetPwdErrCnt(errCnt); computeResetPwdErrCnt(errCnt, account);
return BaseResult.failed().setMsgValue("密码中不得包含用户名的完整字符串、大小写变位或形似变换的字符串"); return BaseResult.failed().setMsgValue("密码中不得包含用户名的完整字符串、大小写变位或形似变换的字符串");
} }
if (CommonUtil.isKeyBoardContinuousChar(newPassWord)) { if (CommonUtil.isKeyBoardContinuousChar(newPassWord)) {
computeResetPwdErrCnt(errCnt); computeResetPwdErrCnt(errCnt, account);
return BaseResult.failed().setMsgValue("密码不得包含键盘连续字符4个及以上"); return BaseResult.failed().setMsgValue("密码不得包含键盘连续字符4个及以上");
} }
if (!CommonUtil.checkPassword(newPassWord)) { if (!CommonUtil.checkPassword(newPassWord)) {
computeResetPwdErrCnt(errCnt); computeResetPwdErrCnt(errCnt, account);
return BaseResult.failed().setMsgValue("至少由大写字母、小写字母、数字与特殊符号等4类中3类混合"); return BaseResult.failed().setMsgValue("至少由大写字母、小写字母、数字与特殊符号等4类中3类混合");
} }
user.setPassword(newPassWord); user.setPassword(newPassWord);
...@@ -282,7 +291,7 @@ public class LoginController { ...@@ -282,7 +291,7 @@ public class LoginController {
} }
} }
private void computeResetPwdErrCnt(int errCnt) { private void computeResetPwdErrCnt(int errCnt, String account) {
if (errCnt < forgetPwdMaxErrCount - 1) { if (errCnt < forgetPwdMaxErrCount - 1) {
UserUtils.setErrCnt(account + OPERATION_RESET, errCnt + 1); UserUtils.setErrCnt(account + OPERATION_RESET, errCnt + 1);
} else { } else {
...@@ -291,3 +300,4 @@ public class LoginController { ...@@ -291,3 +300,4 @@ public class LoginController {
} }
} }
...@@ -5,21 +5,25 @@ import io.swagger.annotations.ApiImplicitParam; ...@@ -5,21 +5,25 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import iot.sixiang.license.entity.PmsUseLog; import iot.sixiang.license.entity.PmsUseLog;
import iot.sixiang.license.entity.SysOperLog; import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.log.BusinessType; import iot.sixiang.license.log.BusinessType;
import iot.sixiang.license.log.MyLog; import iot.sixiang.license.log.MyLog;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.PageResult; import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.vo.DeviceVo;
import iot.sixiang.license.service.PmsUseService; import iot.sixiang.license.service.PmsUseService;
import iot.sixiang.license.service.SysOperLogService; import iot.sixiang.license.util.CommonUtil;
import iot.sixiang.license.util.TreeUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
...@@ -45,14 +49,30 @@ public class PmsUseLogController { ...@@ -45,14 +49,30 @@ public class PmsUseLogController {
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "pageNo", value = "当前在第几页", required = true, dataType = "int"), @ApiImplicitParam(name = "pageNo", value = "当前在第几页", required = true, dataType = "int"),
@ApiImplicitParam(name = "pageSize", value = "每页显示多少条", required = true, dataType = "int"), @ApiImplicitParam(name = "pageSize", value = "每页显示多少条", required = true, dataType = "int"),
@ApiImplicitParam(name = "startTime", value = "开始时间"),
@ApiImplicitParam(name = "endTime", value = "结束时间"),
@ApiImplicitParam(name = "sn", value = "设备编号"), @ApiImplicitParam(name = "sn", value = "设备编号"),
@ApiImplicitParam(name = "status", value = "状态 1:成功,0:失败", dataType = "int") @ApiImplicitParam(name = "status", value = "状态 1:成功,0:失败", dataType = "int")
}) })
public PageResult<PmsUseLog> getPmsUseLogList(@RequestParam(value = "pageNo", defaultValue = "0") int pageNo, public PageResult<PmsUseLog> getPmsUseLogList(@RequestParam(value = "pageNo", defaultValue = "0") int pageNo,
@RequestParam(value = "pageSize", defaultValue = "0") int pageSize, @RequestParam(value = "pageSize", defaultValue = "0") int pageSize,
@RequestParam(value = "startTime", required = false) String startTime,
@RequestParam(value = "endTime", required = false) String endTime,
@RequestParam(value = "sn", required = false) String sn, @RequestParam(value = "sn", required = false) String sn,
@RequestParam(value = "status", required = false) Integer status) { @RequestParam(value = "status", required = false) Integer status) throws ParseException {
PageInfoModel<PmsUseLog> records = pmsUseService.getPmsUseLogList(pageNo, pageSize, sn, status); String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
throw new IotLicenseException(403, "请重新登录");
}
List<Integer> userIds = new ArrayList<>();
List<Integer> userChildIds = TreeUtil.getUserChildIds(Integer.parseInt(userId), userIds);
userChildIds.add(Integer.parseInt(userId));
if (StringUtils.isEmpty(endTime)) {
endTime = CommonUtil.getDayByNum(1, CommonUtil.dateToString(new Date(), "yyyy-MM-dd"));
} else {
endTime = CommonUtil.getDayByNum(1, endTime);
}
PageInfoModel<PmsUseLog> records = pmsUseService.getPmsUseLogList(pageNo, pageSize, sn, status, startTime, endTime, userChildIds);
int total = records.getTotal(); int total = records.getTotal();
int pages = total / pageSize;//pages为总页数 int pages = total / pageSize;//pages为总页数
int mod = total % pageSize; int mod = total % pageSize;
......
package iot.sixiang.license.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import iot.sixiang.license.entity.ReportType;
import iot.sixiang.license.log.BusinessType;
import iot.sixiang.license.log.MyLog;
import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.ResResult;
import iot.sixiang.license.model.dto.ReportDTO;
import iot.sixiang.license.model.vo.ReportVO;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.service.ReportTypeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by m33
* Date 2023/2/1 9:52
* Description
*/
@RestController
@RequestMapping("/iot_license/report")
@Api(value = "安全报警模块", tags = {"安全报警模块"})
public class ReportController {
@Resource
ReportTypeService reportTypeService;
@Resource
ReportService reportService;
/**
* 查询所有报警类型
*
* @return
*/
@ApiOperation(value = "获取报警类型接口", notes = "用于获取报警类型")
@GetMapping("report_type/list")
@MyLog(title = "获取报警类型", businessType = BusinessType.SELECT)
public ResResult getReportTypeList() {
List<ReportType> reportTypes = reportTypeService.getReportTypeList();
return ResResult.success().goRecord(reportTypes);
}
@ApiOperation(value = "获取报警列表接口", notes = "用于获取报警列表")
@GetMapping("list")
@MyLog(title = "获取报警列表", optParam = "#{reportDTO.pageNo},#{reportDTO.pageSize},#{reportDTO.type},#{reportDTO.sn},#{reportDTO.startTime},#{reportDTO.endTime}", businessType = BusinessType.SELECT)
public PageResult<ReportVO> getReportList(ReportDTO reportDTO) {
return reportService.getReportList(reportDTO);
}
}
...@@ -10,12 +10,16 @@ import iot.sixiang.license.model.PageInfoModel; ...@@ -10,12 +10,16 @@ import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.PageResult; import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.vo.SysOperLogVo; import iot.sixiang.license.model.vo.SysOperLogVo;
import iot.sixiang.license.service.SysOperLogService; import iot.sixiang.license.service.SysOperLogService;
import iot.sixiang.license.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
...@@ -31,6 +35,7 @@ public class SysOperLogController { ...@@ -31,6 +35,7 @@ public class SysOperLogController {
/** /**
* 分页查询所有的oper_log * 分页查询所有的oper_log
*
* @param pageNo * @param pageNo
* @param pageSize * @param pageSize
* @return * @return
...@@ -39,17 +44,26 @@ public class SysOperLogController { ...@@ -39,17 +44,26 @@ public class SysOperLogController {
@GetMapping("operate/list") @GetMapping("operate/list")
@MyLog(title = "获取日志列表", businessType = BusinessType.SELECT) @MyLog(title = "获取日志列表", businessType = BusinessType.SELECT)
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "pageNo",value = "当前在第几页", required = true,dataType = "int"), @ApiImplicitParam(name = "pageNo", value = "当前在第几页", required = true, dataType = "int"),
@ApiImplicitParam(name = "pageSize",value = "每页显示多少条", required = true, dataType = "int") @ApiImplicitParam(name = "pageSize", value = "每页显示多少条", required = true, dataType = "int"),
@ApiImplicitParam(name = "startTime", value = "开始时间"),
@ApiImplicitParam(name = "endTime", value = "结束时间")
}) })
public PageResult<SysOperLogVo> getOperLogList(@RequestParam(value = "pageNo", defaultValue = "0") int pageNo, public PageResult<SysOperLogVo> getOperLogList(@RequestParam(value = "pageNo", defaultValue = "0") int pageNo,
@RequestParam(value = "pageSize",defaultValue = "0") int pageSize) { @RequestParam(value = "pageSize", defaultValue = "0") int pageSize,
PageInfoModel<SysOperLogVo> records = sysOperLogService.getOperLogList(pageNo,pageSize); @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
@RequestParam(value = "endTime", required = false, defaultValue = "") String endTime) throws ParseException {
if (StringUtils.isEmpty(endTime)) {
endTime = CommonUtil.getDayByNum(1, CommonUtil.dateToString(new Date(), "yyyy-MM-dd"));
} else {
endTime = CommonUtil.getDayByNum(1, endTime);
}
PageInfoModel<SysOperLogVo> records = sysOperLogService.getOperLogList(pageNo, pageSize, startTime, endTime);
int total = records.getTotal(); int total = records.getTotal();
int pages = total/pageSize;//pages为总页数 int pages = total / pageSize;//pages为总页数
int mod = total%pageSize; int mod = total % pageSize;
if(mod!=0){ if (mod != 0) {
pages = pages +1; pages = pages + 1;
} }
List<SysOperLogVo> result = records.getResult(); List<SysOperLogVo> result = records.getResult();
return new PageResult(200, "查找成功", pageNo, pages, total, result); return new PageResult(200, "查找成功", pageNo, pages, total, result);
......
package iot.sixiang.license.controller; package iot.sixiang.license.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.acc.secret.util.RSAUtil; import com.acc.secret.util.RSAUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
...@@ -10,17 +12,26 @@ import io.swagger.annotations.Api; ...@@ -10,17 +12,26 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import iot.sixiang.license.auth.AuthManager;
import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.entity.Permission;
import iot.sixiang.license.entity.User; import iot.sixiang.license.entity.User;
import iot.sixiang.license.entity.UserPermission;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils; import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.log.BusinessType; import iot.sixiang.license.log.BusinessType;
import iot.sixiang.license.log.MyLog; import iot.sixiang.license.log.MyLog;
import iot.sixiang.license.model.BaseResult; import iot.sixiang.license.model.BaseResult;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.PageResult; import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.vo.UserUpdatePwdVo; import iot.sixiang.license.model.ResResult;
import iot.sixiang.license.model.vo.UserVo; import iot.sixiang.license.model.dto.AssignUserPermissionDTO;
import iot.sixiang.license.service.UserService; import iot.sixiang.license.model.dto.UpdateNotifyDTO;
import iot.sixiang.license.model.vo.*;
import iot.sixiang.license.service.*;
import iot.sixiang.license.util.CommonUtil; import iot.sixiang.license.util.CommonUtil;
import iot.sixiang.license.util.EmailUtils;
import iot.sixiang.license.util.TreeUtil;
import iot.sixiang.license.xss.XssUtil; import iot.sixiang.license.xss.XssUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -29,6 +40,8 @@ import org.springframework.util.DigestUtils; ...@@ -29,6 +40,8 @@ import org.springframework.util.DigestUtils;
import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
...@@ -44,8 +57,23 @@ import java.util.List; ...@@ -44,8 +57,23 @@ import java.util.List;
@Api(value = "用户模块", tags = {"用户模块"}) @Api(value = "用户模块", tags = {"用户模块"})
public class UserController { public class UserController {
@Autowired @Resource
EmailUtils emailUtils;
@Resource
private UserService userService; private UserService userService;
@Resource
private PermissionService permissionService;
@Resource
private UserPermissionService userPermissionService;
@Resource
private ApplyService applyService;
@Resource
private DeviceService deviceService;
@Resource
private DeviceManager deviceManager;
@Resource
private AuthManager authManager;
@Value("${rsa.private_key}") @Value("${rsa.private_key}")
private String PRIVATE_KRY; private String PRIVATE_KRY;
@Value("${other.error_count.change_pwd}") @Value("${other.error_count.change_pwd}")
...@@ -62,24 +90,42 @@ public class UserController { ...@@ -62,24 +90,42 @@ public class UserController {
} }
/** /**
* 添加user * 邀请用户注册
* *
* @param jsonObject * @param jsonObject
* @return * @return
*/ */
@ApiOperation(value = "用户添加接口", notes = "用于添加用户") @ApiOperation(value = "邀请注册接口", notes = "用于邀请用户注册")
@PostMapping("add") @PostMapping("add")
@MyLog(title = "添加用户", optParam = "#{jsonObject}", businessType = BusinessType.INSERT) @MyLog(title = "邀请用户注册", optParam = "#{jsonObject}", businessType = BusinessType.INSERT)
@ApiOperationSupport(params = @DynamicParameters(name = "jsonObject", properties = { @ApiOperationSupport(params = @DynamicParameters(name = "jsonObject", properties = {
@DynamicParameter(name = "userName", value = "账户名", required = true, dataTypeClass = String.class), @DynamicParameter(name = "userName", value = "账户名", required = true, dataTypeClass = String.class),
@DynamicParameter(name = "company", value = "公司名", required = true, dataTypeClass = String.class) @DynamicParameter(name = "company", value = "公司名", required = true, dataTypeClass = String.class)
})) }))
public BaseResult addUser(@RequestBody JSONObject jsonObject) { public BaseResult addUser(@RequestBody JSONObject jsonObject) {
String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
return BaseResult.failed().setMsgValue("请重新登录");
}
String userName = (String) jsonObject.get("userName"); String userName = (String) jsonObject.get("userName");
String company = (String) jsonObject.get("company"); String company = (String) jsonObject.get("company");
if (!Validator.isEmail(userName)) {
throw new IotLicenseException(403, "请输入正确的邮箱账号");
}
String password = CommonUtil.genRandomNum(18); String password = CommonUtil.genRandomNum(18);
boolean res = userService.addUser(userName, company, password); User user = userService.getUserById(Integer.parseInt(userId));
List<UserPermission> userPermissions = userPermissionService.getPermissionById(user.getUserId());
if (!CommonUtil.checkPermission(userPermissions, 1)) {
throw new IotLicenseException(403, "您无邀请用户注册权限!");
}
int level = user.getLevel();
if (level >= 3 || level <= 0) {
return BaseResult.failed().setMsgValue("您的账号等级不支持邀请注册用户");
}
boolean res = userService.addUser(userName, company, password, user.getUserId(), ++level);
if (res) { if (res) {
String content = "注册成功!感谢您使用实名制身份验证云应用平台,请点击以下链接登录:http://web.license.srthinker.com/user#/login";
emailUtils.sendSimpleMail(userName, "感谢您使用实名制身份验证云应用平台", content);
return BaseResult.success(); return BaseResult.success();
} else { } else {
return BaseResult.failed(); return BaseResult.failed();
...@@ -89,16 +135,34 @@ public class UserController { ...@@ -89,16 +135,34 @@ public class UserController {
/** /**
* 删除user * 删除user
* *
* @param userId * @param userDeleteVO
* @return * @return
*/ */
@ApiOperation(value = "用户删除接口", notes = "删除用户") @ApiOperation(value = "用户删除接口", notes = "删除用户")
@PostMapping("delete") @PostMapping("delete")
@MyLog(title = "删除用户", optParam = "#{userId}", businessType = BusinessType.DELETE) @MyLog(title = "删除用户", optParam = "#{userId}", businessType = BusinessType.DELETE)
public BaseResult deleteUser(@RequestParam("userId") int userId) { public BaseResult deleteUser(@RequestBody UserDeleteVO userDeleteVO) {
String userId = XssUtil.checkXSS(userDeleteVO.getUserId());
userId = Integer.valueOf(XssUtil.checkXSS(String.valueOf(userId))); String curUserId = UserUtils.getLoginUserId();
boolean res = userService.deleteUser(userId); if (StringUtils.isEmpty(curUserId)) {
return BaseResult.failed().setMsgValue("请重新登录");
}
List<UserPermission> userPermissions = userPermissionService.getPermissionById(Integer.parseInt(curUserId));
if (!CommonUtil.checkPermission(userPermissions, 2)) {
throw new IotLicenseException(403, "您无删除用户权限!");
}
List<UserChildIdVO> childUser = userService.getChildUser(Integer.parseInt(userId));
if (!childUser.isEmpty()) {
throw new IotLicenseException(403, "该账户存在子账号,请先删除所有子账号!");
}
deviceService.deleteByUserId(Integer.parseInt(userId));
applyService.deleteByUserId(Integer.parseInt(userId));
boolean res = userService.deleteUser(Integer.parseInt(userId));
userPermissionService.deleteUserPermission(Integer.parseInt(userId));
deviceManager.initDevices();
authManager.initApps();
UserUtils.removeToken(userId);
UserUtils.removeTokenExp(userId);
if (res) { if (res) {
return BaseResult.success(); return BaseResult.success();
} else { } else {
...@@ -196,6 +260,31 @@ public class UserController { ...@@ -196,6 +260,31 @@ public class UserController {
} }
} }
/**
* 查询用户
*
* @return
*/
@ApiOperation(value = "获取用户信息接口", notes = "获取用户信息")
@GetMapping("get")
@MyLog(title = "获取用户信息", businessType = BusinessType.SELECT)
public ResResult<UserDetailVO> getUserPermissionList() {
String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
return ResResult.failed().setMsgValue("请重新登录");
}
User user = userService.getUserById(Integer.parseInt(userId));
if (user == null) {
return ResResult.failed();
} else {
List<UserPermission> permissions = userPermissionService.getPermissionById(user.getUserId());
UserDetailVO userDetailVO = new UserDetailVO();
BeanUtil.copyProperties(user, userDetailVO);
userDetailVO.setPermissionList(permissions);
return ResResult.success().goRecord(userDetailVO);
}
}
/** /**
* 分页查询所有的user * 分页查询所有的user
...@@ -219,8 +308,18 @@ public class UserController { ...@@ -219,8 +308,18 @@ public class UserController {
@RequestParam(value = "company", required = false) String company) { @RequestParam(value = "company", required = false) String company) {
userName = XssUtil.checkXSS(userName); userName = XssUtil.checkXSS(userName);
company = XssUtil.checkXSS(company); company = XssUtil.checkXSS(company);
PageInfoModel<UserVo> records = userService.getUserList(pageNo, pageSize, userName, company); String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
throw new IotLicenseException(403, "请重新登录");
}
List<Integer> userIds = new ArrayList<>();
List<Integer> userChildIds = TreeUtil.getUserChildIds(Integer.parseInt(userId), userIds);
userChildIds.add(Integer.parseInt(userId));
PageInfoModel<UserVo> records = userService.getUserList(pageNo, pageSize, userName, company, userChildIds);
int total = records.getTotal(); int total = records.getTotal();
if (total <= 0) {
return new PageResult(200, "查找成功", pageNo, 0, 0, null);
}
int pages = total / pageSize;//pages为总页数 int pages = total / pageSize;//pages为总页数
int mod = total % pageSize; int mod = total % pageSize;
if (mod != 0) { if (mod != 0) {
...@@ -233,5 +332,55 @@ public class UserController { ...@@ -233,5 +332,55 @@ public class UserController {
} }
return new PageResult(200, "查找成功", pageNo, pages, total, result); return new PageResult(200, "查找成功", pageNo, pages, total, result);
} }
/**
* 查询所有权限类型
*
* @return
*/
@ApiOperation(value = "获取权限列表接口", notes = "用于获取权限列表")
@GetMapping("permission/list")
@MyLog(title = "获取权限列表", businessType = BusinessType.SELECT)
public ResResult<List<Permission>> getPermissionList() {
List<Permission> permissionList = permissionService.getPermissionList();
return ResResult.success().goRecord(permissionList);
}
/**
* 查询用户所拥有的权限
*
* @return
*/
@ApiOperation(value = "获取用户权限接口", notes = "获取用户权限")
@GetMapping("user_permission/get")
@MyLog(title = "获取用户权限", businessType = BusinessType.SELECT)
public ResResult<List<UserPermission>> getUserPermissionList(@RequestParam("userId") int userId) {
List<UserPermission> userPermissions = userPermissionService.getPermissionById(userId);
return ResResult.success().goRecord(userPermissions);
}
/**
* 为用户批量分配权限
*
* @param assignUserPermissionDTO
* @return
*/
@ApiOperation(value = "分配权限接口", notes = "用于为用户分配权限")
@PostMapping("user_permission/assign")
@MyLog(title = "分配权限", businessType = BusinessType.INSERT)
public BaseResult assignUserPermission(@RequestBody AssignUserPermissionDTO assignUserPermissionDTO) {
boolean res = userPermissionService.saveBatch(assignUserPermissionDTO);
if (res) {
return BaseResult.success();
} else {
return BaseResult.failed();
}
}
@ApiOperation(value = "修改通知人接口", notes = "修改通知人邮箱")
@PostMapping("update_notify")
public BaseResult updateNotify(@RequestBody UpdateNotifyDTO updateNotifyDTO) {
return userService.updateNotify(updateNotifyDTO);
}
} }
...@@ -54,7 +54,7 @@ public class DeviceManager { ...@@ -54,7 +54,7 @@ public class DeviceManager {
public void initDevices() { public void initDevices() {
allDevice = new HashMap<>(); allDevice = new HashMap<>();
PageInfoModel<DeviceVo> records = deviceService.getDeviceList(1, 10000, "", "", null, null); PageInfoModel<DeviceVo> records = deviceService.getDeviceList(1, 10000, null, "", "", null, null);
List<DeviceVo> deviceList = records.getResult(); List<DeviceVo> deviceList = records.getResult();
for (DeviceVo deviceVo : deviceList) { for (DeviceVo deviceVo : deviceList) {
...@@ -151,7 +151,7 @@ public class DeviceManager { ...@@ -151,7 +151,7 @@ public class DeviceManager {
} }
public PageInfoModel<DeviceDetailVo> getDeviceDetailList(int pageNo, int pageSize, String appName, String userName) { public PageInfoModel<DeviceDetailVo> getDeviceDetailList(int pageNo, int pageSize, String appName, String userName) {
PageInfoModel<DeviceVo> records = deviceService.getDeviceList(pageNo, pageSize, appName, userName, null, null); PageInfoModel<DeviceVo> records = deviceService.getDeviceList(pageNo, pageSize, null, appName, userName, null, null);
List<DeviceVo> deviceVos = records.getResult(); List<DeviceVo> deviceVos = records.getResult();
PageInfoModel<DeviceDetailVo> detailVoPageInfoModel = new PageInfoModel<>(); PageInfoModel<DeviceDetailVo> detailVoPageInfoModel = new PageInfoModel<>();
List<DeviceDetailVo> detailVos = new ArrayList<>(); List<DeviceDetailVo> detailVos = new ArrayList<>();
......
...@@ -9,14 +9,18 @@ import io.netty.channel.SimpleChannelInboundHandler; ...@@ -9,14 +9,18 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.auth.AuthManager; import iot.sixiang.license.auth.AuthManager;
import iot.sixiang.license.consts.Constant; import iot.sixiang.license.consts.Constant;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.event.CreateForwardClientEvent; import iot.sixiang.license.event.CreateForwardClientEvent;
import iot.sixiang.license.event.DeviceClientInactiveEvent; import iot.sixiang.license.event.DeviceClientInactiveEvent;
import iot.sixiang.license.event.DeviceClientLicenseEvent; import iot.sixiang.license.event.DeviceClientLicenseEvent;
import iot.sixiang.license.event.EventPublisher; import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.ForwardClientRequestEvent; import iot.sixiang.license.event.ForwardClientRequestEvent;
import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.SessionContext; import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.model.dto.ReportErrorMsgDTO; import iot.sixiang.license.model.dto.ReportErrorMsgDTO;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.service.PmsUseService; import iot.sixiang.license.service.PmsUseService;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.service.TerminalDeviceService; import iot.sixiang.license.service.TerminalDeviceService;
import iot.sixiang.license.third_lib.LibHelper; import iot.sixiang.license.third_lib.LibHelper;
import iot.sixiang.license.util.CommonUtil; import iot.sixiang.license.util.CommonUtil;
...@@ -28,6 +32,7 @@ import org.springframework.stereotype.Component; ...@@ -28,6 +32,7 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Date;
import java.util.List; import java.util.List;
@Component @Component
...@@ -41,6 +46,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -41,6 +46,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
private PmsUseService pmsUseService; private PmsUseService pmsUseService;
@Resource @Resource
TerminalDeviceService terminalDeviceService; TerminalDeviceService terminalDeviceService;
@Resource
ReportService reportService;
@Resource
UserMapper userMapper;
public DeviceServerHandler() { public DeviceServerHandler() {
super(); super();
...@@ -172,6 +181,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -172,6 +181,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
eventPublisher.publishEvent(event); eventPublisher.publishEvent(event);
} else { } else {
pmsUseService.createFailUseLog(sn, "鉴权失败"); pmsUseService.createFailUseLog(sn, "鉴权失败");
UserInfoVO user = userMapper.getUserBySn(sn);
Report report = Report.builder().category(0).type(6).sn(sn).userName(user.getUserName())
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
} }
return license; return license;
} }
......
package iot.sixiang.license.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/1/31 14:26
* Description
*/
@Data
public class Permission {
@ApiModelProperty("id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("权限说明")
private String description;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("逻辑删除标识 1:删除,0:未删除")
private Integer deleted;
}
package iot.sixiang.license.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/1/31 14:27
* Description
*/
@Data
@Builder
public class Report {
@ApiModelProperty("id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("报警大类 1:系统,0:设备")
private Integer category;
@ApiModelProperty("报警类型")
private Integer type;
@ApiModelProperty("设备编码(系统报警该值为空)")
private String sn;
@ApiModelProperty("报警说明")
private String description;
@ApiModelProperty("报警账户")
private String userName;
@ApiModelProperty("报警公司")
private String userCompany;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("逻辑删除标识 1:删除,0:未删除")
private Integer deleted;
}
package iot.sixiang.license.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/1/31 14:31
* Description
*/
@Data
public class ReportType {
@ApiModelProperty("id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("报警大类 1:系统,0:设备")
private Integer category;
@ApiModelProperty("报警说明")
private String description;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("逻辑删除标识 1:删除,0:未删除")
private Integer deleted;
}
...@@ -13,7 +13,7 @@ import java.util.Date; ...@@ -13,7 +13,7 @@ import java.util.Date;
/** /**
* <p> * <p>
* *
* </p> * </p>
* *
* @author m33 * @author m33
...@@ -40,6 +40,15 @@ public class User implements Serializable { ...@@ -40,6 +40,15 @@ public class User implements Serializable {
@ApiModelProperty("公司") @ApiModelProperty("公司")
private String company; private String company;
@ApiModelProperty("报警的邮箱,注册的时候用户名是邮箱则这里自动填那个邮箱,可以修改")
private String notify;
@ApiModelProperty("父账号标识(超管为空)")
private Integer parent;
@ApiModelProperty("账号等级(共有三级),超管一级")
private Integer level;
@ApiModelProperty("创建时间") @ApiModelProperty("创建时间")
private Date createTime; private Date createTime;
......
package iot.sixiang.license.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/1/31 14:41
* Description
*/
@Data
public class UserPermission {
@ApiModelProperty("id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("权限标识")
private Integer permission;
@ApiModelProperty("用户标识")
private Integer user;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("逻辑删除标识 1:删除,0:未删除")
private Integer deleted;
}
...@@ -2,16 +2,22 @@ package iot.sixiang.license.event; ...@@ -2,16 +2,22 @@ package iot.sixiang.license.event;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.SamInfo; import iot.sixiang.license.model.SamInfo;
import iot.sixiang.license.model.SamMonitor; import iot.sixiang.license.model.SamMonitor;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.operate.OperateManager; import iot.sixiang.license.operate.OperateManager;
import iot.sixiang.license.service.AlarmService; import iot.sixiang.license.service.AlarmService;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.util.CommonUtil; import iot.sixiang.license.util.CommonUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
...@@ -23,9 +29,12 @@ import java.util.List; ...@@ -23,9 +29,12 @@ import java.util.List;
public class OperateSAMStatusResponseEventHandler { public class OperateSAMStatusResponseEventHandler {
@Autowired @Autowired
public OperateManager operateManager; public OperateManager operateManager;
@Autowired @Autowired
private AlarmService alarmService; private AlarmService alarmService;
@Resource
UserMapper userMapper;
@Resource
ReportService reportService;
public OperateSAMStatusResponseEventHandler() { public OperateSAMStatusResponseEventHandler() {
} }
...@@ -51,6 +60,10 @@ public class OperateSAMStatusResponseEventHandler { ...@@ -51,6 +60,10 @@ public class OperateSAMStatusResponseEventHandler {
String title = "SAM故障"; String title = "SAM故障";
String content = "index为" + index + "的SAM发生故障"; String content = "index为" + index + "的SAM发生故障";
alarmService.addAlarm(typeId,title,content); alarmService.addAlarm(typeId,title,content);
UserInfoVO user = userMapper.getRootAccount();
Report report = Report.builder().category(1).type(1).userName(user.getUserName())
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
} }
} }
SamMonitor samMonitor = new SamMonitor(); SamMonitor samMonitor = new SamMonitor();
...@@ -63,6 +76,10 @@ public class OperateSAMStatusResponseEventHandler { ...@@ -63,6 +76,10 @@ public class OperateSAMStatusResponseEventHandler {
String title = "SAM不足"; String title = "SAM不足";
String content = "当前在线客户端已超过70%"; String content = "当前在线客户端已超过70%";
alarmService.addAlarm(typeId,title,content); alarmService.addAlarm(typeId,title,content);
UserInfoVO user = userMapper.getRootAccount();
Report report = Report.builder().category(1).type(2).userName(user.getUserName())
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
} }
} }
} }
...@@ -4,17 +4,23 @@ import io.netty.channel.ChannelFuture; ...@@ -4,17 +4,23 @@ import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager; import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.event.DeviceClientBeForcedOfflineEvent; import iot.sixiang.license.event.DeviceClientBeForcedOfflineEvent;
import iot.sixiang.license.event.DeviceClientLicenseEvent; import iot.sixiang.license.event.DeviceClientLicenseEvent;
import iot.sixiang.license.event.EventPublisher; import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.ForwardClientConnectEvent; import iot.sixiang.license.event.ForwardClientConnectEvent;
import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.SessionContext; import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.net.BaseConnectionListener; import iot.sixiang.license.net.BaseConnectionListener;
import iot.sixiang.license.operate.OperateManager; import iot.sixiang.license.operate.OperateManager;
import iot.sixiang.license.service.AlarmService; import iot.sixiang.license.service.AlarmService;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.util.SpringUtil; import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.Date;
@Slf4j @Slf4j
public class ForwardConnectionListener extends BaseConnectionListener { public class ForwardConnectionListener extends BaseConnectionListener {
private DeviceManager deviceManager; private DeviceManager deviceManager;
...@@ -34,7 +40,13 @@ public class ForwardConnectionListener extends BaseConnectionListener { ...@@ -34,7 +40,13 @@ public class ForwardConnectionListener extends BaseConnectionListener {
String title = "连接服器失败"; String title = "连接服器失败";
String content = "连接服务器:" + this.host + ":" + this.port + "失败"; String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId, title, content); alarmService.addAlarm(typeId, title, content);
UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
ReportService reportService = SpringUtil.getBean(ReportService.class);
UserInfoVO user = userMapper.getRootAccount();
Report report = Report.builder().category(1).type(3).userName(user.getUserName())
.description("桥接客户端,连接服务器" + this.host + ":" + this.port + "失败")
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
// forward client连接失败,则强制踢掉设备客户端 // forward client连接失败,则强制踢掉设备客户端
DeviceClientBeForcedOfflineEvent deviceClientBeForcedOfflineEvent = new DeviceClientBeForcedOfflineEvent(); DeviceClientBeForcedOfflineEvent deviceClientBeForcedOfflineEvent = new DeviceClientBeForcedOfflineEvent();
deviceClientBeForcedOfflineEvent.setSn(this.sn); deviceClientBeForcedOfflineEvent.setSn(this.sn);
......
...@@ -17,7 +17,7 @@ public class GlobalExceptionHandler { ...@@ -17,7 +17,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
@ResponseBody //为了返回数据 @ResponseBody //为了返回数据
public BaseResult error(Exception e){ public BaseResult error(Exception e){
log.error("出现自定义异常", e); log.error("出现全局异常", e);
return BaseResult.serverException(); return BaseResult.serverException();
} }
...@@ -25,7 +25,7 @@ public class GlobalExceptionHandler { ...@@ -25,7 +25,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(IotLicenseException.class) @ExceptionHandler(IotLicenseException.class)
@ResponseBody//为了返回数据 @ResponseBody//为了返回数据
public BaseResult error(IotLicenseException e){ public BaseResult error(IotLicenseException e){
log.error("出现自定义异常,{}" + e.getMsg()); log.error("出现自定义异常,{}", e.getMsg());
return BaseResult.failed().setMsgValue(e.getMsg()).setCodeValue(e.getCode()); return BaseResult.failed().setMsgValue(e.getMsg()).setCodeValue(e.getCode());
} }
} }
...@@ -97,6 +97,11 @@ public class JwtFilter implements Filter { ...@@ -97,6 +97,11 @@ public class JwtFilter implements Filter {
String userId = userData.get("userId").asString(); String userId = userData.get("userId").asString();
String userName = userData.get("userName").asString(); String userName = userData.get("userName").asString();
String password = ""; String password = "";
if (UserUtils.getToken(userId) == null) {
request.setAttribute("msg", "登录信息已失效,请重新登录");
request.getRequestDispatcher("/iot_license/fail").forward(request, response);
return;
}
if (!token.equals(UserUtils.getToken(userId))) { if (!token.equals(UserUtils.getToken(userId))) {
request.setAttribute("msg", "账户已在别处登录,请重新登录"); request.setAttribute("msg", "账户已在别处登录,请重新登录");
request.getRequestDispatcher("/iot_license/fail").forward(request, response); request.getRequestDispatcher("/iot_license/fail").forward(request, response);
......
...@@ -8,7 +8,7 @@ import java.util.List; ...@@ -8,7 +8,7 @@ import java.util.List;
/** /**
* <p> * <p>
* Mapper 接口 * Mapper 接口
* </p> * </p>
* *
* @author m33 * @author m33
...@@ -18,7 +18,9 @@ public interface ApplyMapper extends BaseMapper<Apply> { ...@@ -18,7 +18,9 @@ public interface ApplyMapper extends BaseMapper<Apply> {
boolean addApply(String appId, String appName, String appKey, int userId); boolean addApply(String appId, String appName, String appKey, int userId);
List<AppVo> getAppList(String appName); List<AppVo> getAppList(String appName, List<Integer> userChildIds);
Apply getApplyByAppName(String appName); Apply getApplyByAppName(String appName);
void deleteByUserId(Integer userId);
} }
...@@ -13,9 +13,11 @@ import java.util.List; ...@@ -13,9 +13,11 @@ import java.util.List;
* @since 2022-06-08 * @since 2022-06-08
*/ */
public interface DeviceMapper extends BaseMapper<Device> { public interface DeviceMapper extends BaseMapper<Device> {
List<DeviceVo> getDeviceList(String appName, String userName, String sn, Integer status); List<DeviceVo> getDeviceList(String appName, String userName, List<Integer> userChildIds, String sn, Integer status);
boolean addDevice(String sn, String appId); boolean addDevice(String sn, String appId);
int updateDeviceById(Device device); int updateDeviceById(Device device);
void deleteByUserId(int userId);
} }
package iot.sixiang.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import iot.sixiang.license.entity.Permission;
/**
* Created by m33
* Date 2023/1/31 14:48
* Description
*/
public interface PermissionMapper extends BaseMapper<Permission> {
}
...@@ -12,5 +12,5 @@ import java.util.List; ...@@ -12,5 +12,5 @@ import java.util.List;
* Description * Description
*/ */
public interface PmsUseLogMapper extends BaseMapper<PmsUseLog> { public interface PmsUseLogMapper extends BaseMapper<PmsUseLog> {
List<PmsUseLog> getPmsUseLogList(String sn, Integer status); List<PmsUseLog> getPmsUseLogList(String sn, Integer status, String startTime, String endTime, List<Integer> userChildIds);
} }
package iot.sixiang.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.model.vo.ReportVO;
import java.util.List;
/**
* Created by m33
* Date 2023/2/1 10:00
* Description
*/
public interface ReportMapper extends BaseMapper<Report> {
List<ReportVO> getReportList(Integer type, String sn, String startTime, String endTime, List<Integer> userChildIds);
}
package iot.sixiang.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import iot.sixiang.license.entity.ReportType;
/**
* Created by m33
* Date 2023/2/1 10:00
* Description
*/
public interface ReportTypeMapper extends BaseMapper<ReportType> {
}
...@@ -19,5 +19,5 @@ public interface SysOperLogMapper extends BaseMapper<SysOperLog> { ...@@ -19,5 +19,5 @@ public interface SysOperLogMapper extends BaseMapper<SysOperLog> {
boolean addOperlog(String title, Integer businessType, String uri, Integer status, String optParam, String errorMsg, Date operTime); boolean addOperlog(String title, Integer businessType, String uri, Integer status, String optParam, String errorMsg, Date operTime);
List<SysOperLogVo> getOperLogList(); List<SysOperLogVo> getOperLogList(String startTime, String endTime);
} }
...@@ -2,13 +2,15 @@ package iot.sixiang.license.mapper; ...@@ -2,13 +2,15 @@ package iot.sixiang.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import iot.sixiang.license.entity.User; import iot.sixiang.license.entity.User;
import iot.sixiang.license.model.vo.UserChildIdVO;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.model.vo.UserVo; import iot.sixiang.license.model.vo.UserVo;
import java.util.List; import java.util.List;
/** /**
* <p> * <p>
* Mapper 接口 * Mapper 接口
* </p> * </p>
* *
* @author m33 * @author m33
...@@ -19,13 +21,19 @@ public interface UserMapper extends BaseMapper<User> { ...@@ -19,13 +21,19 @@ public interface UserMapper extends BaseMapper<User> {
boolean deleteUser(int user); boolean deleteUser(int user);
boolean addUser(String userName, String company, String password); boolean addUser(String userName, String company, String password, String notify, int parent, int level);
boolean updateUser(int userId, String password); boolean updateUser(int userId, String password);
List<UserVo> getUserList( String userName, String company); List<UserVo> getUserList(String userName, String company, List<Integer> userIds);
User getUserByUserName(String userName); User getUserByUserName(String userName);
User getUserById(int userId); User getUserById(int userId);
List<UserChildIdVO> getChildUser(int userId);
UserInfoVO getRootAccount();
UserInfoVO getUserBySn(String sn);
} }
package iot.sixiang.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import iot.sixiang.license.entity.Permission;
import iot.sixiang.license.entity.UserPermission;
import java.util.List;
/**
* Created by m33
* Date 2023/1/31 14:48
* Description
*/
public interface UserPermissionMapper extends BaseMapper<UserPermission> {
List<UserPermission> getPermissionById(int userId);
int saveBatch(List<Integer> userPermissions, int userId);
void deleteUserPermission(int parseInt);
int delBatch(List<Integer> permissionDelList, Integer userId);
}
package iot.sixiang.license.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* Created by m33
* Date 2023/1/31 15:32
* Description
*/
@Data
public class AssignUserPermissionDTO {
@ApiModelProperty("权限列表")
List<Integer> permissions;
@ApiModelProperty("用户id")
Integer userId;
}
...@@ -10,6 +10,9 @@ import lombok.Data; ...@@ -10,6 +10,9 @@ import lombok.Data;
*/ */
@Data @Data
public class CheckCodeDto { public class CheckCodeDto {
@ApiModelProperty("验证码")
private String account;
@ApiModelProperty("验证码") @ApiModelProperty("验证码")
private String code; private String code;
} }
package iot.sixiang.license.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/2/1 13:57
* Description
*/
@Data
public class ReportDTO {
@ApiModelProperty("当前页")
private Integer pageNo;
@ApiModelProperty("每页条数")
private Integer pageSize;
@ApiModelProperty("报警事件类型")
private Integer type;
@ApiModelProperty("设备编码")
private String sn;
@ApiModelProperty("开始时间")
private String startTime;
@ApiModelProperty("结束时间")
private String endTime;
}
package iot.sixiang.license.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* Created by m33
* Date 2023/1/30 14:18
* Description
*/
@Data
public class UpdateNotifyDTO {
@ApiModelProperty("通知人邮箱")
private String notify;
}
...@@ -16,8 +16,8 @@ public class LoginReqVo { ...@@ -16,8 +16,8 @@ public class LoginReqVo {
@ApiModelProperty("用户名") @ApiModelProperty("用户名")
private String userName; private String userName;
@ApiModelProperty("密码") // @ApiModelProperty("密码")
private String password; // private String password;
@ApiModelProperty("验证码") @ApiModelProperty("验证码")
private String code; private String code;
......
package iot.sixiang.license.model.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import iot.sixiang.license.entity.Report;
import lombok.Data;
import java.util.Date;
/**
* Created by m33
* Date 2023/2/1 14:06
* Description
*/
@Data
public class ReportVO {
@ApiModelProperty("id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("报警大类 1:系统,0:设备")
private Integer category;
@ApiModelProperty("报警类型")
private Integer type;
@ApiModelProperty("设备编码(系统报警该值为空)")
private String sn;
@ApiModelProperty("报警说明")
private String description;
@ApiModelProperty("报警账户")
private String userName;
@ApiModelProperty("报警公司")
private String userCompany;
@ApiModelProperty("创建时间")
private Date createTime;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("逻辑删除标识 1:删除,0:未删除")
private Integer deleted;
@ApiModelProperty("报警事件")
private String reportTypeStr;
}
package iot.sixiang.license.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* Created by m33
* Date 2023/2/1 14:52
* Description
*/
@Data
public class UserChildIdVO {
@ApiModelProperty("用户Id")
private Integer userId;
@ApiModelProperty("父Id")
private Integer parent;
@ApiModelProperty("账号级别")
private Integer level;
}
package iot.sixiang.license.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* Created by m33
* Date 2023/1/31 17:51
* Description
*/
@Data
public class UserDeleteVO {
@ApiModelProperty("userId")
public String userId;
}
package iot.sixiang.license.model.vo;
import io.swagger.annotations.ApiModelProperty;
import iot.sixiang.license.entity.User;
import iot.sixiang.license.entity.UserPermission;
import lombok.Data;
import java.util.List;
/**
* Created by m33
* Date 2023/2/2 16:53
* Description
*/
@Data
public class UserDetailVO extends User {
@ApiModelProperty("用户权限列表")
private List<UserPermission> permissionList;
}
package iot.sixiang.license.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* Created by m33
* Date 2023/2/2 15:03
* Description
*/
@Data
public class UserInfoVO {
@ApiModelProperty("用户名")
private String userName;
@ApiModelProperty("公司名")
private String company;
@ApiModelProperty("通知邮箱")
private String notify;
}
...@@ -9,5 +9,6 @@ import lombok.Data; ...@@ -9,5 +9,6 @@ import lombok.Data;
*/ */
@Data @Data
public class UserResetPwdVo { public class UserResetPwdVo {
private String account;
private String password; private String password;
} }
...@@ -2,12 +2,22 @@ package iot.sixiang.license.net; ...@@ -2,12 +2,22 @@ package iot.sixiang.license.net;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import iot.sixiang.license.util.CommonUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.io.File;
@Slf4j @Slf4j
public class TcpServer { public class TcpServer {
private int port; private int port;
...@@ -18,7 +28,15 @@ public class TcpServer { ...@@ -18,7 +28,15 @@ public class TcpServer {
this.channelInitializer = channelInitializer; this.channelInitializer = channelInitializer;
} }
@SneakyThrows
public void start() { public void start() {
String topPath = CommonUtil.getServerParentDirectory() + File.separator + "/sec/";
SslContext sslContext = SslContextBuilder
.forServer(new File(topPath + "server.crt"), new File(topPath + "server.pkcs8.key"))
.trustManager(new File(topPath + "ca.crt"))
.clientAuth(ClientAuth.REQUIRE)
.build();
//创建两个线程组 bossGroup、workerGroup //创建两个线程组 bossGroup、workerGroup
EventLoopGroup bossGroup = new NioEventLoopGroup(4); EventLoopGroup bossGroup = new NioEventLoopGroup(4);
EventLoopGroup workerGroup = new NioEventLoopGroup(4); EventLoopGroup workerGroup = new NioEventLoopGroup(4);
...@@ -29,8 +47,17 @@ public class TcpServer { ...@@ -29,8 +47,17 @@ public class TcpServer {
b.group(bossGroup, workerGroup) b.group(bossGroup, workerGroup)
//设置服务端通道实现类型 //设置服务端通道实现类型
.channel(NioServerSocketChannel.class) .channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() { //配置具体的数据处理方式
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addFirst("ssl", sslContext.newHandler(socketChannel.alloc()));
//业务handler
pipeline.addLast(channelInitializer);
}
})
// .handler(new LoggingHandler(LogLevel.INFO)) // .handler(new LoggingHandler(LogLevel.INFO))
.childHandler(channelInitializer) //.childHandler(channelInitializer)
// 设置tcp缓冲区 // 设置tcp缓冲区
.option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_BACKLOG, 1024)
//设置保持活动连接状态 //设置保持活动连接状态
......
...@@ -3,13 +3,19 @@ package iot.sixiang.license.operate; ...@@ -3,13 +3,19 @@ package iot.sixiang.license.operate;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.event.EventPublisher; import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.OperateSAMStatusRequestEvent; import iot.sixiang.license.event.OperateSAMStatusRequestEvent;
import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.net.BaseConnectionListener; import iot.sixiang.license.net.BaseConnectionListener;
import iot.sixiang.license.service.AlarmService; import iot.sixiang.license.service.AlarmService;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.util.SpringUtil; import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.Date;
@Slf4j @Slf4j
public class OperateConnectionListener extends BaseConnectionListener { public class OperateConnectionListener extends BaseConnectionListener {
...@@ -25,6 +31,13 @@ public class OperateConnectionListener extends BaseConnectionListener { ...@@ -25,6 +31,13 @@ public class OperateConnectionListener extends BaseConnectionListener {
String title = "连接服器失败"; String title = "连接服器失败";
String content = "连接服务器:" + this.host + ":" + this.port + "失败"; String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId, title, content); alarmService.addAlarm(typeId, title, content);
UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
ReportService reportService = SpringUtil.getBean(ReportService.class);
UserInfoVO user = userMapper.getRootAccount();
Report report = Report.builder().category(1).type(3).userName(user.getUserName())
.description("运维客户端,连接服务器" + this.host + ":" + this.port + "失败")
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
} else { } else {
log.info("运维客户端,连接服务器成功:{},{}", this.host, this.port); log.info("运维客户端,连接服务器成功:{},{}", this.host, this.port);
//TODO 查询SAM状态 //TODO 查询SAM状态
......
...@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.extension.service.IService; ...@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.extension.service.IService;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.vo.AppVo; import iot.sixiang.license.model.vo.AppVo;
import java.util.List;
/** /**
* <p> * <p>
* 服务类 * 服务类
...@@ -17,5 +19,7 @@ public interface ApplyService extends IService<Apply> { ...@@ -17,5 +19,7 @@ public interface ApplyService extends IService<Apply> {
boolean addApply(String appName, String appKey, int userId); boolean addApply(String appName, String appKey, int userId);
PageInfoModel<AppVo> getAppList(int pageNo, int pageSize, String appName); PageInfoModel<AppVo> getAppList(int pageNo, int pageSize, String appName, List<Integer> userChildIds);
void deleteByUserId(Integer userId);
} }
...@@ -10,6 +10,8 @@ import iot.sixiang.license.model.dto.TerminalDevieBindDTO; ...@@ -10,6 +10,8 @@ import iot.sixiang.license.model.dto.TerminalDevieBindDTO;
import iot.sixiang.license.model.dto.TerminalDevieUnBindDTO; import iot.sixiang.license.model.dto.TerminalDevieUnBindDTO;
import iot.sixiang.license.model.vo.DeviceVo; import iot.sixiang.license.model.vo.DeviceVo;
import java.util.List;
/** /**
* 服务类 * 服务类
* *
...@@ -17,7 +19,7 @@ import iot.sixiang.license.model.vo.DeviceVo; ...@@ -17,7 +19,7 @@ import iot.sixiang.license.model.vo.DeviceVo;
* @since 2022-06-08 * @since 2022-06-08
*/ */
public interface DeviceService extends IService<Device> { public interface DeviceService extends IService<Device> {
PageInfoModel<DeviceVo> getDeviceList(int pageNo, int pageSize, String appName, String userName, String sn, Integer status); PageInfoModel<DeviceVo> getDeviceList(int pageNo, int pageSize, String appName, String userName, String sn, Integer status, List<Integer> userChildIds);
boolean addDevice(String appId, int count); boolean addDevice(String appId, int count);
...@@ -28,4 +30,6 @@ public interface DeviceService extends IService<Device> { ...@@ -28,4 +30,6 @@ public interface DeviceService extends IService<Device> {
ResResult getBindStatus(TerminalDevieUnBindDTO terminalDevieUnBindDTO); ResResult getBindStatus(TerminalDevieUnBindDTO terminalDevieUnBindDTO);
BaseResult platFormBind(PlatFormBindDTO platFormBindDTO); BaseResult platFormBind(PlatFormBindDTO platFormBindDTO);
void deleteByUserId(int userId);
} }
package iot.sixiang.license.service;
import iot.sixiang.license.entity.Permission;
import java.util.List;
/**
* Created by m33
* Date 2023/1/31 14:21
* Description
*/
public interface PermissionService {
List<Permission> getPermissionList();
}
...@@ -4,6 +4,8 @@ import iot.sixiang.license.entity.PmsUseLog; ...@@ -4,6 +4,8 @@ import iot.sixiang.license.entity.PmsUseLog;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.dto.ReportErrorMsgDTO; import iot.sixiang.license.model.dto.ReportErrorMsgDTO;
import java.util.List;
/** /**
* Created by M=54G * Created by M=54G
* Date 11/23/22 3:09 PM * Date 11/23/22 3:09 PM
...@@ -14,11 +16,13 @@ public interface PmsUseService { ...@@ -14,11 +16,13 @@ public interface PmsUseService {
void createFailUseLog(String sn, String message); void createFailUseLog(String sn, String message);
void success(int useLogId); void success(ReportErrorMsgDTO reportErrorMsgDTO);
PageInfoModel<PmsUseLog> getPmsUseLogList(int pageNo, int pageSize, String sn, Integer status); PageInfoModel<PmsUseLog> getPmsUseLogList(int pageNo, int pageSize, String sn, Integer status, String startTime, String endTime, List<Integer> userChildIds);
boolean reportErrorMsg(ReportErrorMsgDTO reportErrorMsgDTO); boolean reportErrorMsg(ReportErrorMsgDTO reportErrorMsgDTO);
boolean deletePmsUseLogById(Integer id); boolean deletePmsUseLogById(Integer id);
PmsUseLog getPmsUseLogById(Integer id);
} }
package iot.sixiang.license.service;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.model.BaseResult;
import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.dto.ReportDTO;
import iot.sixiang.license.model.vo.ReportVO;
/**
* Created by M=54G
* Date 11/23/22 3:09 PM
* Description
*/
public interface ReportService {
PageResult<ReportVO> getReportList(ReportDTO reportDTO);
void reportToEmail(Report report, String notify);
}
package iot.sixiang.license.service;
import iot.sixiang.license.entity.PmsUseLog;
import iot.sixiang.license.entity.ReportType;
import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.dto.ReportErrorMsgDTO;
import java.util.List;
/**
* Created by M=54G
* Date 11/23/22 3:09 PM
* Description
*/
public interface ReportTypeService {
List<ReportType> getReportTypeList();
}
...@@ -18,5 +18,5 @@ import java.util.Date; ...@@ -18,5 +18,5 @@ import java.util.Date;
public interface SysOperLogService extends IService<SysOperLog> { public interface SysOperLogService extends IService<SysOperLog> {
boolean addOperlog(String title, Integer businessType, String uri, Integer status, String optParam, String errorMsg, Date operTime); boolean addOperlog(String title, Integer businessType, String uri, Integer status, String optParam, String errorMsg, Date operTime);
PageInfoModel<SysOperLogVo> getOperLogList(int pageNo, int pageSize); PageInfoModel<SysOperLogVo> getOperLogList(int pageNo, int pageSize, String startTime, String endTime);
} }
package iot.sixiang.license.service;
import iot.sixiang.license.entity.Permission;
import iot.sixiang.license.entity.UserPermission;
import iot.sixiang.license.model.dto.AssignUserPermissionDTO;
import java.util.List;
/**
* Created by m33
* Date 2023/1/31 14:21
* Description
*/
public interface UserPermissionService {
List<UserPermission> getPermissionById(int userId);
boolean saveBatch(AssignUserPermissionDTO assignUserPermissionDTO);
void deleteUserPermission(int parseInt);
}
package iot.sixiang.license.service; package iot.sixiang.license.service;
import iot.sixiang.license.entity.User; import iot.sixiang.license.entity.User;
import iot.sixiang.license.model.BaseResult;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.dto.UpdateNotifyDTO;
import iot.sixiang.license.model.vo.UserChildIdVO;
import iot.sixiang.license.model.vo.UserVo; import iot.sixiang.license.model.vo.UserVo;
import java.util.List;
/** /**
* <p> * <p>
* 服务类 * 服务类
...@@ -16,13 +21,17 @@ public interface UserService { ...@@ -16,13 +21,17 @@ public interface UserService {
boolean deleteUser(int userIdVo); boolean deleteUser(int userIdVo);
boolean addUser(String userName, String company, String password); boolean addUser(String userName, String company, String password, int parent, int level);
boolean updateUser(User user); boolean updateUser(User user);
PageInfoModel<UserVo> getUserList(int pageNo, int pageSize, String userName, String company); PageInfoModel<UserVo> getUserList(int pageNo, int pageSize, String userName, String company, List<Integer> userIds);
User getUserById(int userId); User getUserById(int userId);
User getUserByName(String root); User getUserByName(String root);
BaseResult updateNotify(UpdateNotifyDTO updateNotifyDTO);
List<UserChildIdVO> getChildUser(int userId);
} }
...@@ -22,7 +22,7 @@ import java.util.stream.Collectors; ...@@ -22,7 +22,7 @@ import java.util.stream.Collectors;
/** /**
* <p> * <p>
* 服务实现类 * 服务实现类
* </p> * </p>
* *
* @author m33 * @author m33
...@@ -33,11 +33,12 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ...@@ -33,11 +33,12 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements
@Resource @Resource
ApplyMapper applyMapper; ApplyMapper applyMapper;
@Override @Override
public boolean addApply(String appName, String appKey, int userId) { public boolean addApply(String appName, String appKey, int userId) {
if(StringUtils.isEmpty(appName) || StringUtils.isEmpty(appKey) if (StringUtils.isEmpty(appName) || StringUtils.isEmpty(appKey)
|| userId == 0) { || userId == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
Apply res = applyMapper.getApplyByAppName(appName); Apply res = applyMapper.getApplyByAppName(appName);
if (res != null) { if (res != null) {
...@@ -54,11 +55,11 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ...@@ -54,11 +55,11 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements
} }
@Override @Override
public PageInfoModel<AppVo> getAppList(int pageNo, int pageSize, String appName) { public PageInfoModel<AppVo> getAppList(int pageNo, int pageSize, String appName, List<Integer> userChildIds) {
if(pageNo == 0 || pageSize == 0) { if (pageNo == 0 || pageSize == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
List<AppVo> records = applyMapper.getAppList(appName); List<AppVo> records = applyMapper.getAppList(appName, userChildIds);
records = records.stream().sorted(Comparator.comparing(AppVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList()); records = records.stream().sorted(Comparator.comparing(AppVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList());
List<AppVo> result = new ArrayList<>(); List<AppVo> result = new ArrayList<>();
int begin = (pageNo - 1) * pageSize; int begin = (pageNo - 1) * pageSize;
...@@ -70,4 +71,9 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ...@@ -70,4 +71,9 @@ public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements
objectPageInfoModel.setResult(result); objectPageInfoModel.setResult(result);
return objectPageInfoModel; return objectPageInfoModel;
} }
@Override
public void deleteByUserId(Integer userId) {
applyMapper.deleteByUserId(userId);
}
} }
...@@ -40,11 +40,11 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme ...@@ -40,11 +40,11 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
private DeviceMapper deviceMapper; private DeviceMapper deviceMapper;
@Override @Override
public PageInfoModel<DeviceVo> getDeviceList(int pageNo, int pageSize, String appName, String userName, String sn, Integer status) { public PageInfoModel<DeviceVo> getDeviceList(int pageNo, int pageSize, String appName, String userName, String sn, Integer status, List<Integer> userChildIds) {
if (pageNo == 0 || pageSize == 0) { if (pageNo == 0 || pageSize == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
List<DeviceVo> deviceTypes = deviceMapper.getDeviceList(appName, userName, sn, status); List<DeviceVo> deviceTypes = deviceMapper.getDeviceList(appName, userName, userChildIds, sn, status);
deviceTypes = deviceTypes.stream().sorted(Comparator.comparing(DeviceVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList()); deviceTypes = deviceTypes.stream().sorted(Comparator.comparing(DeviceVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList());
List<DeviceVo> result = new ArrayList<>(); List<DeviceVo> result = new ArrayList<>();
int begin = (pageNo - 1) * pageSize; int begin = (pageNo - 1) * pageSize;
...@@ -156,7 +156,15 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme ...@@ -156,7 +156,15 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
if (deviceId.equals(device.getDeviceId())) { if (deviceId.equals(device.getDeviceId())) {
return BaseResult.success(); return BaseResult.success();
} else { } else {
return BaseResult.failed().setMsgValue("设备sn已被绑定"); return BaseResult.failed().setMsgValue("设备编码已被绑定");
}
}
LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(Device::getSn, sn).last("limit 1");
Device device1 = deviceMapper.selectOne(lambdaQueryWrapper);
if (device1 != null) {
if (!deviceId.equals(device1.getDeviceId())) {
return BaseResult.failed().setMsgValue("SN已存在");
} }
} }
LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
...@@ -180,4 +188,9 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme ...@@ -180,4 +188,9 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
return BaseResult.failed(); return BaseResult.failed();
} }
} }
@Override
public void deleteByUserId(int userId) {
deviceMapper.deleteByUserId(userId);
}
} }
package iot.sixiang.license.service.impl;
import iot.sixiang.license.entity.Permission;
import iot.sixiang.license.mapper.PermissionMapper;
import iot.sixiang.license.service.PermissionService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by m33
* Date 2023/1/31 14:21
* Description
*/
@Service
public class PermissionServiceImpl implements PermissionService {
@Resource
PermissionMapper permissionMapper;
@Override
public List<Permission> getPermissionList() {
return permissionMapper.selectList(null);
}
}
...@@ -7,6 +7,8 @@ import iot.sixiang.license.mapper.PmsUseLogMapper; ...@@ -7,6 +7,8 @@ import iot.sixiang.license.mapper.PmsUseLogMapper;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.dto.ReportErrorMsgDTO; import iot.sixiang.license.model.dto.ReportErrorMsgDTO;
import iot.sixiang.license.service.PmsUseService; import iot.sixiang.license.service.PmsUseService;
import iot.sixiang.license.util.CommonUtil;
import org.owasp.esapi.ESAPI;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
...@@ -41,19 +43,33 @@ public class PmsUseServiceImpl implements PmsUseService { ...@@ -41,19 +43,33 @@ public class PmsUseServiceImpl implements PmsUseService {
} }
@Override @Override
public void success(int useLogId) { public void success(ReportErrorMsgDTO reportErrorMsgDTO) {
PmsUseLog pmsUseLog = new PmsUseLog(); PmsUseLog pmsUseLog = new PmsUseLog();
pmsUseLog.setId(useLogId); pmsUseLog.setId(reportErrorMsgDTO.getId());
pmsUseLog.setStatus(1); pmsUseLog.setStatus(1);
if (reportErrorMsgDTO.getErrorMsg() != null) {
String[] successMessage = reportErrorMsgDTO.getErrorMsg().split(",");
if (successMessage.length == 2) {
// 身份证脱敏
String idCardString = ESAPI.encoder().encodeForDN(CommonUtil.idCardEncrypt(successMessage[1]));
// 姓名脱敏
String nameString = ESAPI.encoder().encodeForDN(CommonUtil.nameDesensitization(CommonUtil.unicodeToStr(successMessage[0])));
pmsUseLog.setMessage(nameString + "," + idCardString);
} else {
pmsUseLog.setMessage(reportErrorMsgDTO.getErrorMsg());
}
}
pmsUseLogMapper.updateById(pmsUseLog); pmsUseLogMapper.updateById(pmsUseLog);
} }
@Override @Override
public PageInfoModel<PmsUseLog> getPmsUseLogList(int pageNo, int pageSize, String sn, Integer status) { public PageInfoModel<PmsUseLog> getPmsUseLogList(int pageNo, int pageSize, String sn, Integer status, String startTime, String endTime, List<Integer> userChildIds) {
if (pageNo == 0 || pageSize == 0) { if (pageNo == 0 || pageSize == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
List<PmsUseLog> pmsUseLogs = pmsUseLogMapper.getPmsUseLogList(sn, status); List<PmsUseLog> pmsUseLogs = pmsUseLogMapper.getPmsUseLogList(sn, status, startTime, endTime, userChildIds);
List<PmsUseLog> result = new ArrayList<>(); List<PmsUseLog> result = new ArrayList<>();
int begin = (pageNo - 1) * pageSize; int begin = (pageNo - 1) * pageSize;
if (begin >= 0 && pmsUseLogs.size() > 0) { if (begin >= 0 && pmsUseLogs.size() > 0) {
...@@ -91,6 +107,11 @@ public class PmsUseServiceImpl implements PmsUseService { ...@@ -91,6 +107,11 @@ public class PmsUseServiceImpl implements PmsUseService {
return res > 0; return res > 0;
} }
@Override
public PmsUseLog getPmsUseLogById(Integer id) {
return pmsUseLogMapper.selectById(id);
}
private PmsUseLog getPmsUseLog(String sn) { private PmsUseLog getPmsUseLog(String sn) {
PmsUseLog pmsUseLog = new PmsUseLog(); PmsUseLog pmsUseLog = new PmsUseLog();
Date date = new Date(); Date date = new Date();
......
package iot.sixiang.license.service.impl;
import cn.hutool.core.lang.Validator;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.entity.ReportType;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.mapper.ReportMapper;
import iot.sixiang.license.mapper.ReportTypeMapper;
import iot.sixiang.license.model.PageResult;
import iot.sixiang.license.model.dto.ReportDTO;
import iot.sixiang.license.model.vo.ReportVO;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.util.CommonUtil;
import iot.sixiang.license.util.EmailUtils;
import iot.sixiang.license.util.TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by m33
* Date 2023/2/1 9:59
* Description
*/
@Service
public class ReportServiceImpl implements ReportService {
@Resource
ReportMapper reportMapper;
@Resource
EmailUtils emailUtils;
@Resource
ReportTypeMapper reportTypeMapper;
@Override
public PageResult<ReportVO> getReportList(ReportDTO reportDTO) {
int pageNo = reportDTO.getPageNo();
int pageSize = reportDTO.getPageSize();
Integer type = reportDTO.getType();
String sn = reportDTO.getSn();
String startTime = reportDTO.getStartTime();
String endTime = reportDTO.getEndTime();
String userId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(userId)) {
throw new IotLicenseException(403, "请重新登录");
}
List<Integer> userIds = new ArrayList<>();
List<Integer> userChildIds = TreeUtil.getUserChildIds(Integer.parseInt(userId), userIds);
userChildIds.add(Integer.parseInt(userId));
List<ReportVO> reportList = reportMapper.getReportList(type, sn, startTime, endTime, userChildIds);
int total = reportList.size();
List<ReportVO> result;
int begin = (pageNo - 1) * pageSize;
if (begin >= 0 && total > 0) {
result = reportList.stream().skip(begin).limit(pageSize).collect(Collectors.toList());
} else {
return new PageResult<>(200, "查找成功", pageNo, 0, 0, null);
}
// pages为总页数
int pages = total / pageSize;
int mod = total % pageSize;
if (mod != 0) {
pages = pages + 1;
}
return new PageResult(200, "查找成功", pageNo, pages, total, result);
}
@Async("mailExecutor")
@Override
public void reportToEmail(Report report, String notify) {
if (!Validator.isEmail(notify)) {
throw new IotLicenseException(403, "报警失败,无效的邮箱账号");
}
reportMapper.insert(report);
Integer type = report.getType();
ReportType reportType = reportTypeMapper.selectById(type);
if (reportType == null) {
throw new IotLicenseException(403, "报警失败,无效的报警类型");
}
Integer category = report.getCategory();
String content = "";
if (category == 1) {
content = "【实名制身份验证云平台】系统报警!报警时间:" + CommonUtil.getSystemTime() + ",报警事件:" + reportType.getDescription()
+ ",报警用户:" + report.getUserName() + ",公司名称:" + report.getUserCompany() + ",请核实!";
} else if (category == 0) {
content = "【实名制身份验证云平台】设备报警!报警时间:" + CommonUtil.getSystemTime() + ",报警事件:" + reportType.getDescription()
+ ",设备SN:" + report.getSn() + ",报警用户:" + report.getUserName() + ",公司名称:" + report.getUserCompany()
+ ",请核实!";
} else {
throw new IotLicenseException(403, "报警失败,无效的报警大类");
}
emailUtils.sendSimpleMail(notify, "实名制身份验证云平台", content);
}
}
package iot.sixiang.license.service.impl;
import iot.sixiang.license.entity.ReportType;
import iot.sixiang.license.mapper.ReportTypeMapper;
import iot.sixiang.license.service.ReportTypeService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by m33
* Date 2023/2/1 9:59
* Description
*/
@Service
public class ReportTypeServiceImpl implements ReportTypeService {
@Resource
ReportTypeMapper reportTypeMapper;
@Override
public List<ReportType> getReportTypeList() {
return reportTypeMapper.selectList(null);
}
}
...@@ -45,11 +45,11 @@ public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOper ...@@ -45,11 +45,11 @@ public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOper
} }
@Override @Override
public PageInfoModel<SysOperLogVo> getOperLogList(int pageNo, int pageSize) { public PageInfoModel<SysOperLogVo> getOperLogList(int pageNo, int pageSize, String startTime, String endTime) {
if(pageNo == 0 || pageSize == 0) { if(pageNo == 0 || pageSize == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMsg());
} }
List<SysOperLogVo> records = sysOperLogMapper.getOperLogList(); List<SysOperLogVo> records = sysOperLogMapper.getOperLogList(startTime, endTime);
List<SysOperLogVo> result = new ArrayList<>(); List<SysOperLogVo> result = new ArrayList<>();
int begin = (pageNo - 1) * pageSize; int begin = (pageNo - 1) * pageSize;
if (begin >= 0 && records.size() > 0) { if (begin >= 0 && records.size() > 0) {
......
...@@ -2,14 +2,19 @@ package iot.sixiang.license.service.impl; ...@@ -2,14 +2,19 @@ package iot.sixiang.license.service.impl;
import iot.sixiang.license.auth.AuthManager; import iot.sixiang.license.auth.AuthManager;
import iot.sixiang.license.device.DeviceManager; import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.entity.PmsUseLog;
import iot.sixiang.license.entity.Report;
import iot.sixiang.license.handler.IotLicenseException; import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.JwtUtil; import iot.sixiang.license.jwt.JwtUtil;
import iot.sixiang.license.jwt.LoginUser; import iot.sixiang.license.jwt.LoginUser;
import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.BaseResult; import iot.sixiang.license.model.BaseResult;
import iot.sixiang.license.model.ResResult; import iot.sixiang.license.model.ResResult;
import iot.sixiang.license.model.dto.*; import iot.sixiang.license.model.dto.*;
import iot.sixiang.license.model.vo.UserInfoVO;
import iot.sixiang.license.service.DeviceService; import iot.sixiang.license.service.DeviceService;
import iot.sixiang.license.service.PmsUseService; import iot.sixiang.license.service.PmsUseService;
import iot.sixiang.license.service.ReportService;
import iot.sixiang.license.service.TerminalDeviceService; import iot.sixiang.license.service.TerminalDeviceService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -17,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -17,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Comparator; import java.util.Date;
import java.util.List; import java.util.List;
@Slf4j @Slf4j
...@@ -31,6 +36,10 @@ public class TerminalDeviceServiceImpl implements TerminalDeviceService { ...@@ -31,6 +36,10 @@ public class TerminalDeviceServiceImpl implements TerminalDeviceService {
private PmsUseService pmsUseService; private PmsUseService pmsUseService;
@Resource @Resource
private DeviceManager deviceManager; private DeviceManager deviceManager;
@Resource
UserMapper userMapper;
@Resource
ReportService reportService;
@Override @Override
public ResResult getToken(GetTerminalDeviceTokenDTO getTerminalDeviceTokenDTO) { public ResResult getToken(GetTerminalDeviceTokenDTO getTerminalDeviceTokenDTO) {
...@@ -69,10 +78,27 @@ public class TerminalDeviceServiceImpl implements TerminalDeviceService { ...@@ -69,10 +78,27 @@ public class TerminalDeviceServiceImpl implements TerminalDeviceService {
return BaseResult.validate_failed(); return BaseResult.validate_failed();
} }
if ("0".equals(reportErrorMsgDTO.getErrorCode())) { if ("0".equals(reportErrorMsgDTO.getErrorCode())) {
pmsUseService.success(reportErrorMsgDTO.getId()); pmsUseService.success(reportErrorMsgDTO);
} else if ("-1".equals(reportErrorMsgDTO.getErrorCode())) { } else if ("-1".equals(reportErrorMsgDTO.getErrorCode())) {
pmsUseService.deletePmsUseLogById(id); pmsUseService.deletePmsUseLogById(id);
} else { } else {
PmsUseLog pmsUseLog = pmsUseService.getPmsUseLogById(reportErrorMsgDTO.getId());
if (pmsUseLog == null || StringUtils.isEmpty(pmsUseLog.getSn())) {
throw new IotLicenseException(403, "添加报警信息失败:查无SN");
}
UserInfoVO user = userMapper.getUserBySn(pmsUseLog.getSn());
int code = Integer.parseInt(reportErrorMsgDTO.getErrorCode());
int type = 0;
if (code == 1) {
type = 5;
} else if (code == 2) {
type = 4;
} else if (code == 3) {
type = 7;
}
Report report = Report.builder().category(0).type(type).sn(pmsUseLog.getSn()).userName(user.getUserName())
.userCompany(user.getCompany()).createTime(new Date()).updateTime(new Date()).build();
reportService.reportToEmail(report, user.getNotify());
boolean res = pmsUseService.reportErrorMsg(reportErrorMsgDTO); boolean res = pmsUseService.reportErrorMsg(reportErrorMsgDTO);
if (!res) { if (!res) {
return BaseResult.failed(); return BaseResult.failed();
......
package iot.sixiang.license.service.impl;
import iot.sixiang.license.consts.ResultCode;
import iot.sixiang.license.entity.UserPermission;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.mapper.UserPermissionMapper;
import iot.sixiang.license.model.dto.AssignUserPermissionDTO;
import iot.sixiang.license.service.UserPermissionService;
import iot.sixiang.license.util.CommonUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by m33
* Date 2023/1/31 14:21
* Description
*/
@Service
public class UserPermissionServiceImpl implements UserPermissionService {
@Resource
UserPermissionMapper userPermissionMapper;
@Override
public List<UserPermission> getPermissionById(int userId) {
if (userId <= 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
}
return userPermissionMapper.getPermissionById(userId);
}
@Override
public boolean saveBatch(AssignUserPermissionDTO assignUserPermissionDTO) {
List<Integer> userPermissions = assignUserPermissionDTO.getPermissions();
Integer userId = assignUserPermissionDTO.getUserId();
if (userPermissions.isEmpty() || userId <= 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
}
List<UserPermission> permissionById = userPermissionMapper.getPermissionById(userId);
// 筛选出已有的权限
List<Integer> originPermissions = permissionById.stream().map(UserPermission::getPermission).collect(Collectors.toList());
// 新增权限处理,找出 userPermissions 中新增的权限并添加到用户权限表中
List<Integer> permissionAddList = CommonUtil.getDiffList(userPermissions, originPermissions);
int res = 0;
if (!permissionAddList.isEmpty()) {
res = userPermissionMapper.saveBatch(permissionAddList, userId);
}
// 删除权限处理,找出 originPermissions 中多出的权限并从用户权限表中删除
List<Integer> permissionDelList = CommonUtil.getDiffList(originPermissions, userPermissions);
if (!permissionDelList.isEmpty()) {
res += userPermissionMapper.delBatch(permissionDelList, userId);
}
return res >= 0;
}
@Override
public void deleteUserPermission(int parseInt) {
userPermissionMapper.deleteUserPermission(parseInt);
}
}
package iot.sixiang.license.service.impl; package iot.sixiang.license.service.impl;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import iot.sixiang.license.consts.ResultCode; import iot.sixiang.license.consts.ResultCode;
import iot.sixiang.license.entity.User; import iot.sixiang.license.entity.User;
import iot.sixiang.license.handler.IotLicenseException; import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.mapper.UserMapper; import iot.sixiang.license.mapper.UserMapper;
import iot.sixiang.license.model.BaseResult;
import iot.sixiang.license.model.PageInfoModel; import iot.sixiang.license.model.PageInfoModel;
import iot.sixiang.license.model.dto.UpdateNotifyDTO;
import iot.sixiang.license.model.vo.UserChildIdVO;
import iot.sixiang.license.model.vo.UserVo; import iot.sixiang.license.model.vo.UserVo;
import iot.sixiang.license.service.UserService; import iot.sixiang.license.service.UserService;
import iot.sixiang.license.util.CommonUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -35,12 +40,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us ...@@ -35,12 +40,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
UserMapper userMapper; UserMapper userMapper;
@Override @Override
public PageInfoModel<UserVo> getUserList(int pageNo, int pageSize, String userName, String company) { public PageInfoModel<UserVo> getUserList(int pageNo, int pageSize, String userName, String company, List<Integer> userIds) {
if (pageNo == 0 || pageSize == 0) { if (pageNo == 0 || pageSize == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
List<UserVo> records = userMapper.getUserList(userName, company); List<UserVo> records = userMapper.getUserList(userName, company, userIds);
records = records.stream().sorted(Comparator.comparing(UserVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList()); records = records.stream().sorted(Comparator.comparing(UserVo::getCreateTime, Comparator.reverseOrder())).sorted(Comparator.comparing(UserVo::getLevel)).collect(Collectors.toList());
List<UserVo> result = new ArrayList<>(); List<UserVo> result = new ArrayList<>();
int begin = (pageNo - 1) * pageSize; int begin = (pageNo - 1) * pageSize;
if (begin >= 0 && records.size() > 0) { if (begin >= 0 && records.size() > 0) {
...@@ -73,19 +78,55 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us ...@@ -73,19 +78,55 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
} }
@Override @Override
public boolean addUser(String userName, String company, String password) { public boolean addUser(String userName, String company, String password, int parent, int level) {
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(company) || !CommonUtil.regularMessage(userName)) { String notify;
if (Validator.isEmail(userName)) {
notify = userName;
} else {
throw new IotLicenseException(403, "请输入正确的邮箱账号");
}
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(company)) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
User res = userMapper.getUserByUserName(userName); User res = userMapper.getUserByUserName(userName);
if (res != null) { if (res != null) {
throw new IotLicenseException(403, "用户名已存在"); throw new IotLicenseException(403, "用户名已存在");
} }
return userMapper.addUser(userName, company, password); return userMapper.addUser(userName, company, password, notify, parent, level);
} }
@Override @Override
public boolean updateUser(User user) { public boolean updateUser(User user) {
return userMapper.updateUser(user.getUserId(), user.getPassword()); return userMapper.updateUser(user.getUserId(), user.getPassword());
} }
@Override
public BaseResult updateNotify(UpdateNotifyDTO updateNotifyDTO) {
String notify = updateNotifyDTO.getNotify();
String loginUserId = UserUtils.getLoginUserId();
if (StringUtils.isEmpty(notify) || !Validator.isEmail(notify)) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
}
if (StringUtils.isEmpty(loginUserId)) {
throw new IotLicenseException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMsg());
}
int userId = Integer.parseInt(loginUserId);
User user = new User();
user.setNotify(notify);
user.setUpdateTime(new Date());
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getUserId, userId);
int res = userMapper.update(user, wrapper);
if (res > 0) {
return BaseResult.success();
} else {
return BaseResult.failed();
}
}
@Override
public List<UserChildIdVO> getChildUser(int userId) {
return userMapper.getChildUser(userId);
}
} }
package iot.sixiang.license.util; package iot.sixiang.license.util;
import iot.sixiang.license.consts.Constant; import iot.sixiang.license.consts.Constant;
import iot.sixiang.license.entity.UserPermission;
import iot.sixiang.license.model.ResResult; import iot.sixiang.license.model.ResResult;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -11,16 +12,45 @@ import java.io.File; ...@@ -11,16 +12,45 @@ import java.io.File;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Slf4j @Slf4j
public class CommonUtil { public class CommonUtil {
/**
* 获取指定日期前或后几天
*
* @return
*/
public static String getDayByNum(int num, String dateStr) throws ParseException {
//获取指定当前日期的前三天时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, num);
date = calendar.getTime();
return format.format(date);
}
/**
* date 转 字符串
*
* @param date
* @param pattern
* @return
*/
public static String dateToString(Date date, String pattern) {
SimpleDateFormat ft = new SimpleDateFormat(pattern);
return ft.format(date);
}
/** /**
* 验证密码-是否包含用户名字符(密码应与用户名无相关性,密码中不得包含用户名的完整字符串、大小写变位或形似变换的字符串) * 验证密码-是否包含用户名字符(密码应与用户名无相关性,密码中不得包含用户名的完整字符串、大小写变位或形似变换的字符串)
*/ */
...@@ -100,11 +130,6 @@ public class CommonUtil { ...@@ -100,11 +130,6 @@ public class CommonUtil {
return result; return result;
} }
public static void main(String[] args) {
boolean b = checkPassword("1234qwe123");
System.out.println(b);
}
/** /**
* 密码验证 * 密码验证
* (至少由8位及以上大写字母、小写字母、数字与特殊符号等4类中3类混合) * (至少由8位及以上大写字母、小写字母、数字与特殊符号等4类中3类混合)
...@@ -234,7 +259,7 @@ public class CommonUtil { ...@@ -234,7 +259,7 @@ public class CommonUtil {
} }
public static String getServerParentDirectory() { public static String getServerParentDirectory() {
return new File(new ApplicationHome(Constant.class).getSource().getParentFile().getPath()).getParent() + File.separator + "lib"; return new File(new ApplicationHome(Constant.class).getSource().getParentFile().getPath()) + File.separator + "file";
} }
/** /**
...@@ -271,7 +296,7 @@ public class CommonUtil { ...@@ -271,7 +296,7 @@ public class CommonUtil {
return myName; return myName;
} }
//身份证前三后四脱敏 // 身份证前三后四脱敏
public static String idCardEncrypt(String idcard) { public static String idCardEncrypt(String idcard) {
if (idcard == null || idcard.length() == 0 || idcard.contains("*")) { if (idcard == null || idcard.length() == 0 || idcard.contains("*")) {
return idcard; return idcard;
...@@ -279,10 +304,11 @@ public class CommonUtil { ...@@ -279,10 +304,11 @@ public class CommonUtil {
if (StringUtils.isEmpty(idcard) || (idcard.length() < 8)) { if (StringUtils.isEmpty(idcard) || (idcard.length() < 8)) {
return idcard; return idcard;
} }
String res = StringUtils.overlay(idcard, "**************", 0, 14); String res = StringUtils.overlay(idcard, "***********", 3, 14);
return res; return res;
} }
public static String getCurDateStr() { public static String getCurDateStr() {
Date date = new Date(); Date date = new Date();
String pattern = "yyyy-MM-dd"; String pattern = "yyyy-MM-dd";
...@@ -315,4 +341,62 @@ public class CommonUtil { ...@@ -315,4 +341,62 @@ public class CommonUtil {
} }
return ""; return "";
} }
/**
* 检查是否有某个权限
*
* @param userPermissions
* @param permission
* @return
*/
public static boolean checkPermission(List<UserPermission> userPermissions, int permission) {
boolean res = false;
for (UserPermission userPermission : userPermissions) {
if (userPermission.getPermission() == permission) {
res = true;
break;
}
}
return res;
}
/**
* 差集计算
*
* @param A 集合A
* @param B 集合B
* @return 筛选出【集合A中存在且集合B中不存在】的元素集合
*/
public static <T> List<T> getDiffList(List<T> A, List<T> B) {
if (A == null) {
return Collections.emptyList();
}
if (B == null) {
return A;
}
return A.stream().filter(a -> {
if (a == null) {
return false;
}
return B.stream().noneMatch(b -> b != null && b.equals(a));
}
).collect(Collectors.toList());
}
/**
* UNICODE转字符串
*
* @param unicode
* @return
*/
public static String unicodeToStr(String unicode) {
StringBuilder sb = new StringBuilder();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
int index = Integer.parseInt(hex[i], 16);
sb.append((char) index);
}
return sb.toString();
}
} }
package iot.sixiang.license.util;
import iot.sixiang.license.model.vo.UserChildIdVO;
import iot.sixiang.license.service.UserService;
import java.util.List;
/**
* Created by m33
* Date 2023/2/1 14:49
* Description
*/
public class TreeUtil {
/**
* 获取所有子账号userId
*
* @param userId
* @param res
* @return
*/
public static List<Integer> getUserChildIds(int userId, List<Integer> res) {
UserService userService = SpringUtil.getBean(UserService.class);
List<UserChildIdVO> userChildIdVOS = userService.getChildUser(userId);
if (userChildIdVOS.isEmpty()) {
return res;
}
for (UserChildIdVO userChildIdVO : userChildIdVOS) {
if (userChildIdVO.getLevel() < 3) {
getUserChildIds(userChildIdVO.getUserId(), res);
}
res.add(userChildIdVO.getUserId());
}
return res;
}
}
...@@ -2,7 +2,7 @@ server: ...@@ -2,7 +2,7 @@ server:
port: 8868 port: 8868
logging: logging:
level: level:
root: debug root: info
spring: spring:
datasource: datasource:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
......
...@@ -32,7 +32,7 @@ server: ...@@ -32,7 +32,7 @@ server:
cros: cros:
# 需要设置访问白名单 # 需要设置访问白名单
cros_allowed_origins: http://192.168.1.88:8080, http://192.168.1.88:8081, http://localhost:8868, http://localhost:8080, http://192.168.1.54:8080 cros_allowed_origins: http://192.168.1.88:8080, http://192.168.1.88:8081, http://localhost:8868, http://localhost:8080, http://192.168.1.155:8080
cros_allowed_method: GET,POST cros_allowed_method: GET,POST
other: other:
......
...@@ -6,16 +6,28 @@ ...@@ -6,16 +6,28 @@
app.app_id, app.app_name, app.app_key, app.create_time, app.update_time, us.user_id, app.app_id, app.app_name, app.app_key, app.create_time, app.update_time, us.user_id,
COUNT(sn) AS deviceCount, us.user_name, us.company COUNT(sn) AS deviceCount, us.user_name, us.company
</sql> </sql>
<insert id="addApply" parameterType="iot.sixiang.license.entity.Apply"> <insert id="addApply" parameterType="iot.sixiang.license.entity.Apply">
insert into apply(app_id,app_name, app_key, user_id, create_time, update_time) values (#{appId}, #{appName}, #{appKey}, #{userId}, now(), now()) insert into apply(app_id,app_name, app_key, user_id, create_time, update_time) values (#{appId}, #{appName}, #{appKey}, #{userId}, now(), now())
</insert> </insert>
<delete id="deleteByUserId">
delete from `apply` where user_id = #{userId}
</delete>
<select id="getAppList" resultType="iot.sixiang.license.model.vo.AppVo"> <select id="getAppList" resultType="iot.sixiang.license.model.vo.AppVo">
SELECT <include refid="AppVoColumn"/> SELECT <include refid="AppVoColumn"/>
FROM apply AS app LEFT JOIN device AS de ON app.app_id = de.app_id FROM apply AS app LEFT JOIN device AS de ON app.app_id = de.app_id
LEFT JOIN user AS us ON us.user_id = app.user_id LEFT JOIN user AS us ON us.user_id = app.user_id
where 1=1 where 1=1
<if test="null != _parameter and '' != _parameter"> <if test="userChildIds != null">
and app_name like concat('%',#{_parameter},'%') AND us.user_id IN
<foreach collection="userChildIds" open="(" separator="," close=")" item="userId">
#{userId}
</foreach>
</if>
<if test="null != appName and '' != appName">
and app_name like concat('%',#{appName},'%')
</if> </if>
GROUP BY app.app_id GROUP BY app.app_id
</select> </select>
......
<?xml version="1.0" encoding="UTF-8"?> <?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"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="iot.sixiang.license.mapper.DeviceMapper"> <mapper namespace="iot.sixiang.license.mapper.DeviceMapper">
<delete id="deleteByUserId">
delete device from device,apply,`user` WHERE device.app_id = apply.app_id
and user.user_id = apply.user_id and user.user_id = #{userId}
</delete>
<select id="getDeviceList" resultType="iot.sixiang.license.model.vo.DeviceVo"> <select id="getDeviceList" resultType="iot.sixiang.license.model.vo.DeviceVo">
SELECT de.device_id, de.app_id, app_name,user_name,sn,sn_bind,de.status,de.create_time,de.update_time,de.device_id IN (select SELECT de.device_id, de.app_id, app_name,user_name,sn,sn_bind,de.status,de.create_time,de.update_time,de.device_id IN (select
...@@ -8,6 +12,12 @@ ...@@ -8,6 +12,12 @@
JOIN apply AS app ON de.app_id = app.app_id JOIN apply AS app ON de.app_id = app.app_id
JOIN `user` AS us ON us.user_id = app.user_id JOIN `user` AS us ON us.user_id = app.user_id
where 1=1 where 1=1
<if test="userChildIds != null">
AND us.user_id IN
<foreach collection="userChildIds" open="(" separator="," close=")" item="userId">
#{userId}
</foreach>
</if>
<if test="null != appName and '' != appName"> <if test="null != appName and '' != appName">
and app_name like concat('%',#{appName},'%') and app_name like concat('%',#{appName},'%')
</if> </if>
......
<?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="iot.sixiang.license.mapper.PermissionMapper">
</mapper>
\ No newline at end of file
...@@ -2,18 +2,33 @@ ...@@ -2,18 +2,33 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="iot.sixiang.license.mapper.PmsUseLogMapper"> <mapper namespace="iot.sixiang.license.mapper.PmsUseLogMapper">
<select id="getPmsUseLogList" resultType="iot.sixiang.license.entity.PmsUseLog"> <select id="getPmsUseLogList" resultType="iot.sixiang.license.entity.PmsUseLog">
SELECT * FROM pms_use_log SELECT * FROM `pms_use_log`
INNER JOIN device ON device.sn = pms_use_log.sn
INNER JOIN apply ON device.app_id = apply.app_id
INNER JOIN `user` ON `user`.user_id = apply.user_id
where 1=1 where 1=1
<if test="userChildIds != null">
AND user.user_id IN
<foreach collection="userChildIds" open="(" separator="," close=")" item="userId">
#{userId}
</foreach>
</if>
<if test="startTime != null and startTime != ''">
AND pms_use_log.create_time &gt; #{startTime}
</if>
<if test="endTime != null and endTime != ''">
AND pms_use_log.create_time &lt; #{endTime}
</if>
<if test="null != sn and '' != sn"> <if test="null != sn and '' != sn">
and sn like concat('%',#{sn},'%') and pms_use_log.sn like concat('%',#{sn},'%')
</if> </if>
<if test="null != status and status == 0"> <if test="null != status and status == 0">
and status = #{status} and pms_use_log.status = #{status}
</if> </if>
<if test="null != status and status == 1"> <if test="null != status and status == 1">
and (status = #{status} or status is null) and (pms_use_log.status = #{status} or pms_use_log.status is null)
</if> </if>
and deleted = 0 and pms_use_log.deleted = 0
order by create_time desc order by pms_use_log.create_time desc
</select> </select>
</mapper> </mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="iot.sixiang.license.mapper.ReportMapper">
<select id="getReportList" resultType="iot.sixiang.license.model.vo.ReportVO">
SELECT
report.*,
report_type.description
FROM
`report`
LEFT JOIN `user` ON user.user_name = report.user_name
LEFT JOIN report_type ON report.type = report_type.id
where 1=1
<if test="userChildIds != null">
AND user.user_id IN
<foreach collection="userChildIds" open="(" separator="," close=")" item="userId">
#{userId}
</foreach>
</if>
<if test="null != type">
AND report.type = #{type}
</if>
<if test="null != sn and '' != sn">
AND report.sn like concat('%',#{sn},'%')
</if>
<if test="startTime != null and startTime != ''">
AND report.create_time &gt; #{startTime}
</if>
<if test="endTime != null and endTime != ''">
AND report.create_time &lt; #{endTime}
</if>
AND report.deleted = 0
AND report_type.deleted = 0
ORDER BY report.create_time DESC
</select>
</mapper>
...@@ -6,6 +6,14 @@ ...@@ -6,6 +6,14 @@
</insert> </insert>
<select id="getOperLogList" resultType="iot.sixiang.license.model.vo.SysOperLogVo"> <select id="getOperLogList" resultType="iot.sixiang.license.model.vo.SysOperLogVo">
select id, title, business_type, uri, status, error_msg, oper_time from sys_oper_log order by oper_time desc select id, title, business_type, uri, status, error_msg, oper_time from sys_oper_log
where 1=1
<if test="startTime != null and startTime != ''">
AND oper_time &gt; #{startTime}
</if>
<if test="endTime != null and endTime != ''">
AND oper_time &lt; #{endTime}
</if>
order by oper_time desc
</select> </select>
</mapper> </mapper>
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
<mapper namespace="iot.sixiang.license.mapper.UserMapper"> <mapper namespace="iot.sixiang.license.mapper.UserMapper">
<insert id="addUser" parameterType="iot.sixiang.license.entity.User"> <insert id="addUser" parameterType="iot.sixiang.license.entity.User">
insert into user(user_name, company, password,create_time, update_time) values (#{userName},#{company}, #{password}, now(), now()) insert into user(user_name, company, password, notify, parent, `level`, create_time, update_time) values (#{userName},#{company}, #{password}, #{notify, jdbcType=VARCHAR}, #{parent}, #{level}, now(), now())
</insert> </insert>
<delete id="deleteUser" parameterType="iot.sixiang.license.entity.User"> <delete id="deleteUser" parameterType="iot.sixiang.license.entity.User">
...@@ -15,15 +15,22 @@ ...@@ -15,15 +15,22 @@
</update> </update>
<select id="getUserList" resultType="iot.sixiang.license.model.vo.UserVo"> <select id="getUserList" resultType="iot.sixiang.license.model.vo.UserVo">
SELECT user.user_id, user_name, password, company, user.create_time, user.update_time, SELECT user.user_id, user_name, password, company, user.level, user.create_time, user.update_time,
COUNT(device.`device_id`) totalDevice, COUNT(device.`device_id`) totalDevice,
COUNT(if(device.device_id is NOT NULL, if (device.`status` = 0 or device.`status` is NULL, 1, NULL), NULL)) unUseDevice, COUNT(if(device.device_id is NOT NULL, if (device.`status` = 0 or device.`status` is NULL, 1, NULL), NULL))
COUNT(if(device.device_id is NOT NULL and device.`status` = 1, 1, NULL)) inUseDevice, unUseDevice,
COUNT(if(device.device_id is NOT NULL and device.`status` = 2, 1, NULL)) failedDevice COUNT(if(device.device_id is NOT NULL and device.`status` = 1, 1, NULL)) inUseDevice,
FROM USER COUNT(if(device.device_id is NOT NULL and device.`status` = 2, 1, NULL)) failedDevice
LEFT JOIN apply ON user.user_id = apply.user_id FROM USER
LEFT JOIN device ON apply.app_id = device.app_id LEFT JOIN apply ON user.user_id = apply.user_id
LEFT JOIN device ON apply.app_id = device.app_id
where 1=1 where 1=1
<if test="userIds != null">
and user.user_id in
<foreach collection="userIds" open="(" separator="," close=")" item="userId">
#{userId}
</foreach>
</if>
<if test="null != userName and '' != userName"> <if test="null != userName and '' != userName">
and user_name like concat('%',#{userName},'%') and user_name like concat('%',#{userName},'%')
</if> </if>
...@@ -34,11 +41,26 @@ ...@@ -34,11 +41,26 @@
</select> </select>
<select id="getUserByUserName" resultType="iot.sixiang.license.entity.User"> <select id="getUserByUserName" resultType="iot.sixiang.license.entity.User">
select * from user where user_name = #{userName} select * from user where user_name = #{userName} limit 1
</select> </select>
<select id="getUserById" resultType="iot.sixiang.license.entity.User"> <select id="getUserById" resultType="iot.sixiang.license.entity.User">
select * from user where user_id = #{userId} select * from user where user_id = #{userId} limit 1
</select>
<select id="getChildUser" resultType="iot.sixiang.license.model.vo.UserChildIdVO">
select user_id, parent, `level` from `user` where parent = #{userId}
</select>
<select id="getUserBySn" resultType="iot.sixiang.license.model.vo.UserInfoVO">
SELECT `user`.user_name, `user`.company, `user`.notify FROM user
INNER JOIN apply on user.user_id = apply.user_id
INNER JOIN device on device.app_id = apply.app_id
WHERE device.sn = #{sn}
</select>
<select id="getRootAccount" resultType="iot.sixiang.license.model.vo.UserInfoVO">
SELECT user_name, company, notify FROM `user` WHERE parent IS NULL AND `level` = 1 LIMIT 1
</select> </select>
</mapper> </mapper>
<?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="iot.sixiang.license.mapper.UserPermissionMapper">
<insert id="saveBatch">
insert into user_permission(permission, user, create_time) values
<foreach collection="userPermissions" separator="," item="permission">
(#{permission}, #{userId}, now())
</foreach>
</insert>
<delete id="deleteUserPermission">
delete from user_permission where user = #{userId}
</delete>
<delete id="delBatch">
delete from user_permission where user = #{userId} and permission in
<foreach collection="permissionDelList" open="(" separator="," close=")" item="permission">
#{permission}
</foreach>
</delete>
<select id="getPermissionById" resultType="iot.sixiang.license.entity.UserPermission">
SELECT * FROM `user_permission` WHERE user = #{userId} and deleted = 0
</select>
</mapper>
\ No newline at end of file
package iot.sixiang.license;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
/**
* Created by M=54G
* Date 9/14/22 3:08 PM
* Description
*/
@SpringBootTest
@ActiveProfiles({"test-acc"})
@Slf4j
public class BaseTest {
protected void log(Object object) {
log.info(JSON.toJSONString(object));
}
}
\ No newline at end of file
package iot.sixiang.license.controller;
import com.alibaba.fastjson2.JSON;
import iot.sixiang.license.object.data.AuthData;
import iot.sixiang.license.util.HmacUtil;
import iot.sixiang.license.util.sm4.SM4;
import iot.sixiang.license.util.sm4.SM4Context;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
/**
* Created by M=54G
* Date 11/11/22 9:54 AM
* Description
*/
public class DeviceControllerTest {
@Test
void terminalDeviceSign() {
String appId = "7j26zr7en9fiyoyvjz";
String sn = "8HOE8JH4EFSEV28534";
// String snBind = "snabcd";
String appKey = "2";
String string = "app_id=" + appId + "&sn=" + sn;
String sign = HmacUtil.encrypt(string, appKey, HmacUtil.HMAC_SHA1);
System.out.println("token appId:" + appId);
System.out.println("token sn:" + sn);
System.out.println("token sign:" + sign);
}
@Test
void tokenSign() {
String appId = "ebsh71dp5t1ck948l5";
String sn = "ERE54S619LNYMPKVN9";
String snBind = "snabcd";
String appKey = "110801";
String string = "app_id=" + appId + "&sn=" + sn + "&sn_bind=" + snBind;
String sign = HmacUtil.encrypt(string, appKey, HmacUtil.HMAC_SHA1);
System.out.println("token appId:" + appId);
System.out.println("token sn:" + sn);
System.out.println("token sign:" + sign);
}
@Test
void auth() {
String appId = "ebsh71dp5t1ck948l5";
String sn = "ERE54S619LNYMPKVN9";
String snBind = "snabcd";
String appKey = "110801";
//byte[] baseKeyBytes = "nAOq38p4bGQyF4FG".getBytes();
//System.out.println(baseKeyBytes.length);
byte[] allBytes = getAuthSendBytes(appId, sn, snBind, appKey);
System.out.println(bytes2Hex(allBytes));
}
@Test
void testSocket() {
String serverIp = "112.74.57.111";
int serverPort = 18889;
String appId = "ebsh71dp5t1ck948l5";
String sn = "ERE54S619LNYMPKVN9";
String snBind = "ZA2207G5NQ";
String appKey = "110801";
socket(serverIp, serverPort, appId, sn, snBind, appKey);
}
@Test
void yxSocket() {
String serverIp = "14.116.221.61";
int serverPort = 18889;
String appId = "mny3i9pgg0xxs520qf";
String sn = "IU23404BR1CQJOC63Q";
String snBind = "snabcd";
String appKey = "20221114";
socket(serverIp, serverPort, appId, sn, snBind, appKey);
}
@SneakyThrows
void socket(String serverIp, int serverPort, String appId, String sn, String snBind, String appKey) {
Socket socket = new Socket(serverIp, serverPort);
socket.setKeepAlive(true);
System.out.println("connect success...");
// 事先组装好要发送的鉴权信息
byte[] authSendBytes = getAuthSendBytes(appId, sn, snBind, appKey);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
// 鉴权
sendAndReceive(socket, outputStream, inputStream, "auth", authSendBytes);
Thread.sleep(1000);
// 鉴权后做动作
String request = "55AA340090000156F43D4D806827D1BB8F78C00D2B5488479CEB172C5D477C4D3023CE7B111621D4AD2C11ACAC4D876A3AC66A82F5F19000EF";
byte[] actionSendBytes = hex2Byte(request);
byte[] actionResultBytes = sendAndReceive(socket, outputStream, inputStream, "action", actionSendBytes);
//String result = "55AA1500A40035414E7DB5B3EDE72BC6BA44203F52EA0000005B";
//String result = "55aa1500a4008926834e684c4c6911b02304b3a0ce9c00000000";
//Assert.assertEquals(bytes2Hex(actionResultBytes), result);
inputStream.close();
outputStream.close();
socket.close();
}
@SneakyThrows
private byte[] sendAndReceive(Socket socket, OutputStream outputStream, InputStream inputStream, String tag, byte[] requestBytes) {
System.out.println(tag + " send:" + bytes2Hex(requestBytes));
outputStream.write(requestBytes);
outputStream.flush();
byte[] bytes = new byte[1024];
int count = inputStream.read(bytes);
while (count < 0) {
Thread.sleep(200);
count = inputStream.read(bytes);
}
byte[] resultBytes = new byte[count];
for (int i = 0; i < count; i++) {
resultBytes[i] = bytes[i];
}
System.out.println(tag + " receive:" + bytes2Hex(resultBytes));
return requestBytes;
}
private byte[] getAuthSendBytes(String appId, String sn, String snBind, String appKey) {
byte[] stxBytes = {(byte) 0x55, (byte) 0xaa};
// 这部分生成内容
// 用于SM4
byte[] randomBytes = new byte[16];
Random random = new Random();
for (int i = 0; i < randomBytes.length; i++) {
randomBytes[i] = (byte) (random.nextInt());
}
byte[] sm4KeyBytes = new byte[16];
byte[] baseKeyBytes = "nAOq38p4bGQyF4FG".getBytes();
for (int i = 0; i < randomBytes.length; i++) {
sm4KeyBytes[i] = (byte) (randomBytes[i] ^ baseKeyBytes[i]);
}
String string = "app_id=" + appId + "&sn=" + sn + "&sn_bind=" + snBind;
String sign = HmacUtil.encrypt(string, appKey, HmacUtil.HMAC_SHA1);
// 组装
AuthData authData = new AuthData();
authData.setApp_id(appId);
authData.setSn(sn);
authData.setSign(sign);
byte[] dataBytes = encryptData_ECB(JSON.toJSONString(authData), sm4KeyBytes);
dataBytes = byteMerger(randomBytes, dataBytes);
int length = dataBytes.length + stxBytes.length;
byte[] lenBytes = {(byte) length, (byte) (length >> 8)};
// 这部分是命令
byte cmdByte = (byte) 0x01;
byte ackByte = (byte) 0x00;
// 结束符
byte endByte = (byte) 0x00;
// 加密最后字段
endByte = (byte) (endByte ^ cmdByte);
endByte = (byte) (endByte ^ ackByte);
for (int i = 0; i < length - 2; i++) {
endByte = (byte) (endByte ^ dataBytes[i]);
}
return byteMerger(stxBytes, lenBytes, new byte[]{cmdByte, ackByte}, dataBytes, new byte[]{endByte});
}
public byte[] encryptData_ECB(String string, byte[] keyBytes) {
try {
SM4Context ctx = new SM4Context();
ctx.mode = SM4.SM4_ENCRYPT;
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
byte[] encrypted = sm4_crypt_ecb(sm4, ctx, string.getBytes("UTF-8"));
return encrypted;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] sm4_crypt_ecb(SM4 sm4, SM4Context ctx, byte[] input) throws Exception {
int length = input.length;
ByteArrayInputStream bins = new ByteArrayInputStream(input);
ByteArrayOutputStream bous = new ByteArrayOutputStream();
for (; length > 0; length -= 16) {
byte[] in = new byte[16];
byte[] out = new byte[16];
bins.read(in);
sm4.sm4_one_round(ctx.sk, in, out);
bous.write(out);
}
byte[] output = bous.toByteArray();
bins.close();
bous.close();
return output;
}
@Test
void authDevice() {
}
public static byte[] byteMerger(byte[]... byteList) {
int lengthByte = 0;
for (int i = 0; i < byteList.length; i++) {
lengthByte += byteList[i].length;
}
byte[] allByte = new byte[lengthByte];
int countLength = 0;
for (int i = 0; i < byteList.length; i++) {
byte[] b = byteList[i];
System.arraycopy(b, 0, allByte, countLength, b.length);
countLength += b.length;
}
return allByte;
}
public static String bytes2Hex(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder builder = new StringBuilder();
// 遍历byte[]数组,将每个byte数字转换成16进制字符,再拼接起来成字符串
for (int i = 0; i < bytes.length; i++) {
// 每个byte转换成16进制字符时,bytes[i] & 0xff如果高位是0,输出将会去掉,所以+0x100(在更高位加1),再截取后两位字符
builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
return builder.toString();
}
public static byte[] hex2Byte(String string) {
if (string == null || string.length() < 1) {
return null;
}
// 因为一个byte生成两个字符,长度对应1:2,所以byte[]数组长度是字符串长度一半
byte[] bytes = new byte[string.length() / 2];
// 遍历byte[]数组,遍历次数是字符串长度一半
for (int i = 0; i < string.length() / 2; i++) {
// 截取没两个字符的前一个,将其转为int数值
int high = Integer.parseInt(string.substring(i * 2, i * 2 + 1), 16);
// 截取没两个字符的后一个,将其转为int数值
int low = Integer.parseInt(string.substring(i * 2 + 1, i * 2 + 2), 16);
// 高位字符对应的int值*16+低位的int值,强转成byte数值即可
// 如dd,高位13*16+低位13=221(强转成byte二进制11011101,对应十进制-35)
bytes[i] = (byte) (high * 16 + low);
}
return bytes;
}
//public static void main(String[] args) {
// byte[] stxbyte = {(byte) 0x7E};
// byte[] typebyte = {(byte) 0x01};
// RespDevDataDto build = RespDevDataDto.builder().seqNo("0")
// .deviceSn("FSDF32FFZV").command("decodeconnectnorth")
// .timeStamp("1652233401604")
// .data(toStringHex("55AA34009000AB752BE54B0B05796E4C5E60060D99B79A37A534B4D081A6184C105FD7EABDBFE5ECE7EF08F933ED415CCD6DA82157059000FE")).build();
// String serverRespSign = DecodeHmacShaUtils.terminalReqSign(build);
// build.setSign(serverRespSign);
// byte[] resultbyte = JSONProvider.toJSONString(build).getBytes();
// Integer len = resultbyte.length + typebyte.length;
// String strlen = Integer.toString(len, 16);
// byte[] lenbyte = ByteHelper.hexStrToBytes(strlen, 2);
// byte[] databyte = ByteHelper.byteMerger(stxbyte, lenbyte, typebyte, resultbyte);
// System.out.println(byte2Hex(databyte));
// //7e0100017b22636f6d6d616e64223a226465636f6465636f6e6e6563746e6f727468222c2264617461223a2255efbfbd345c7530303030efbfbd5c7530303030efbfbd752befbfbd4b5c75303030425c7530303035796e4c5e605c75303030365c72efbfbdefbfbdefbfbd37efbfbd34efbfbdd081efbfbd5c75303031384c5c75303031305fefbfbdeabdbfefbfbdefbfbdefbfbdefbfbd5c62efbfbd33efbfbd415c5cefbfbd6defbfbd21575c7530303035efbfbd5c7530303030efbfbd222c22646576696365536e223a2246534446333246465a56222c227365714e6f223a2230222c227369676e223a2244344245393930333539343346454331323345354132414534443145353231304236413541463635222c2274696d655374616d70223a2231363532323333343031363034227d
//}
// 转化十六进制编码为字符串
//public static String toStringHex(String s) {
// byte[] baKeyword = new byte[s.length() / 2];
// for (int i = 0; i < baKeyword.length; i++) {
// try {
// baKeyword[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// try {
// s = new String(baKeyword, "utf-8");//UTF-16le:Not
// } catch (Exception e1) {
// e1.printStackTrace();
// }
// return s;
//}
//public static String bytes2hex(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// String tmp;
// sb.append("[");
// for (byte b : bytes) {
// // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
// //tmp = Integer.toHexString(b);
// tmp = Integer.toString((b & 0xff) + 0x100, 16).substring(1);
// if (tmp.length() == 1) {
// tmp = "0" + tmp;//只有一位的前面补个0
// }
// sb.append(tmp).append(",");//每个字节用空格断开
// }
// sb.delete(sb.length() - 1, sb.length());//删除最后一个字节后面对于的空格
// sb.append("]");
// return sb.toString();
//}
}
\ No newline at end of file
package iot.sixiang.license.object.data;
import lombok.Data;
/**
* Created by M=54G
* Date 11/11/22 10:08 AM
* Description
*/
@Data
public class AuthData {
private String app_id;
private String sn;
private String sign;
}
\ No newline at end of file
package iot.sixiang.license.service;
import iot.sixiang.license.BaseTest;
import iot.sixiang.license.model.dto.ReportErrorMsgDTO;
import org.junit.jupiter.api.Test;
import javax.annotation.Resource;
/**
* Created by M=54G
* Date 11/23/22 3:39 PM
* Description
*/
public class PmsUseServiceTest extends BaseTest {
@Resource
private PmsUseService pmsUseService;
@Test
void addLog() {
log(pmsUseService.createUseLog("abcd"));
}
@Test
void updateLog() {
ReportErrorMsgDTO reportErrorMsgDTO = new ReportErrorMsgDTO();
reportErrorMsgDTO.setId(1);
pmsUseService.success(reportErrorMsgDTO);
}
}
\ No newline at end of file
package iot.sixiang.license.util;
import org.apache.http.util.TextUtils;
public class ByteHelper {
/**
* src:源数组
* srcPos:源数组要复制的起始位置
* dest:目的数组
* destPos:目的数组放置的起始位置
* length:要复制的长度
*
* @param src
* @param begin
* @param count
* @return
*/
public static byte[] subBytes(byte[] src, int begin, int count) {
byte[] bs = new byte[count];
System.arraycopy(src, begin, bs, 0, count);
return bs;
}
/**
* 字节码转化十六进制
*
* @author xzb
*/
public static String fromBytesToHex(byte[] resultBytes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < resultBytes.length; i++) {
if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) {
builder.append("0").append(Integer.toHexString(0xFF & resultBytes[i]));
} else {
builder.append(Integer.toHexString(0xFF & resultBytes[i]));
}
}
return builder.toString();
}
/**
* byte[] 转为16进制String
*/
public static String Bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
/**
* 转化十六进制编码为字符串
*
* @param s
* @return
*/
public static String toStringHex(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "utf-8");//UTF-16le:Not
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
/***
* 合并数组
* @param byteList
* @return
*/
public static byte[] byteMerger(byte[]... byteList) {
int lengthByte = 0;
for (int i = 0; i < byteList.length; i++) {
lengthByte += byteList[i].length;
}
byte[] allByte = new byte[lengthByte];
int countLength = 0;
for (int i = 0; i < byteList.length; i++) {
byte[] b = byteList[i];
System.arraycopy(b, 0, allByte, countLength, b.length);
countLength += b.length;
}
return allByte;
}
/**
* 字符串转16进制
*
* @param string
* @return
*/
public static String stringToHexString(String string) {
char[] c = new char[string.length()];
c = string.toCharArray();
String hesStr = "";
for (int i = 0; i < c.length; i++) {
hesStr = hesStr + Integer.toHexString(c[i]);
}
return hesStr;
}
/**
* 字符串转化成为16进制字符串
*
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
/**
* hex字符串转byte数组
*
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex, int len) {
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1) {
//奇数
hexlen++;
result = new byte[(hexlen / 2)];
inHex = "0" + inHex;
} else {
//偶数
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
public static long bytes2long(byte[] bs) throws Exception {
int bytes = bs.length;
if (bytes > 1) {
if ((bytes % 2) != 0 || bytes > 8) {
throw new Exception("not support");
}
}
switch (bytes) {
case 0:
return 0;
case 1:
return (long) ((bs[0] & 0xff));
case 2:
return (long) ((bs[0] & 0xff) << 8 | (bs[1] & 0xff));
case 4:
return (long) ((bs[0] & 0xffL) << 24 | (bs[1] & 0xffL) << 16 | (bs[2] & 0xffL) << 8 | (bs[3] & 0xffL));
case 8:
return (long) ((bs[0] & 0xffL) << 56 | (bs[1] & 0xffL) << 48 | (bs[2] & 0xffL) << 40 | (bs[3] & 0xffL) << 32 |
(bs[4] & 0xffL) << 24 | (bs[5] & 0xffL) << 16 | (bs[6] & 0xffL) << 8 | (bs[7] & 0xffL));
default:
throw new Exception("not support");
}
//return 0;
}
public static long bytes2long(byte[] bs, int offset) {
return (long) ((bs[7 + offset] & 0xffL) << 56 | (bs[6 + offset] & 0xffL) << 48 | (bs[5 + offset] & 0xffL) << 40 | (bs[4 + offset] & 0xffL) << 32 |
(bs[3 + offset] & 0xffL) << 24 | (bs[2 + offset] & 0xffL) << 16 | (bs[1 + offset] & 0xffL) << 8 | (bs[0 + offset] & 0xffL));
}
public static byte[] hexStrToBytes(String hexStr, int len) {
if (TextUtils.isEmpty(hexStr) || hexStr.length() == 0) {
return null;
}
if (hexStr.length() % 2 == 1) {
hexStr = "0" + hexStr;
}
byte[] result = new byte[len];
char[] chars = hexStr.toCharArray();
int hexlen = hexStr.length();
if (hexlen > len)
hexlen = len;
for (int i = 0; i < hexlen - 1; i++) {
result[i] = (byte) (charToByte(chars[i]) << 4 | charToByte(chars[i + 1]));
}
return result;
}
private static byte charToByte(char c) {
String chars = "0123456789ABCDEF";
byte b = (byte) chars.indexOf(c);
return b;
}
/**
* Hex字符串转byte
*
* @param inHex 待转换的Hex字符串
* @return 转换后的byte
*/
public static byte hexToByte(String inHex) {
return (byte) Integer.parseInt(inHex, 16);
}
}
package iot.sixiang.license.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* Title: HmacShaUtils
* Description:
*
* @author YFW
* @version V1.0
* @date 2022-03-14
*/
public class HmacShaUtils {
private static final String HMAC_ALGORITHM = "hmacsha1";
private static final String secretKey = "90d2fca50ea8ed5472c5776c9fc53699";
/**
* 使用HMAC_ALGORITHM加密。
*
* @param content,明文。
* @param secret,密钥。
* @return 密文。
*/
public static String encrypt(String content, String secret) {
if (PubUtils.isNull(secret)) secret = secretKey;
try {
byte[] text = content.getBytes(StandardCharsets.UTF_8);
byte[] key = secret.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_ALGORITHM);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return byte2hex(mac.doFinal(text));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 二进制转十六进制字符串。
*
* @param b,二进制数组。
* @return 十六进制字符串。
*/
public static String byte2hex(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int n = 0; b != null && n < b.length; n++) {
String stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
sb.append('0');
}
sb.append(stmp);
}
return sb.toString().toUpperCase();
}
}
package iot.sixiang.license.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.UUID;
/**
* Title: PubUtils
* Description: 公共实体类
*
* @author YFW
* @version V1.0
* @date 2020-07-28
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PubUtils {
/**
* The constant STRING_NULL.
*/
private final static String STRING_NULL = "-";
/**
* 匹配手机号码, 支持+86和86开头
*/
private static final String REGX_MOBILENUM = "^((\\+86)|(86))?(13|15|17|18)\\d{9}$";
/**
* 匹配手机号码, 支持+86和86开头
*/
private static final String REGX_MOBILENUM_NEW = "^((\\+86)|(86))?(1)\\d{10}$";
/**
* 匹配邮箱帐号
*/
private static final String REGX_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
/**
* 匹配设备标签,支持字母、数字、汉字和英文逗号,但不能以英文逗号结尾
*/
private static final String REGX_TAGS = "[a-zA-Z0-9,\\u4E00-\\u9FA5]*[^,]";
/**
* 匹配手机号码(先支持13, 15, 17, 18开头的手机号码).
*
* @param inputStr the input str
*
* @return the boolean
*/
public static Boolean isMobileNumber(String inputStr) {
return !PubUtils.isNull(inputStr) && inputStr.matches(REGX_MOBILENUM);
}
public static Boolean isMobileNumberNew(String inputStr) {
return !PubUtils.isNull(inputStr) && inputStr.matches(REGX_MOBILENUM_NEW);
}
/**
* 判断一个或多个对象是否为空
*
* @param values 可变参数, 要判断的一个或多个对象
*
* @return 只有要判断的一个对象都为空则返回true, 否则返回false boolean
*/
public static boolean isNull(Object... values) {
if (!PubUtils.isNotNullAndNotEmpty(values)) {
return true;
}
for (Object value : values) {
boolean flag;
if (value instanceof Object[]) {
flag = !isNotNullAndNotEmpty((Object[]) value);
} else if (value instanceof Collection<?>) {
flag = !isNotNullAndNotEmpty((Collection<?>) value);
} else if (value instanceof String) {
flag = isOEmptyOrNull(value);
} else {
flag = (null == value);
}
if (flag) {
return true;
}
}
return false;
}
/**
* Is o empty or null boolean.
*
* @param o the o
*
* @return boolean boolean
*/
private static boolean isOEmptyOrNull(Object o) {
return o == null || isSEmptyOrNull(o.toString());
}
/**
* Is s empty or null boolean.
*
* @param s the s
*
* @return boolean boolean
*/
private static boolean isSEmptyOrNull(String s) {
return trimAndNullAsEmpty(s).length() <= 0;
}
/**
* Trim and null as empty string.
*
* @param s the s
*
* @return java.lang.String string
*/
private static String trimAndNullAsEmpty(String s) {
if (s != null && !s.trim().equals(STRING_NULL)) {
return s.trim();
} else {
return "";
}
// return s == null ? "" : s.trim();
}
/**
* 判断对象数组是否为空并且数量大于0
*
* @param value the value
*
* @return boolean
*/
private static Boolean isNotNullAndNotEmpty(Object[] value) {
boolean bl = false;
if (null != value && 0 < value.length) {
bl = true;
}
return bl;
}
/**
* 判断对象集合(List,Set)是否为空并且数量大于0
*
* @param value the value
*
* @return boolean
*/
private static Boolean isNotNullAndNotEmpty(Collection<?> value) {
boolean bl = false;
if (null != value && !value.isEmpty()) {
bl = true;
}
return bl;
}
/**
* Is email boolean.
*
* @param str the str
*
* @return the boolean
*/
public static boolean isEmail(String str) {
boolean bl = true;
if (isSEmptyOrNull(str) || !str.matches(REGX_EMAIL)) {
bl = false;
}
return bl;
}
/**
* Is tags boolean.
*
* @param str the str
*
* @return the boolean
*/
public static boolean isTags(String str) {
boolean bl = true;
if (isSEmptyOrNull(str) || !str.matches(REGX_TAGS)) {
bl = false;
}
return bl;
}
/**
* Uuid string.
*
* @return the string
*/
public synchronized static String uuid() {
return UUID.randomUUID().toString().replace("-", "");
}
}
package iot.sixiang.license.util.sm4;
import java.math.BigInteger;
public class ByteUtil {
/**
* 整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个整型数据
* @return 4个字节的自己数组
*/
public static byte[] intToBytes(int num) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & (num >> 0));
bytes[1] = (byte) (0xff & (num >> 8));
bytes[2] = (byte) (0xff & (num >> 16));
bytes[3] = (byte) (0xff & (num >> 24));
return bytes;
}
/**
* 四个字节的字节数据转换成一个整形数据
*
* @param bytes 4个字节的字节数组
* @return 一个整型数据
*/
public static int byteToInt(byte[] bytes) {
int num = 0;
int temp;
temp = (0x000000ff & (bytes[0])) << 0;
num = num | temp;
temp = (0x000000ff & (bytes[1])) << 8;
num = num | temp;
temp = (0x000000ff & (bytes[2])) << 16;
num = num | temp;
temp = (0x000000ff & (bytes[3])) << 24;
num = num | temp;
return num;
}
/**
* 长整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个长整型数据
* @return 4个字节的自己数组
*/
public static byte[] longToBytes(long num) {
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++) {
bytes[i] = (byte) (0xff & (num >> (i * 8)));
}
return bytes;
}
/**
* 大数字转换字节流(字节数组)型数据
*
* @param n
* @return
*/
public static byte[] byteConvert32Bytes(BigInteger n) {
byte tmpd[] = (byte[]) null;
if (n == null) {
return null;
}
if (n.toByteArray().length == 33) {
tmpd = new byte[32];
System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
} else if (n.toByteArray().length == 32) {
tmpd = n.toByteArray();
} else {
tmpd = new byte[32];
for (int i = 0; i < 32 - n.toByteArray().length; i++) {
tmpd[i] = 0;
}
System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
}
return tmpd;
}
/**
* 换字节流(字节数组)型数据转大数字
*
* @param b
* @return
*/
public static BigInteger byteConvertInteger(byte[] b) {
if (b[0] < 0) {
byte[] temp = new byte[b.length + 1];
temp[0] = 0;
System.arraycopy(b, 0, temp, 1, b.length);
return new BigInteger(temp);
}
return new BigInteger(b);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @return
*/
public static String getHexString(byte[] bytes) {
return getHexString(bytes, true);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @param upperCase
* @return
*/
public static String getHexString(byte[] bytes, boolean upperCase) {
String ret = "";
for (int i = 0; i < bytes.length; i++) {
ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
}
return upperCase ? ret.toUpperCase() : ret;
}
/**
* 打印十六进制字符串
*
* @param bytes
*/
public static void printHexString(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print("0x" + hex.toUpperCase() + ",");
}
System.out.println("");
}
/**
* Convert hex string to byte[]
*
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c char
* @return byte
*/
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @return 十六进制String
*/
public static String encodeHexString(byte[] data) {
return encodeHexString(data, true);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制String
*/
public static String encodeHexString(byte[] data, boolean toLowerCase) {
return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
protected static String encodeHexString(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将十六进制字符数组转换为字节数组
*
* @param data 十六进制char[]
* @return byte[]
* @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
*/
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
*/
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
/**
* 数字字符串转ASCII码字符串
*
* @param String 字符串
* @return ASCII字符串
*/
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
String b = Integer.toHexString(c);
result = result + b;
}
return result;
}
/**
* 十六进制转字符串
*
* @param hexString 十六进制字符串
* @param encodeType 编码类型4:Unicode,2:普通编码
* @return 字符串
*/
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(hexString
.substring(i * encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
/**
* 十六进制字符串装十进制
*
* @param hex 十六进制字符串
* @return 十进制数值
*/
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - '0';
} else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/**
* 十六转二进制
*
* @param hex 十六进制字符串
* @return 二进制字符串
*/
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'A':
result += "1010";
break;
case 'B':
result += "1011";
break;
case 'C':
result += "1100";
break;
case 'D':
result += "1101";
break;
case 'E':
result += "1110";
break;
case 'F':
result += "1111";
break;
}
}
return result;
}
/**
* ASCII码字符串转数字字符串
*
* @param String ASCII字符串
* @return 字符串
*/
public static String AsciiStringToString(String content) {
String result = "";
int length = content.length() / 2;
for (int i = 0; i < length; i++) {
String c = content.substring(i * 2, i * 2 + 2);
int a = hexStringToAlgorism(c);
char b = (char) a;
String d = String.valueOf(b);
result += d;
}
return result;
}
/**
* 将十进制转换为指定长度的十六进制字符串
*
* @param algorism int 十进制数字
* @param maxLength int 转换后的十六进制字符串长度
* @return String 转换后的十六进制字符串
*/
public static String algorismToHexString(int algorism, int maxLength) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
return patchHexString(result.toUpperCase(), maxLength);
}
/**
* 字节数组转为普通字符串(ASCII对应的字符)
*
* @param bytearray byte[]
* @return String
*/
public static String byteToString(byte[] bytearray) {
String result = "";
char temp;
int length = bytearray.length;
for (int i = 0; i < length; i++) {
temp = (char) bytearray[i];
result += temp;
}
return result;
}
/**
* 二进制字符串转十进制
*
* @param binary 二进制字符串
* @return 十进制数值
*/
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - '0';
result += Math.pow(2, max - i) * algorism;
}
return result;
}
/**
* 十进制转换为十六进制字符串
*
* @param algorism int 十进制的数字
* @return String 对应的十六进制字符串
*/
public static String algorismToHEXString(int algorism) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
result = result.toUpperCase();
return result;
}
/**
* HEX字符串前补0,主要用于长度位数不足。
*
* @param str String 需要补充长度的十六进制字符串
* @param maxLength int 补充后十六进制字符串的长度
* @return 补充结果
*/
static public String patchHexString(String str, int maxLength) {
String temp = "";
for (int i = 0; i < maxLength - str.length(); i++) {
temp = "0" + temp;
}
str = (temp + str).substring(0, maxLength);
return str;
}
/**
* 将一个字符串转换为int
*
* @param s String 要转换的字符串
* @param defaultInt int 如果出现异常,默认返回的数字
* @param radix int 要转换的字符串是什么进制的,如16 8 10.
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt, int radix) {
int i = 0;
try {
i = Integer.parseInt(s, radix);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 将一个十进制形式的数字字符串转换为int
*
* @param s String 要转换的字符串
* @param defaultInt int 如果出现异常,默认返回的数字
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt) {
int i = 0;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 十六进制串转化为byte数组
*
* @return the array of byte
*/
public static byte[] hexToByte(String hex)
throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
/**
* 字节数组转换为十六进制字符串
*
* @param b byte[] 需要转换的字节数组
* @return String 十六进制字符串
*/
public static String byteToHex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException(
"Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
for (int i = 0; i < length; i++) {
bt[i] = input[i + startIndex];
}
return bt;
}
}
package iot.sixiang.license.util.sm4;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class SM4 {
public static final int SM4_ENCRYPT = 1;
public static final int SM4_DECRYPT = 0;
private long GET_ULONG_BE(byte[] b, int i) {
long n = (long) (b[i] & 0xff) << 24 | (long) ((b[i + 1] & 0xff) << 16) | (long) ((b[i + 2] & 0xff) << 8) | (long) (b[i + 3] & 0xff) & 0xffffffffL;
return n;
}
private void PUT_ULONG_BE(long n, byte[] b, int i) {
b[i] = (byte) (int) (0xFF & n >> 24);
b[i + 1] = (byte) (int) (0xFF & n >> 16);
b[i + 2] = (byte) (int) (0xFF & n >> 8);
b[i + 3] = (byte) (int) (0xFF & n);
}
private long SHL(long x, int n) {
return (x & 0xFFFFFFFF) << n;
}
private long ROTL(long x, int n) {
return SHL(x, n) | x >> (32 - n);
}
private void SWAP(long[] sk, int i) {
long t = sk[i];
sk[i] = sk[(31 - i)];
sk[(31 - i)] = t;
}
public static final byte[] SboxTable = {(byte) 0xd6, (byte) 0x90, (byte) 0xe9, (byte) 0xfe,
(byte) 0xcc, (byte) 0xe1, 0x3d, (byte) 0xb7, 0x16, (byte) 0xb6,
0x14, (byte) 0xc2, 0x28, (byte) 0xfb, 0x2c, 0x05, 0x2b, 0x67,
(byte) 0x9a, 0x76, 0x2a, (byte) 0xbe, 0x04, (byte) 0xc3,
(byte) 0xaa, 0x44, 0x13, 0x26, 0x49, (byte) 0x86, 0x06,
(byte) 0x99, (byte) 0x9c, 0x42, 0x50, (byte) 0xf4, (byte) 0x91,
(byte) 0xef, (byte) 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43,
(byte) 0xed, (byte) 0xcf, (byte) 0xac, 0x62, (byte) 0xe4,
(byte) 0xb3, 0x1c, (byte) 0xa9, (byte) 0xc9, 0x08, (byte) 0xe8,
(byte) 0x95, (byte) 0x80, (byte) 0xdf, (byte) 0x94, (byte) 0xfa,
0x75, (byte) 0x8f, 0x3f, (byte) 0xa6, 0x47, 0x07, (byte) 0xa7,
(byte) 0xfc, (byte) 0xf3, 0x73, 0x17, (byte) 0xba, (byte) 0x83,
0x59, 0x3c, 0x19, (byte) 0xe6, (byte) 0x85, 0x4f, (byte) 0xa8,
0x68, 0x6b, (byte) 0x81, (byte) 0xb2, 0x71, 0x64, (byte) 0xda,
(byte) 0x8b, (byte) 0xf8, (byte) 0xeb, 0x0f, 0x4b, 0x70, 0x56,
(byte) 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, (byte) 0xd1,
(byte) 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, (byte) 0x87,
(byte) 0xd4, 0x00, 0x46, 0x57, (byte) 0x9f, (byte) 0xd3, 0x27,
0x52, 0x4c, 0x36, 0x02, (byte) 0xe7, (byte) 0xa0, (byte) 0xc4,
(byte) 0xc8, (byte) 0x9e, (byte) 0xea, (byte) 0xbf, (byte) 0x8a,
(byte) 0xd2, 0x40, (byte) 0xc7, 0x38, (byte) 0xb5, (byte) 0xa3,
(byte) 0xf7, (byte) 0xf2, (byte) 0xce, (byte) 0xf9, 0x61, 0x15,
(byte) 0xa1, (byte) 0xe0, (byte) 0xae, 0x5d, (byte) 0xa4,
(byte) 0x9b, 0x34, 0x1a, 0x55, (byte) 0xad, (byte) 0x93, 0x32,
0x30, (byte) 0xf5, (byte) 0x8c, (byte) 0xb1, (byte) 0xe3, 0x1d,
(byte) 0xf6, (byte) 0xe2, 0x2e, (byte) 0x82, 0x66, (byte) 0xca,
0x60, (byte) 0xc0, 0x29, 0x23, (byte) 0xab, 0x0d, 0x53, 0x4e, 0x6f,
(byte) 0xd5, (byte) 0xdb, 0x37, 0x45, (byte) 0xde, (byte) 0xfd,
(byte) 0x8e, 0x2f, 0x03, (byte) 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b,
0x51, (byte) 0x8d, 0x1b, (byte) 0xaf, (byte) 0x92, (byte) 0xbb,
(byte) 0xdd, (byte) 0xbc, 0x7f, 0x11, (byte) 0xd9, 0x5c, 0x41,
0x1f, 0x10, 0x5a, (byte) 0xd8, 0x0a, (byte) 0xc1, 0x31,
(byte) 0x88, (byte) 0xa5, (byte) 0xcd, 0x7b, (byte) 0xbd, 0x2d,
0x74, (byte) 0xd0, 0x12, (byte) 0xb8, (byte) 0xe5, (byte) 0xb4,
(byte) 0xb0, (byte) 0x89, 0x69, (byte) 0x97, 0x4a, 0x0c,
(byte) 0x96, 0x77, 0x7e, 0x65, (byte) 0xb9, (byte) 0xf1, 0x09,
(byte) 0xc5, 0x6e, (byte) 0xc6, (byte) 0x84, 0x18, (byte) 0xf0,
0x7d, (byte) 0xec, 0x3a, (byte) 0xdc, 0x4d, 0x20, 0x79,
(byte) 0xee, 0x5f, 0x3e, (byte) 0xd7, (byte) 0xcb, 0x39, 0x48};
public static final int[] FK = {0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc};
public static final int[] CK = {0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279};
private byte sm4Sbox(byte inch) {
int i = inch & 0xFF;
byte retVal = SboxTable[i];
return retVal;
}
private long sm4Lt(long ka) {
long bb = 0L;
long c = 0L;
byte[] a = new byte[4];
byte[] b = new byte[4];
PUT_ULONG_BE(ka, a, 0);
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
bb = GET_ULONG_BE(b, 0);
c = bb ^ ROTL(bb, 2) ^ ROTL(bb, 10) ^ ROTL(bb, 18) ^ ROTL(bb, 24);
return c;
}
private long sm4F(long x0, long x1, long x2, long x3, long rk) {
return x0 ^ sm4Lt(x1 ^ x2 ^ x3 ^ rk);
}
private long sm4CalciRK(long ka) {
long bb = 0L;
long rk = 0L;
byte[] a = new byte[4];
byte[] b = new byte[4];
PUT_ULONG_BE(ka, a, 0);
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
bb = GET_ULONG_BE(b, 0);
rk = bb ^ ROTL(bb, 13) ^ ROTL(bb, 23);
return rk;
}
private void sm4_setkey(long[] SK, byte[] key) {
long[] MK = new long[4];
long[] k = new long[36];
int i = 0;
MK[0] = GET_ULONG_BE(key, 0);
MK[1] = GET_ULONG_BE(key, 4);
MK[2] = GET_ULONG_BE(key, 8);
MK[3] = GET_ULONG_BE(key, 12);
k[0] = MK[0] ^ (long) FK[0];
k[1] = MK[1] ^ (long) FK[1];
k[2] = MK[2] ^ (long) FK[2];
k[3] = MK[3] ^ (long) FK[3];
for (; i < 32; i++) {
k[(i + 4)] = (k[i] ^ sm4CalciRK(k[(i + 1)] ^ k[(i + 2)] ^ k[(i + 3)] ^ (long) CK[i]));
SK[i] = k[(i + 4)];
}
}
public void sm4_one_round(long[] sk, byte[] input, byte[] output) {
int i = 0;
long[] ulbuf = new long[36];
ulbuf[0] = GET_ULONG_BE(input, 0);
ulbuf[1] = GET_ULONG_BE(input, 4);
ulbuf[2] = GET_ULONG_BE(input, 8);
ulbuf[3] = GET_ULONG_BE(input, 12);
while (i < 32) {
ulbuf[(i + 4)] = sm4F(ulbuf[i], ulbuf[(i + 1)], ulbuf[(i + 2)], ulbuf[(i + 3)], sk[i]);
i++;
}
PUT_ULONG_BE(ulbuf[35], output, 0);
PUT_ULONG_BE(ulbuf[34], output, 4);
PUT_ULONG_BE(ulbuf[33], output, 8);
PUT_ULONG_BE(ulbuf[32], output, 12);
}
private byte[] padding(byte[] input, int mode) {
if (input == null) {
return null;
}
byte[] ret = (byte[]) null;
if (mode == SM4_ENCRYPT) {
int p = 16 - input.length % 16;
ret = new byte[input.length + p];
System.arraycopy(input, 0, ret, 0, input.length);
for (int i = 0; i < p; i++) {
ret[input.length + i] = (byte) p;
}
} else {
int p = input[input.length - 1];
ret = new byte[input.length - p];
System.arraycopy(input, 0, ret, 0, input.length - p);
}
return ret;
}
public void sm4_setkey_enc(SM4Context ctx, byte[] key) throws Exception {
if (ctx == null) {
throw new Exception("ctx is null!");
}
if (key == null || key.length != 16) {
throw new Exception("key error!");
}
ctx.mode = SM4_ENCRYPT;
sm4_setkey(ctx.sk, key);
}
public void sm4_setkey_dec(SM4Context ctx, byte[] key) throws Exception {
if (ctx == null) {
throw new Exception("ctx is null!");
}
if (key == null || key.length != 16) {
throw new Exception("key error!");
}
int i = 0;
ctx.mode = SM4_DECRYPT;
sm4_setkey(ctx.sk, key);
for (i = 0; i < 16; i++) {
SWAP(ctx.sk, i);
}
}
public byte[] sm4_crypt_ecb(SM4Context ctx, byte[] input) throws Exception {
if (input == null) {
throw new Exception("input is null!");
}
if ((ctx.isPadding) && (ctx.mode == SM4_ENCRYPT)) {
input = padding(input, SM4_ENCRYPT);
}
int length = input.length;
ByteArrayInputStream bins = new ByteArrayInputStream(input);
ByteArrayOutputStream bous = new ByteArrayOutputStream();
for (; length > 0; length -= 16) {
byte[] in = new byte[16];
byte[] out = new byte[16];
bins.read(in);
sm4_one_round(ctx.sk, in, out);
bous.write(out);
}
byte[] output = bous.toByteArray();
if (ctx.isPadding && ctx.mode == SM4_DECRYPT) {
output = padding(output, SM4_DECRYPT);
}
bins.close();
bous.close();
return output;
}
public byte[] sm4_crypt_cbc(SM4Context ctx, byte[] iv, byte[] input) throws Exception {
if (iv == null || iv.length != 16) {
throw new Exception("iv error!");
}
if (input == null) {
throw new Exception("input is null!");
}
if (ctx.isPadding && ctx.mode == SM4_ENCRYPT) {
input = padding(input, SM4_ENCRYPT);
}
int i = 0;
int length = input.length;
ByteArrayInputStream bins = new ByteArrayInputStream(input);
ByteArrayOutputStream bous = new ByteArrayOutputStream();
if (ctx.mode == SM4_ENCRYPT) {
for (; length > 0; length -= 16) {
byte[] in = new byte[16];
byte[] out = new byte[16];
byte[] out1 = new byte[16];
bins.read(in);
for (i = 0; i < 16; i++) {
out[i] = ((byte) (in[i] ^ iv[i]));
}
sm4_one_round(ctx.sk, out, out1);
System.arraycopy(out1, 0, iv, 0, 16);
bous.write(out1);
}
} else {
byte[] temp = new byte[16];
for (; length > 0; length -= 16) {
byte[] in = new byte[16];
byte[] out = new byte[16];
byte[] out1 = new byte[16];
bins.read(in);
System.arraycopy(in, 0, temp, 0, 16);
sm4_one_round(ctx.sk, in, out);
for (i = 0; i < 16; i++) {
out1[i] = ((byte) (out[i] ^ iv[i]));
}
System.arraycopy(temp, 0, iv, 0, 16);
bous.write(out1);
}
}
byte[] output = bous.toByteArray();
if (ctx.isPadding && ctx.mode == SM4_DECRYPT) {
output = padding(output, SM4_DECRYPT);
}
bins.close();
bous.close();
return output;
}
}
package iot.sixiang.license.util.sm4;
public class SM4Context {
public int mode;
public long[] sk;
public boolean isPadding;
public SM4Context() {
this.mode = 1;
this.isPadding = true;
this.sk = new long[32];
}
}
package iot.sixiang.license.util.sm4;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SM4Utils {
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public boolean isHexString() {
return hexString;
}
public void setHexString(boolean hexString) {
this.hexString = hexString;
}
private String secretKey = "";
public String getIv() {
return iv;
}
public void setIv(String iv) {
this.iv = iv;
}
private String iv = "";
private boolean hexString = false;
public SM4Utils() {
}
public String encryptData_ECB(String plainText) {
try {
SM4Context ctx = new SM4Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
byte[] keyBytes;
if (hexString) {
keyBytes = ByteUtil.hexStringToBytes(secretKey);
} else {
keyBytes = secretKey.getBytes();
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes("UTF-8"));
String cipherText = Base64.getEncoder().encodeToString(encrypted);
if (cipherText != null && cipherText.trim().length() > 0) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(cipherText);
cipherText = m.replaceAll("");
}
return cipherText;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String decryptData_ECB(String cipherText) {
try {
SM4Context ctx = new SM4Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_DECRYPT;
byte[] keyBytes;
if (hexString) {
keyBytes = ByteUtil.hexStringToBytes(secretKey);
} else {
keyBytes = secretKey.getBytes();
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_dec(ctx, keyBytes);
byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Base64.getDecoder().decode(cipherText));
return new String(decrypted, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String encryptData_CBC(String plainText) {
try {
SM4Context ctx = new SM4Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = ByteUtil.hexStringToBytes(secretKey);
ivBytes = ByteUtil.hexStringToBytes(iv);
} else {
keyBytes = secretKey.getBytes();
ivBytes = iv.getBytes();
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes("UTF-8"));
String cipherText = Base64.getEncoder().encodeToString(encrypted);
if (cipherText != null && cipherText.trim().length() > 0) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(cipherText);
cipherText = m.replaceAll("");
}
return cipherText;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String decryptData_CBC(String cipherText) {
try {
SM4Context ctx = new SM4Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_DECRYPT;
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = ByteUtil.hexStringToBytes(secretKey);
ivBytes = ByteUtil.hexStringToBytes(iv);
} else {
keyBytes = secretKey.getBytes();
ivBytes = iv.getBytes();
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_dec(ctx, keyBytes);
byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Base64.getDecoder().decode(cipherText));
return new String(decrypted, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment