代码优化

This commit is contained in:
kerwincui
2022-05-30 23:07:18 +08:00
parent c768af6cf9
commit 1f9636ac96
3 changed files with 201 additions and 158 deletions

View File

@@ -74,11 +74,6 @@ public class ToolController extends BaseController {
@Autowired @Autowired
private IDeviceService deviceService; private IDeviceService deviceService;
private IProductAuthorizeService authorizeService;
@Autowired
private ThingsModelServiceImpl thingsModelService;
@Lazy @Lazy
@Autowired @Autowired
private EmqxService emqxService; private EmqxService emqxService;
@@ -89,9 +84,6 @@ public class ToolController extends BaseController {
@Autowired @Autowired
private IToolService toolService; private IToolService toolService;
@Autowired
private ProductAuthorizeMapper productAuthorizeMapper;
// 令牌秘钥 // 令牌秘钥
@Value("${token.secret}") @Value("${token.secret}")
private String secret; private String secret;
@@ -118,7 +110,7 @@ public class ToolController extends BaseController {
log.info("-----------服务端mqtt认证成功,clientId:" + clientid + "---------------"); log.info("-----------服务端mqtt认证成功,clientId:" + clientid + "---------------");
return ResponseEntity.ok().body("ok"); return ResponseEntity.ok().body("ok");
} else { } else {
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "mqtt账号和密码与认证服务器配置不匹配"); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "mqtt账号和密码与认证服务器配置不匹配");
} }
} else if (clientid.startsWith("web") || clientid.startsWith("phone")) { } else if (clientid.startsWith("web") || clientid.startsWith("phone")) {
// web端和移动端认证token认证 // web端和移动端认证token认证
@@ -131,13 +123,13 @@ public class ToolController extends BaseController {
log.info("-----------移动端/Web端mqtt认证成功,clientId:" + clientid + "---------------"); log.info("-----------移动端/Web端mqtt认证成功,clientId:" + clientid + "---------------");
return ResponseEntity.ok().body("ok"); return ResponseEntity.ok().body("ok");
} catch (Exception ex) { } catch (Exception ex) {
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), ex.getMessage()); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), ex.getMessage());
} }
} else { } else {
// 设备端认证加密认证E和简单认证S配置的账号密码认证 // 设备端认证加密认证E和简单认证S配置的账号密码认证
String[] clientArray = clientid.split("&"); String[] clientArray = clientid.split("&");
if(clientArray.length != 4 || clientArray[0].equals("") || clientArray[1].equals("") || clientArray[2].equals("") || clientArray[3].equals("")){ if(clientArray.length != 4 || clientArray[0].equals("") || clientArray[1].equals("") || clientArray[2].equals("") || clientArray[3].equals("")){
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备mqtt客户端Id格式为认证类型 & 设备编号 & 产品ID & 用户ID"); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备mqtt客户端Id格式为认证类型 & 设备编号 & 产品ID & 用户ID");
} }
String authType = clientArray[0]; String authType = clientArray[0];
String deviceNumber = clientArray[1]; String deviceNumber = clientArray[1];
@@ -146,167 +138,26 @@ public class ToolController extends BaseController {
// 产品认证信息 // 产品认证信息
ProductAuthenticateModel model = deviceService.selectProductAuthenticate(new AuthenticateInputModel(deviceNumber, productId)); ProductAuthenticateModel model = deviceService.selectProductAuthenticate(new AuthenticateInputModel(deviceNumber, productId));
if (model == null) { if (model == null) {
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证通过产品ID查询不到信息"); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证通过产品ID查询不到信息");
} }
if (model.getProductStatus() != 2) { if (model.getProductStatus() != 2) {
// 产品必须为发布状态1-未发布2-已发布 // 产品必须为发布状态1-未发布2-已发布
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证,设备对应产品还未发布"); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证,设备对应产品还未发布");
} }
if (authType.equals("S")) { if (authType.equals("S")) {
// 设备简单认证 // 设备简单认证
return simpleMqttAuthentication(new MqttAuthenticationModel(clientid, username, password, deviceNumber, productId, userId), model); return toolService.simpleMqttAuthentication(new MqttAuthenticationModel(clientid, username, password, deviceNumber, productId, userId), model);
} else if (authType.equals("E")) { } else if (authType.equals("E")) {
// 设备加密认证 // 设备加密认证
return encryptAuthentication(new MqttAuthenticationModel(clientid, username, password, deviceNumber, productId, userId), model); return toolService.encryptAuthentication(new MqttAuthenticationModel(clientid, username, password, deviceNumber, productId, userId), model);
} else { } else {
return returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证,认证类型有误"); return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "设备认证,认证类型有误");
} }
} }
} }
/**
* 设备简单认证
*/
private ResponseEntity simpleMqttAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) {
String[] passwordArray = mqttModel.getPassword().split("&");
if (productModel.getIsAuthorize() == 1 && passwordArray.length != 2) {
return returnUnauthorized(mqttModel, "设备简单认证,产品启用授权码后,密码格式为:密码 & 授权码");
}
String mqttPassword = passwordArray[0];
String authCode = passwordArray.length == 2 ? passwordArray[1] : "";
// 验证用户名和密码
if ((!mqttConfig.getusername().equals(mqttModel.getUserName())) || (!mqttConfig.getpassword().equals(mqttPassword))) {
return returnUnauthorized(mqttModel, "设备简单认证mqtt账号和密码与认证服务器配置不匹配");
}
// 验证授权码
if (productModel.getIsAuthorize() == 1) {
// 授权码验证和处理
String resultMessage = authCodeProcess(authCode, mqttModel, productModel);
if (!resultMessage.equals("")) {
return returnUnauthorized(mqttModel, resultMessage);
}
}
if (productModel.getDeviceId() != null && productModel.getDeviceId() != 0) {
if (productModel.getStatus() == 2) {
return returnUnauthorized(mqttModel, "设备简单认证,设备处于禁用状态");
}
log.info("-----------设备简单认证成功,clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
} else {
// 自动添加设备
int result = deviceService.insertDeviceAuto(mqttModel.getDeviceNumber(), mqttModel.getUserId(), mqttModel.getProductId());
if (result == 1) {
log.info("-----------设备简单认证成功,并自动添加设备到系统clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
}
return returnUnauthorized(mqttModel, "设备简单认证,自动添加设备失败");
}
}
/**
* 设备加密认证
*
* @return
*/
private ResponseEntity encryptAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) throws Exception {
String decryptPassword = AESUtils.decrypt(mqttModel.getPassword(), productModel.getMqttSecret());
if (decryptPassword == null || decryptPassword.equals("")) {
return returnUnauthorized(mqttModel, "设备加密认证mqtt密码解密失败");
}
String[] passwordArray = decryptPassword.split("&");
if (passwordArray.length != 2 && passwordArray.length != 3) {
// 密码加密格式 password & expireTime (& authCode 可选)
return returnUnauthorized(mqttModel, "设备加密认证mqtt密码加密格式为密码 & 过期时间 & 授权码,其中授权码为可选");
}
String mqttPassword = passwordArray[0];
Long expireTime = Long.valueOf(passwordArray[1]);
String authCode = passwordArray.length == 3 ? passwordArray[2] : "";
// 验证用户名
if (!mqttModel.getUserName().equals(productModel.getMqttAccount())) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt用户名错误");
}
// 验证密码
if (!mqttPassword.equals(productModel.getMqttPassword())) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt密码错误");
}
// 验证过期时间
if (expireTime < System.currentTimeMillis()) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt密码已过期");
}
// 验证授权码
if (productModel.getIsAuthorize() == 1) {
// 授权码验证和处理
String resultMessage = authCodeProcess(authCode, mqttModel, productModel);
if (!resultMessage.equals("")) {
return returnUnauthorized(mqttModel, resultMessage);
}
}
// 设备状态验证 1-未激活2-禁用3-在线4-离线)
if (productModel.getDeviceId() != null && productModel.getDeviceId() != 0) {
if (productModel.getStatus() == 2) {
return returnUnauthorized(mqttModel, "设备加密认证,设备处于禁用状态");
}
log.info("-----------设备加密认证成功,clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
} else {
// 自动添加设备
int result = deviceService.insertDeviceAuto(mqttModel.getDeviceNumber(), mqttModel.getUserId(), mqttModel.getProductId());
if (result == 1) {
log.info("-----------设备加密认证成功,并自动添加设备到系统clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
}
return returnUnauthorized(mqttModel, "设备加密认证,自动添加设备失败");
}
}
/**
* 授权码认证和处理
*/
private String authCodeProcess(String authCode, MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) {
String message = "";
if (authCode.equals("")) {
return message = "设备认证,设备授权码不能为空";
}
// 查询授权码是否存在
ProductAuthorize authorize = productAuthorizeMapper.selectFirstAuthorizeByAuthorizeCode(new ProductAuthorize(authCode, productModel.getProductId()));
if (authorize == null) {
message = "设备认证,设备授权码错误";
return message;
}
if (authorize.getSerialNumber() != null && !authorize.getSerialNumber().equals("")) {
// 授权码已关联设备
if (!authorize.getSerialNumber().equals( productModel.getSerialNumber())) {
message = "设备认证,设备授权码已经分配给其他设备";
return message;
}
} else {
// 授权码未关联设备
authorize.setSerialNumber(productModel.getSerialNumber());
authorize.setDeviceId(productModel.getDeviceId());
authorize.setUserId(mqttModel.getUserId());
authorize.setUserName("");
authorize.setUpdateTime(DateUtils.getNowDate());
int result = productAuthorizeMapper.updateProductAuthorize(authorize);
if (result != 1) {
message = "设备认证,设备授权码关联失败";
return message;
}
}
return message;
}
/**
* 返回认证信息
*/
private ResponseEntity returnUnauthorized(MqttAuthenticationModel mqttModel, String message) {
log.warn("认证失败:" + message
+ "\nclientid:" + mqttModel.getClientId()
+ "\nusername:" + mqttModel.getUserName()
+ "\npassword:" + mqttModel.getPassword());
return ResponseEntity.status(401).body("Unauthorized");
}
@ApiOperation("mqtt钩子处理") @ApiOperation("mqtt钩子处理")
@PostMapping("/mqtt/webhook") @PostMapping("/mqtt/webhook")
@@ -317,7 +168,6 @@ public class ToolController extends BaseController {
if (model.getClientid().startsWith("server") || model.getClientid().startsWith("web") || model.getClientid().startsWith("phone")) { if (model.getClientid().startsWith("server") || model.getClientid().startsWith("web") || model.getClientid().startsWith("phone")) {
return; return;
} }
// 设备端认证加密认证E和简单认证S配置的账号密码认证 // 设备端认证加密认证E和简单认证S配置的账号密码认证
String[] clientArray = model.getClientid().split("&"); String[] clientArray = model.getClientid().split("&");
String authType = clientArray[0]; String authType = clientArray[0];

View File

@@ -1,6 +1,12 @@
package com.ruoyi.iot.service; package com.ruoyi.iot.service;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.iot.domain.ProductAuthorize;
import com.ruoyi.iot.model.MqttAuthenticationModel;
import com.ruoyi.iot.model.ProductAuthenticateModel;
import com.ruoyi.iot.model.RegisterUserInput; import com.ruoyi.iot.model.RegisterUserInput;
import com.ruoyi.iot.util.AESUtils;
import org.springframework.http.ResponseEntity;
/** /**
* *
@@ -18,4 +24,22 @@ public interface IToolService
* 生成随机数字和字母 * 生成随机数字和字母
*/ */
public String getStringRandom(int length); public String getStringRandom(int length);
/**
* 设备简单认证
*/
public ResponseEntity simpleMqttAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel);
/**
* 设备加密认证
*
* @return
*/
public ResponseEntity encryptAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel)throws Exception;
/**
* 返回认证信息
*/
public ResponseEntity returnUnauthorized(MqttAuthenticationModel mqttModel, String message);
} }

View File

@@ -6,19 +6,31 @@ import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException; import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException; import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager; import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.iot.domain.ProductAuthorize;
import com.ruoyi.iot.mapper.ProductAuthorizeMapper;
import com.ruoyi.iot.model.MqttAuthenticationModel;
import com.ruoyi.iot.model.ProductAuthenticateModel;
import com.ruoyi.iot.model.RegisterUserInput; import com.ruoyi.iot.model.RegisterUserInput;
import com.ruoyi.iot.service.IDeviceService;
import com.ruoyi.iot.service.IToolService; import com.ruoyi.iot.service.IToolService;
import com.ruoyi.iot.util.AESUtils;
import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService; import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.iot.mqtt.MqttConfig;
import java.util.Random; import java.util.Random;
@@ -30,6 +42,8 @@ import java.util.Random;
@Service @Service
public class ToolServiceImpl implements IToolService public class ToolServiceImpl implements IToolService
{ {
private static final Logger log = LoggerFactory.getLogger(ToolServiceImpl.class);
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
@@ -42,6 +56,16 @@ public class ToolServiceImpl implements IToolService
@Autowired @Autowired
private SysUserMapper userMapper; private SysUserMapper userMapper;
@Autowired
private ProductAuthorizeMapper productAuthorizeMapper;
@Autowired
private MqttConfig mqttConfig;
@Autowired
@Lazy
private IDeviceService deviceService;
/** /**
* 生成随机数字和字母 * 生成随机数字和字母
*/ */
@@ -170,4 +194,149 @@ public class ToolServiceImpl implements IToolService
throw new CaptchaException(); throw new CaptchaException();
} }
} }
/**
* 设备简单认证
*/
@Override
public ResponseEntity simpleMqttAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) {
String[] passwordArray = mqttModel.getPassword().split("&");
if (productModel.getIsAuthorize() == 1 && passwordArray.length != 2) {
return returnUnauthorized(mqttModel, "设备简单认证,产品启用授权码后,密码格式为:密码 & 授权码");
}
String mqttPassword = passwordArray[0];
String authCode = passwordArray.length == 2 ? passwordArray[1] : "";
// 验证用户名和密码
if ((!mqttConfig.getusername().equals(mqttModel.getUserName())) || (!mqttConfig.getpassword().equals(mqttPassword))) {
return returnUnauthorized(mqttModel, "设备简单认证mqtt账号和密码与认证服务器配置不匹配");
}
// 验证授权码
if (productModel.getIsAuthorize() == 1) {
// 授权码验证和处理
String resultMessage = authCodeProcess(authCode, mqttModel, productModel);
if (!resultMessage.equals("")) {
return returnUnauthorized(mqttModel, resultMessage);
}
}
if (productModel.getDeviceId() != null && productModel.getDeviceId() != 0) {
if (productModel.getStatus() == 2) {
return returnUnauthorized(mqttModel, "设备简单认证,设备处于禁用状态");
}
log.info("-----------设备简单认证成功,clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
} else {
// 自动添加设备
int result = deviceService.insertDeviceAuto(mqttModel.getDeviceNumber(), mqttModel.getUserId(), mqttModel.getProductId());
if (result == 1) {
log.info("-----------设备简单认证成功,并自动添加设备到系统clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
}
return returnUnauthorized(mqttModel, "设备简单认证,自动添加设备失败");
}
}
/**
* 设备加密认证
*
* @return
*/
@Override
public ResponseEntity encryptAuthentication(MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) throws Exception {
String decryptPassword = AESUtils.decrypt(mqttModel.getPassword(), productModel.getMqttSecret());
if (decryptPassword == null || decryptPassword.equals("")) {
return returnUnauthorized(mqttModel, "设备加密认证mqtt密码解密失败");
}
String[] passwordArray = decryptPassword.split("&");
if (passwordArray.length != 2 && passwordArray.length != 3) {
// 密码加密格式 password & expireTime (& authCode 可选)
return returnUnauthorized(mqttModel, "设备加密认证mqtt密码加密格式为密码 & 过期时间 & 授权码,其中授权码为可选");
}
String mqttPassword = passwordArray[0];
Long expireTime = Long.valueOf(passwordArray[1]);
String authCode = passwordArray.length == 3 ? passwordArray[2] : "";
// 验证用户名
if (!mqttModel.getUserName().equals(productModel.getMqttAccount())) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt用户名错误");
}
// 验证密码
if (!mqttPassword.equals(productModel.getMqttPassword())) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt密码错误");
}
// 验证过期时间
if (expireTime < System.currentTimeMillis()) {
return returnUnauthorized(mqttModel, "设备加密认证设备mqtt密码已过期");
}
// 验证授权码
if (productModel.getIsAuthorize() == 1) {
// 授权码验证和处理
String resultMessage = authCodeProcess(authCode, mqttModel, productModel);
if (!resultMessage.equals("")) {
return returnUnauthorized(mqttModel, resultMessage);
}
}
// 设备状态验证 1-未激活2-禁用3-在线4-离线)
if (productModel.getDeviceId() != null && productModel.getDeviceId() != 0) {
if (productModel.getStatus() == 2) {
return returnUnauthorized(mqttModel, "设备加密认证,设备处于禁用状态");
}
log.info("-----------设备加密认证成功,clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
} else {
// 自动添加设备
int result = deviceService.insertDeviceAuto(mqttModel.getDeviceNumber(), mqttModel.getUserId(), mqttModel.getProductId());
if (result == 1) {
log.info("-----------设备加密认证成功,并自动添加设备到系统clientId:" + mqttModel.getClientId() + "---------------");
return ResponseEntity.ok().body("ok");
}
return returnUnauthorized(mqttModel, "设备加密认证,自动添加设备失败");
}
}
/**
* 授权码认证和处理
*/
private String authCodeProcess(String authCode, MqttAuthenticationModel mqttModel, ProductAuthenticateModel productModel) {
String message = "";
if (authCode.equals("")) {
return message = "设备认证,设备授权码不能为空";
}
// 查询授权码是否存在
ProductAuthorize authorize = productAuthorizeMapper.selectFirstAuthorizeByAuthorizeCode(new ProductAuthorize(authCode, productModel.getProductId()));
if (authorize == null) {
message = "设备认证,设备授权码错误";
return message;
}
if (authorize.getSerialNumber() != null && !authorize.getSerialNumber().equals("")) {
// 授权码已关联设备
if (!authorize.getSerialNumber().equals( productModel.getSerialNumber())) {
message = "设备认证,设备授权码已经分配给其他设备";
return message;
}
} else {
// 授权码未关联设备
authorize.setSerialNumber(productModel.getSerialNumber());
authorize.setDeviceId(productModel.getDeviceId());
authorize.setUserId(mqttModel.getUserId());
authorize.setUserName("");
authorize.setUpdateTime(DateUtils.getNowDate());
int result = productAuthorizeMapper.updateProductAuthorize(authorize);
if (result != 1) {
message = "设备认证,设备授权码关联失败";
return message;
}
}
return message;
}
/**
* 返回认证信息
*/
@Override
public ResponseEntity returnUnauthorized(MqttAuthenticationModel mqttModel, String message) {
log.warn("认证失败:" + message
+ "\nclientid:" + mqttModel.getClientId()
+ "\nusername:" + mqttModel.getUserName()
+ "\npassword:" + mqttModel.getPassword());
return ResponseEntity.status(401).body("Unauthorized");
}
} }