瀏覽代碼

增加操作设备权限校验

yangxiaokun 4 年之前
父節點
當前提交
d59beba37c

+ 6 - 2
src/main/java/com/zy/bms/common/ServerResponse.java

@@ -36,11 +36,11 @@ public class ServerResponse implements Serializable {
         return new ServerResponse(ResponseCode.ERROR.code, null, ResponseCode.ERROR.msg);
     }
 
-    public static ServerResponse createByErrorMsg(String msg) {
+    public static ServerResponse createByError(String msg) {
         return new ServerResponse(ResponseCode.ERROR.code, null, msg);
     }
 
-    public static ServerResponse createByWarningMsg(String msg) {
+    public static ServerResponse createByWarning(String msg) {
         return new ServerResponse(ResponseCode.WARNING.code, null, msg);
     }
 
@@ -48,6 +48,10 @@ public class ServerResponse implements Serializable {
         return new ServerResponse(ResponseCode.AUTHOR.code, null, ResponseCode.AUTHOR.msg);
     }
 
+    public static ServerResponse createByIllegal() {
+        return new ServerResponse(ResponseCode.ILLEGAL.code, null, ResponseCode.ILLEGAL.msg);
+    }
+
     private ServerResponse(int status, Object data, String msg) {
         this.status = status;
         this.msg = msg;

+ 34 - 0
src/main/java/com/zy/bms/common/controller/BaseController.java

@@ -0,0 +1,34 @@
+package com.zy.bms.common.controller;
+
+import com.zy.bms.common.exception.ApiRuntimeException;
+import com.zy.bms.utils.AesUtils;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * controller公共类提出
+ *
+ * @author chenyi
+ * date: create on 2019/6/8
+ */
+@Component
+public class BaseController {
+    private HttpServletRequest request;
+
+    //获取登录信息
+    @ModelAttribute
+    public void setModelAttribute(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    /**
+     * 获取用户ID
+     */
+    public String getUserId() {
+        String userId = AesUtils.decrypt(request.getHeader("user"));
+        if (userId == null) throw new ApiRuntimeException("未登录");
+        return userId;
+    }
+}

+ 2 - 2
src/main/java/com/zy/bms/common/controller/ExceptionController.java

@@ -21,7 +21,7 @@ public class ExceptionController {
      */
     @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
     public ServerResponse MethodArgumentTypeMismatchExceptionHandler() {
-        return ServerResponse.createByErrorMsg("参数类型错误");
+        return ServerResponse.createByError("参数类型错误");
     }
 
     /**
@@ -29,6 +29,6 @@ public class ExceptionController {
      */
     @ExceptionHandler(value = ApiRuntimeException.class)
     public ServerResponse ApiRuntimeExceptionHandler(ApiRuntimeException apiRuntimeException) {
-        return ServerResponse.createByErrorMsg(apiRuntimeException.getMsg());
+        return ServerResponse.createByError(apiRuntimeException.getMsg());
     }
 }

+ 1 - 0
src/main/java/com/zy/bms/common/enums/ResponseCode.java

@@ -7,6 +7,7 @@ public enum ResponseCode {
     SUCCESS(200, "SUCCESS"),//成功
     WARNING(300, "WARNING"),//警告,不进入成功回调函数,直接alert
     AUTHOR(401, "Forbidden"),//没有权限,跳转登录
+    ILLEGAL(402, "illegal"),//非法请求
     ERROR(500, "ERROR");//服务器异常
     public final int code;
     public final String msg;

+ 8 - 1
src/main/java/com/zy/bms/config/mqtt/MqttCallbackHandler.java

@@ -121,6 +121,7 @@ public class MqttCallbackHandler {
         device.setClientId(clientId);
         device.setPassword(MD5Util.MD5Encode(clientId));
         device.setGroupId(1);
+        device.setStatus(1);
         deviceService.save(device);
         SetBase setBase = new SetBase();
         setBase.setDeviceId(device.getClientId());
@@ -167,7 +168,13 @@ public class MqttCallbackHandler {
         MqttLog mqttLog = new MqttLog();
         mqttLog.setTopic(topic);
         mqttLog.setTag(0);
-        mqttLog.setDeviceId(topic.split("/")[1]);
+        //设备注册报文
+        if (topic.equals("$regdtx")) {
+            MqttMsgDto msgObject = JSON.parseObject(payload, MqttMsgDto.class);
+            mqttLog.setDeviceId(msgObject.getString("regnum￿￿"));
+        } else {
+            mqttLog.setDeviceId(topic.split("/")[1]);
+        }
         mqttLog.setContent(payload);
         mqttLogService.save(mqttLog);
     }

+ 1 - 1
src/main/java/com/zy/bms/config/mqtt/MqttConsumerCfg.java

@@ -31,7 +31,7 @@ public class MqttConsumerCfg {
     private MqttPahoClientFactory mqttClientFactory;
 
     //默认监听主题
-    private final String[] defaultTopic = new String[]{"$regdtx", "$dtx/#", "$drx/#"};
+    private final String[] defaultTopic = new String[]{"$regdtx", "$dtx/#"};
 
     /**
      * MQTT 消息订阅绑定(消费者)

+ 8 - 4
src/main/java/com/zy/bms/controller/DeviceController.java

@@ -1,8 +1,9 @@
 package com.zy.bms.controller;
 
-import com.zy.bms.common.exception.ApiRuntimeException;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.common.ServerResponse;
 import com.zy.bms.service.DeviceService;
+import com.zy.bms.service.RelationService;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
@@ -17,10 +18,12 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/device")
-public class DeviceController {
+public class DeviceController extends BaseController {
 
     @Resource
     private DeviceService deviceService;
+    @Resource
+    private RelationService relationService;
 
     /**
      * 更新设备名称
@@ -30,9 +33,10 @@ public class DeviceController {
      */
     @PostMapping("updateName.do")
     public ServerResponse updateName(String num, String name) {
-        if (!deviceService.updateName(num, name)) {
-            throw new ApiRuntimeException("更新设备名称失败");
+        if (!relationService.checkDeviceIsBelongByNum(getUserId(), num)) {
+            return ServerResponse.createByIllegal();
         }
+        deviceService.updateName(num, name);
         return ServerResponse.createBySuccess();
     }
 }

+ 12 - 12
src/main/java/com/zy/bms/controller/IdiomsController.java

@@ -1,7 +1,7 @@
 package com.zy.bms.controller;
 
 import com.zy.bms.common.ServerResponse;
-import com.zy.bms.model.UserIdioms;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.service.IdiomsService;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -18,37 +18,37 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/idioms")
-public class IdiomsController {
+public class IdiomsController extends BaseController {
 
     @Resource
     IdiomsService userIdiomsService;
 
     /**
      * 通过用户ID 查询用户常用语
-     *
-     * @param userId 用户ID
      */
     @GetMapping("getList.do")
-    public ServerResponse getList(String userId) {
-        return ServerResponse.createBySuccess(userIdiomsService.getListByUserId(userId));
+    public ServerResponse getList() {
+        return ServerResponse.createBySuccess(userIdiomsService.getListByUserId(getUserId()));
     }
 
     /**
      * 添加常用语
      */
     @PostMapping("save.do")
-    public ServerResponse save(UserIdioms entity) {
-        if (userIdiomsService.countByUserId(entity.getUserId()) > 10) {
-            return ServerResponse.createByWarningMsg("最多添加十条常用语");
+    public ServerResponse save(String content) {
+        String userId = getUserId();
+        if (userIdiomsService.countByUserId(getUserId()) > 10) {
+            return ServerResponse.createByWarning("最多添加十条常用语");
         }
-        return ServerResponse.createBySuccess(userIdiomsService.save(entity));
+        userIdiomsService.saveEntity(userId, content);
+        return ServerResponse.createBySuccess();
     }
 
     /**
      * 通过ID删除常用语
      */
     @PostMapping("delById.do")
-    public ServerResponse delById(Integer id, String userId) {
-        return ServerResponse.createBySuccess(userIdiomsService.delById(id, userId));
+    public ServerResponse delById(Integer id) {
+        return ServerResponse.createBySuccess(userIdiomsService.delById(id, getUserId()));
     }
 }

+ 8 - 1
src/main/java/com/zy/bms/controller/LocationController.java

@@ -1,8 +1,10 @@
 package com.zy.bms.controller;
 
 import com.zy.bms.common.ServerResponse;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.common.io.wechat.DeviceHistoryIO;
 import com.zy.bms.service.DeviceLocationService;
+import com.zy.bms.service.RelationService;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -18,16 +20,21 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/location")
-public class LocationController {
+public class LocationController extends BaseController {
 
     @Resource
     private DeviceLocationService locationService;
+    @Resource
+    private RelationService relationService;
 
     /**
      * 通过设备ID获取最新的定位信息
      */
     @GetMapping("getLocation.do")
     public ServerResponse getLocation(String deviceId) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), deviceId)) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(locationService.getLocation(deviceId));
     }
 

+ 8 - 8
src/main/java/com/zy/bms/controller/RelationController.java

@@ -2,7 +2,7 @@ package com.zy.bms.controller;
 
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.zy.bms.common.ServerResponse;
-import com.zy.bms.common.io.wechat.UserDeviceRelationIO;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.model.UserDeviceRelation;
 import com.zy.bms.service.DeviceService;
 import com.zy.bms.service.RelationService;
@@ -21,7 +21,7 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/relation")
-public class RelationController {
+public class RelationController extends BaseController {
 
     @Resource
     private RelationService relationService;
@@ -33,12 +33,12 @@ public class RelationController {
      * 添加绑定关系
      */
     @PostMapping("bind.do")
-    public ServerResponse bind(UserDeviceRelationIO io) {
-        if (deviceService.getByNum(io.getDeviceNum()) == null)
-            return ServerResponse.createByWarningMsg("无效设备码!");
-        if (relationService.isBind(io.getDeviceNum()))
-            return ServerResponse.createByWarningMsg("该设备已经有用户绑定!");
-        relationService.saveEntity(io);
+    public ServerResponse bind(String deviceNum, String deviceName) {
+        if (deviceService.getByNum(deviceNum) == null)
+            return ServerResponse.createByWarning("无效设备码!");
+        if (relationService.checkDeviceIsBind(deviceNum))
+            return ServerResponse.createByWarning("该设备已经有用户绑定!");
+        relationService.saveEntity(getUserId(), deviceNum, deviceName);
         return ServerResponse.createBySuccess();
     }
 

+ 22 - 7
src/main/java/com/zy/bms/controller/SetController.java

@@ -1,7 +1,9 @@
 package com.zy.bms.controller;
 
 import com.zy.bms.common.ServerResponse;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.common.io.wechat.*;
+import com.zy.bms.service.RelationService;
 import com.zy.bms.service.SetService;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -17,17 +19,30 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/set")
-public class SetController {
+public class SetController extends BaseController {
 
     @Resource
     private SetService setService;
+    @Resource
+    private RelationService relationService;
+
+    /**
+     * 校验设备是否是该用户的设备
+     */
+    public boolean verify(SimpleSetIO io) {
+        boolean flag = relationService.checkDeviceIsBelongByDeviceId(getUserId(), io.getDeviceId());
+        if (!flag) {
+            System.out.println("非法请求----" + getUserId() + "-----" + io.getDeviceId());
+        }
+        return flag;
+    }
 
     /**
      * 设置音量
      */
     @PostMapping("volume.do")
     public ServerResponse setVolume(VolumeSetIO io) {
-        setService.setVolume(io);
+        if (verify(io)) setService.setVolume(io);
         return ServerResponse.createBySuccess();
     }
 
@@ -36,7 +51,7 @@ public class SetController {
      */
     @PostMapping("gpsRate.do")
     public ServerResponse gpsRate(GpsRateSetIO io) {
-        setService.setGpsRate(io);
+        if (verify(io)) setService.setGpsRate(io);
         return ServerResponse.createBySuccess();
     }
 
@@ -47,7 +62,7 @@ public class SetController {
      */
     @PostMapping("autoAnswer.do")
     public ServerResponse setAutoAnswer(AnswerSetIO io) {
-        setService.setAutoAnswer(io);
+        if (verify(io)) setService.setAutoAnswer(io);
         return ServerResponse.createBySuccess();
     }
 
@@ -56,7 +71,7 @@ public class SetController {
      */
     @PostMapping("news.do")
     public ServerResponse setNews(NewsSetIO io) {
-        setService.setNews(io);
+        if (verify(io)) setService.setNews(io);
         return ServerResponse.createBySuccess();
     }
 
@@ -65,7 +80,7 @@ public class SetController {
      */
     @PostMapping("sos.do")
     public ServerResponse setSOS(SosSetIO io) {
-        setService.setSOS(io);
+        if (verify(io)) setService.setSOS(io);
         return ServerResponse.createBySuccess();
     }
 
@@ -74,7 +89,7 @@ public class SetController {
      */
     @PostMapping("continue.do")
     public ServerResponse setContinue(ContinueSetIO io) {
-        setService.setContinue(io);
+        if (verify(io)) setService.setContinue(io);
         return ServerResponse.createBySuccess();
     }
 }

+ 20 - 1
src/main/java/com/zy/bms/controller/SetInfoController.java

@@ -1,9 +1,11 @@
 package com.zy.bms.controller;
 
 import com.zy.bms.common.ServerResponse;
+import com.zy.bms.common.controller.BaseController;
 import com.zy.bms.common.io.CallRecordsIO;
 import com.zy.bms.common.io.NewsIO;
 import com.zy.bms.service.CallRecordsService;
+import com.zy.bms.service.RelationService;
 import com.zy.bms.service.SetBaseService;
 import com.zy.bms.service.SetNewsService;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -20,7 +22,7 @@ import javax.annotation.Resource;
  */
 @RestController
 @RequestMapping("zy4g/api/setInfo")
-public class SetInfoController {
+public class SetInfoController extends BaseController {
 
     @Resource
     private SetBaseService setBaseService;
@@ -28,6 +30,8 @@ public class SetInfoController {
     private CallRecordsService callRecordsService;
     @Resource
     private SetNewsService setNewsService;
+    @Resource
+    private RelationService relationService;
 
     /**
      * 查询设备的音量设置
@@ -37,6 +41,9 @@ public class SetInfoController {
      */
     @GetMapping("volume.do")
     public ServerResponse volume(String deviceId) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), deviceId)) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(setBaseService.getVolumeSet(deviceId));
     }
 
@@ -48,6 +55,9 @@ public class SetInfoController {
      */
     @GetMapping("other.do")
     public ServerResponse other(String deviceId) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), deviceId)) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(setBaseService.getOtherSet(deviceId));
     }
 
@@ -58,6 +68,9 @@ public class SetInfoController {
      */
     @GetMapping("sos.do")
     public ServerResponse sos(String deviceId) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), deviceId)) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(setBaseService.getSosSet(deviceId));
     }
 
@@ -66,6 +79,9 @@ public class SetInfoController {
      */
     @GetMapping("callRecords.do")
     public ServerResponse callRecords(CallRecordsIO io) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), io.getDeviceId())) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(callRecordsService.getListPage(io));
     }
 
@@ -74,6 +90,9 @@ public class SetInfoController {
      */
     @GetMapping("news.do")
     public ServerResponse news(NewsIO io) {
+        if (!relationService.checkDeviceIsBelongByDeviceId(getUserId(), io.getDeviceId())) {
+            return ServerResponse.createByIllegal();
+        }
         return ServerResponse.createBySuccess(setNewsService.getListPage(io));
     }
 }

+ 2 - 1
src/main/java/com/zy/bms/controller/UserController.java

@@ -3,6 +3,7 @@ package com.zy.bms.controller;
 import com.zy.bms.common.ServerResponse;
 import com.zy.bms.model.User;
 import com.zy.bms.service.UserService;
+import com.zy.bms.utils.AesUtils;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
@@ -35,6 +36,6 @@ public class UserController {
         if (userService.getByOpenId(openId) == null) {
             userService.save(new User(openId));
         }
-        return ServerResponse.createBySuccess(openId);
+        return ServerResponse.createBySuccess(AesUtils.encrypt(openId));
     }
 }

+ 2 - 2
src/main/java/com/zy/bms/controller/pc/AdminController.java

@@ -37,8 +37,8 @@ public class AdminController {
     public ServerResponse login(String username, String password) {
         password = MD5Util.MD5Encode(password);
         Admin admin = adminService.getByUsername(username);
-        if (admin == null) return ServerResponse.createByWarningMsg("用户不存在");
-        if (!admin.getPassword().equals(password)) return ServerResponse.createByWarningMsg("密码错误");
+        if (admin == null) return ServerResponse.createByWarning("用户不存在");
+        if (!admin.getPassword().equals(password)) return ServerResponse.createByWarning("密码错误");
         // 返回 token 和 昵称
         Map<String, String> result = new HashMap<>();
         result.put("token", sessionManager.generateToken(admin));

+ 1 - 1
src/main/java/com/zy/bms/mapper/DeviceMapper.java

@@ -39,5 +39,5 @@ public interface DeviceMapper extends BaseMapper<Device> {
      * @param num  设备号
      * @param name 名称
      */
-    int updateName(@Param("num") String num, @Param("name") String name);
+    void updateName(@Param("num") String num, @Param("name") String name);
 }

+ 23 - 0
src/main/java/com/zy/bms/mapper/UserDeviceRelationMapper.java

@@ -25,4 +25,27 @@ public interface UserDeviceRelationMapper extends BaseMapper<UserDeviceRelation>
      * @param userId 用户ID
      */
     List<DeviceRelationVo> getListByUserId(@Param("userId") String userId);
+
+    /**
+     * 查询设备是否有绑定用户
+     *
+     * @param deviceNum 设备号
+     */
+    int checkDeviceIsBind(@Param("deviceNum") String deviceNum);
+
+    /**
+     * 查询设备是否属于某用户
+     *
+     * @param userId    用户ID
+     * @param deviceNum 设备号
+     */
+    int checkDeviceIsBelongByNum(@Param("userId") String userId, @Param("deviceNum") String deviceNum);
+
+    /**
+     * 查询设备是否属于某用户
+     *
+     * @param userId   用户ID
+     * @param deviceId 设备ID
+     */
+    int checkDeviceIsBelongByDeviceId(@Param("userId") String userId, @Param("deviceNum") String deviceId);
 }

+ 2 - 2
src/main/java/com/zy/bms/service/DeviceService.java

@@ -69,8 +69,8 @@ public class DeviceService extends ServiceImpl<DeviceMapper, Device> {
      * @param num  设备号
      * @param name 名称
      */
-    public boolean updateName(String num, String name) {
-        return baseMapper.updateName(num, name) > 0;
+    public void updateName(String num, String name) {
+        baseMapper.updateName(num, name);
     }
 
     /**

+ 13 - 0
src/main/java/com/zy/bms/service/IdiomsService.java

@@ -17,6 +17,19 @@ import java.util.List;
 @Service
 public class IdiomsService extends ServiceImpl<IdiomsMapper, UserIdioms> {
 
+    /**
+     * 添加常用语
+     *
+     * @param userId  用户Id
+     * @param content 常用语内容
+     */
+    public void saveEntity(String userId, String content) {
+        UserIdioms entity = new UserIdioms();
+        entity.setUserId(userId);
+        entity.setContent(content);
+        baseMapper.insert(entity);
+    }
+
     /**
      * 通过用户ID 查询用户常用语
      *

+ 30 - 12
src/main/java/com/zy/bms/service/RelationService.java

@@ -28,16 +28,16 @@ public class RelationService extends ServiceImpl<UserDeviceRelationMapper, UserD
     /**
      * 添加绑定关系
      *
-     * @param io 实体类
+     * @param userId     用户ID
+     * @param deviceNum  设备随机码
+     * @param deviceName 设备名称
      */
-    public void saveEntity(UserDeviceRelationIO io) {
-        QueryWrapper<UserDeviceRelation> queryWrapper = new QueryWrapper<>();
-        queryWrapper.eq("userId", io.getUserId()).eq("isDefault", 1);
-        int isDefault = baseMapper.selectOne(queryWrapper) == null ? 1 : 0;
-        UserDeviceRelation entity = BeanUtil.cast(io, UserDeviceRelation.class);
-        entity.setIsDefault(isDefault);
+    public void saveEntity(String userId, String deviceNum, String deviceName) {
+        UserDeviceRelation entity = new UserDeviceRelation();
+        entity.setUserId(userId);
+        entity.setDeviceNum(deviceNum);
         baseMapper.insert(entity);
-        deviceService.updateName(io.getDeviceNum(), io.getDeviceName());
+        deviceService.updateName(deviceNum, deviceName);
     }
 
     /**
@@ -66,9 +66,27 @@ public class RelationService extends ServiceImpl<UserDeviceRelationMapper, UserD
      *
      * @param deviceNum 设备号
      */
-    public boolean isBind(String deviceNum) {
-        QueryWrapper<UserDeviceRelation> queryWrapper = new QueryWrapper<>();
-        queryWrapper.eq("deviceNum", deviceNum);
-        return baseMapper.selectCount(queryWrapper) > 0;
+    public boolean checkDeviceIsBind(String deviceNum) {
+        return baseMapper.checkDeviceIsBind(deviceNum) > 0;
+    }
+
+    /**
+     * 查询设备是否属于该用户
+     *
+     * @param userId    用户ID
+     * @param deviceNum 设备码
+     */
+    public boolean checkDeviceIsBelongByNum(String userId, String deviceNum) {
+        return baseMapper.checkDeviceIsBelongByNum(userId, deviceNum) > 0;
+    }
+
+    /**
+     * 查询设备是否属于该用户
+     *
+     * @param userId   用户ID
+     * @param deviceId 设备ID
+     */
+    public boolean checkDeviceIsBelongByDeviceId(String userId, String deviceId) {
+        return baseMapper.checkDeviceIsBelongByDeviceId(userId, deviceId) > 0;
     }
 }

+ 74 - 0
src/main/java/com/zy/bms/utils/AesUtils.java

@@ -0,0 +1,74 @@
+package com.zy.bms.utils;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.Key;
+import java.security.SecureRandom;
+import java.util.Base64;
+
+/**
+ * AES对称加密工具类
+ *
+ * @author yangxiaokun
+ */
+public class AesUtils {
+
+    private static final String KEY_ALGORITHM = "AES";
+    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
+    //进行了Base64编码的秘钥(由keyGenerate()方法生成的)
+    private static final String KEY_NUM = "6RAwrG9BcU1D1bObGGskqw==";
+
+    /**
+     * AES对称-加密操作
+     *
+     * @param data 需要进行加密的原文
+     * @return 数据密文,加密后的数据,进行了Base64的编码
+     */
+    public static String encrypt(String data) {
+        try {
+            // 转换密钥
+            Key key = new SecretKeySpec(Base64.getDecoder().decode(KEY_NUM), KEY_ALGORITHM);
+            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+            // 加密
+            cipher.init(Cipher.ENCRYPT_MODE, key);
+            byte[] result = cipher.doFinal(data.getBytes());
+            return Base64.getEncoder().encodeToString(result);
+        } catch (Exception e) {
+            return "AES";
+        }
+    }
+
+    /**
+     * @param data 需要解密的数据(数据必须是通过AES进行加密后,对加密数据Base64编码的数据)
+     * @return String 返回解密后的原文
+     */
+    public static String decrypt(String data) {
+        try {
+            // 转换密钥
+            Key key = new SecretKeySpec(Base64.getDecoder().decode(KEY_NUM), KEY_ALGORITHM);
+            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+            // 解密
+            cipher.init(Cipher.DECRYPT_MODE, key);
+            byte[] result = cipher.doFinal(Base64.getDecoder().decode(data));
+            return new String(result);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /**
+     * 生成AES的秘钥,秘钥进行了Base64编码的字符串
+     *
+     * @return 对生成的秘钥进行了Base64编码的字符串
+     */
+    public static String keyGenerate() throws Exception {
+        // 生成密钥
+        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
+        keyGenerator.init(new SecureRandom());
+        SecretKey secretKey = keyGenerator.generateKey();
+        byte[] keyBytes = secretKey.getEncoded();
+        return Base64.getEncoder().encodeToString(keyBytes);
+    }
+}

+ 22 - 0
src/main/resources/mapper/UserDeviceRelationMapping.xml

@@ -14,4 +14,26 @@
         WHERE t1.userId = #{userId}
         ORDER BY t1.isDefault DESC
     </select>
+
+    <select id="checkDeviceIsBind" resultType="java.lang.Integer">
+        SELECT IFNULL( (SELECT 1 FROM user_device_relation WHERE deviceNum = #{deviceNum} LIMIT 1) ,0)
+    </select>
+
+    <select id="checkDeviceIsBelongByNum" resultType="java.lang.Integer">
+        SELECT IFNULL( (SELECT 1 FROM user_device_relation WHERE deviceNum = #{deviceNum} AND userId=#{userId} LIMIT 1),0 )
+    </select>
+
+    <select id="checkDeviceIsBelongByDeviceId" resultType="java.lang.Integer">
+        SELECT IFNULL(
+        (
+        SELECT
+            1
+        FROM
+            zy_device t1
+        INNER JOIN
+            user_device_relation t2 ON t1.num = t2.deviceNum
+        WHERE
+            t2.deviceNum = #{deviceNum} AND t2.userId = #{userId} LIMIT 1
+        ),0)
+    </select>
 </mapper>