Browse Source

1.获取凭证,推送用户接口 增加client_id,密码加密,增加日志

S0025136190 1 year ago
parent
commit
0c02cd5d5c

+ 67 - 0
Backend/sample/src/main/java/com/dji/sample/common/util/DesUtil.java

@@ -0,0 +1,67 @@
+package com.dji.sample.common.util;
+
+import cn.hutool.core.codec.Base64;
+import cn.hutool.crypto.SecureUtil;
+import cn.hutool.crypto.symmetric.DES;
+import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
+
+import java.util.UUID;
+
+/**
+ * @description:对称加密
+ */
+public class DesUtil {
+
+    private static final String KEY = "jPQQqFT3lwg=";
+
+    /**
+     * 根据KEY生成DES
+     */
+    private static final DES DES = SecureUtil.des(SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), KEY.getBytes()).getEncoded());
+
+    /**
+     * 获取加密后信息
+     *
+     * @param plainText 明文
+     * @return 加密后信息
+     */
+    public static String getEncryptData(String plainText) {
+        return DES.encryptHex(plainText); // 加密为16进制
+    }
+
+    /**
+     * 获取解密后信息
+     *
+     * @param cipherText 密文
+     * @return 解密后信息
+     */
+    public static String getDecryptData(String cipherText) {
+        return DES.decryptStr(cipherText);
+    }
+
+    /**
+     * 生成密钥,并转为字符串,可以储存起来,解密时可直接使用
+     *
+     * @return 密钥
+     */
+    public static String getSecretKey() {
+        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue()).getEncoded(); // 随机生成秘钥
+        return Base64.encode(key);
+    }
+
+    public static void main(String[] args) {
+        String encodeData = DesUtil.getEncryptData("WosIsAC58v");
+        System.out.println(encodeData);
+        encodeData = getEncryptData("123456");
+        System.out.println(encodeData);
+        encodeData = getEncryptData("test123456");
+        System.out.println(encodeData);
+        encodeData = getEncryptData("test12345678");
+        System.out.println(encodeData);
+        String decodeData = getDecryptData("017d8a1661714a61fefb8093f6cee7c5");
+        System.out.println(decodeData);
+        System.out.println(UUID.randomUUID().toString());
+        System.out.println(UUID.randomUUID().toString());
+
+    }
+}

+ 7 - 2
Backend/sample/src/main/java/com/dji/sample/manage/controller/LoginController.java

@@ -5,6 +5,7 @@ import com.dji.sample.manage.model.dto.UserDTO;
 import com.dji.sample.manage.model.dto.UserLoginDTO;
 import com.dji.sample.manage.service.IUserService;
 import com.dji.sdk.common.HttpResultResponse;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -18,6 +19,7 @@ import java.util.Optional;
 
 import static com.dji.sample.component.AuthInterceptor.PARAM_TOKEN;
 
+@Slf4j
 @RestController
 @RequestMapping("${url.manage.prefix}${url.manage.version}")
 public class LoginController {
@@ -33,10 +35,13 @@ public class LoginController {
     }
 
     @PostMapping("/getToken")
-    public HttpResultResponse getToken(@RequestBody UserLoginDTO loginDTO) {
+    public HttpResultResponse getToken(HttpServletRequest request,@RequestBody UserLoginDTO loginDTO) {
+
         String username = loginDTO.getUsername();
         String password = loginDTO.getPassword();
-        return userService.getToken(username, password);
+        String clientId = loginDTO.getClientId();
+        log.info("==========获取Token接口调用 ClientId:"+ clientId +",username:" + username + ",password:" + password + ",IP:" + request.getRemoteAddr());
+        return userService.getToken(clientId, username, password);
     }
 
     @PostMapping("/token/refresh")

+ 6 - 16
Backend/sample/src/main/java/com/dji/sample/manage/controller/UserController.java

@@ -6,6 +6,7 @@ import com.dji.sample.manage.model.dto.UserLoginDTO;
 import com.dji.sample.manage.service.IUserService;
 import com.dji.sdk.common.HttpResultResponse;
 import com.dji.sdk.common.PaginationData;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.util.StringUtils;
 import org.springframework.web.bind.annotation.*;
@@ -14,7 +15,7 @@ import javax.servlet.http.HttpServletRequest;
 
 import static com.dji.sample.component.AuthInterceptor.TOKEN_CLAIM;
 
-
+@Slf4j
 @RestController
 @RequestMapping("${url.manage.prefix}${url.manage.version}/users")
 public class UserController {
@@ -65,23 +66,12 @@ public class UserController {
     }
 
     @PostMapping("/saveApiUser")
-    public HttpResultResponse getToken(@RequestBody UserLoginDTO loginDTO) {
+    public HttpResultResponse saveApiUser(HttpServletRequest request,@RequestBody UserLoginDTO loginDTO) {
         String username = loginDTO.getUsername();
         String password = loginDTO.getPassword();
-        String message = "";
-        if(!StringUtils.hasText(username)) {
-            message = "用户名不能为空!";
-        }
-
-        if(!StringUtils.hasText(password)) {
-            message = "密码不能为空!";
-        }
-
-        if(StringUtils.hasText(message)) {
-            return HttpResultResponse.error(message);
-        }
-        boolean isSucc = userService.saveApiUser(username, password);
-        return isSucc ? HttpResultResponse.success() : HttpResultResponse.error("添加失败");
+        String clientId = loginDTO.getClientId();
+        log.info("==========saveApiUser接口调用 ClientId:"+ clientId +",username:" + username + ",password:" + password + ",IP:" + request.getRemoteAddr());
+        return userService.saveApiUser(clientId,username, password);
     }
 
 }

+ 4 - 1
Backend/sample/src/main/java/com/dji/sample/manage/model/dto/UserLoginDTO.java

@@ -8,7 +8,8 @@ import lombok.NonNull;
 @Data
 @AllArgsConstructor
 @NoArgsConstructor
-public class UserLoginDTO {
+public class
+UserLoginDTO {
 
     @NonNull
     private String username;
@@ -20,4 +21,6 @@ public class UserLoginDTO {
     private Integer flag;
 
     private String gateway_sn;
+
+    private String clientId;
 }

+ 3 - 0
Backend/sample/src/main/java/com/dji/sample/manage/model/entity/UserEntity.java

@@ -44,4 +44,7 @@ public class UserEntity implements Serializable {
 
     @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
     private Long updateTime;
+
+    @TableField(value = "client_id")
+    private String clientId;
 }

+ 2 - 0
Backend/sample/src/main/java/com/dji/sample/manage/model/enums/UserTypeEnum.java

@@ -13,6 +13,8 @@ public enum UserTypeEnum {
 
     API(3,"API"),
 
+    CLIENT(4,"API"),
+
     UNKNOWN(-1, "Unknown");
 
     private int val;

+ 2 - 2
Backend/sample/src/main/java/com/dji/sample/manage/service/IUserService.java

@@ -26,7 +26,7 @@ public interface IUserService {
      */
     HttpResultResponse userLogin(String username, String password, Integer flag, String gatewaySn);
 
-    HttpResultResponse getToken(String username, String password);
+    HttpResultResponse getToken(String clientId,String username, String password);
 
     /**
      * Create a user object containing a new token.
@@ -42,7 +42,7 @@ public interface IUserService {
      */
     PaginationData<UserListDTO> getUsersByWorkspaceId(long page, long pageSize, String workspaceId);
 
-    Boolean saveApiUser(String username, String password);
+    HttpResultResponse saveApiUser(String clientId,String username, String password);
 
     Boolean updateUser(String workspaceId, String userId, UserListDTO user);
 

+ 69 - 20
Backend/sample/src/main/java/com/dji/sample/manage/service/impl/UserServiceImpl.java

@@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.dji.sample.common.model.CustomClaim;
+import com.dji.sample.common.util.DesUtil;
 import com.dji.sample.common.util.JwtUtil;
 import com.dji.sample.component.mqtt.config.MqttPropertyConfiguration;
 import com.dji.sample.manage.dao.IUserMapper;
@@ -23,12 +24,14 @@ import com.dji.sample.manage.service.IWorkspaceService;
 import com.dji.sdk.common.HttpResultResponse;
 import com.dji.sdk.common.Pagination;
 import com.dji.sdk.common.PaginationData;
+import org.apache.commons.codec.digest.DigestUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.StringUtils;
 
+import java.nio.charset.StandardCharsets;
 import java.time.Instant;
 import java.time.LocalDateTime;
 import java.time.ZoneId;
@@ -82,6 +85,10 @@ public class UserServiceImpl implements IUserService {
         if (flag.intValue() != userEntity.getUserType().intValue()) {
             return HttpResultResponse.error("The account type does not match.");
         }
+
+        //密码加密
+        password = DesUtil.getEncryptData(password);
+
         if (!password.equals(userEntity.getPassword())) {
             return new HttpResultResponse()
                     .setCode(HttpStatus.UNAUTHORIZED.value())
@@ -123,32 +130,28 @@ public class UserServiceImpl implements IUserService {
     }
 
     @Override
-    public HttpResultResponse getToken(String username, String password) {
-        UserEntity userEntity = this.getUserByUsername(username);
+    public HttpResultResponse getToken(String clientId, String username, String password) {
+        UserEntity userEntity = this.getClientUser(clientId);
         if (userEntity == null) {
             return new HttpResultResponse()
                     .setCode(HttpStatus.UNAUTHORIZED.value())
-                    .setMessage("invalid username");
+                    .setMessage("clientId不存在");
         }
-        if (UserTypeEnum.API.getVal() != userEntity.getUserType().intValue()) {
-            return HttpResultResponse.error("The account type does not match.");
-        }
-        if (!password.equals(userEntity.getPassword())) {
-            return new HttpResultResponse()
-                    .setCode(HttpStatus.UNAUTHORIZED.value())
-                    .setMessage("invalid password");
+        if (UserTypeEnum.CLIENT.getVal() != userEntity.getUserType().intValue()) {
+            return HttpResultResponse.error("用户类型不匹配");
         }
 
-        Optional<WorkspaceDTO> workspaceOpt = workspaceService.getWorkspaceByWorkspaceId(userEntity.getWorkspaceId());
-        if (workspaceOpt.isEmpty()) {
+        //密码加密
+        String encryptPsw = DesUtil.getEncryptData(password);
+        if (!encryptPsw.equals(userEntity.getPassword()) || !username.equals(userEntity.getUsername())) {
             return new HttpResultResponse()
                     .setCode(HttpStatus.UNAUTHORIZED.value())
-                    .setMessage("invalid workspace id:" + userEntity.getWorkspaceId());
+                    .setMessage("用户名或密码不匹配");
         }
 
         CustomClaim customClaim = new CustomClaim(userEntity.getUserId(),
                 userEntity.getUsername(), userEntity.getUserType(),
-                workspaceOpt.get().getWorkspaceId());
+                "");
 
         // create token
         String token = JwtUtil.createToken(customClaim.convertToMap());
@@ -196,23 +199,57 @@ public class UserServiceImpl implements IUserService {
     }
 
     @Override
-    public Boolean saveApiUser(String username,String password) {
+    public HttpResultResponse saveApiUser(String clientId, String username, String password) {
+        if(!StringUtils.hasText(clientId)) {
+            return new HttpResultResponse()
+                    .setCode(HttpStatus.UNAUTHORIZED.value())
+                    .setMessage("clientId不能为空");
+        }
+
+        UserEntity userEntity = this.getClientUser(clientId);
+        if (userEntity == null) {
+            return new HttpResultResponse()
+                    .setCode(HttpStatus.UNAUTHORIZED.value())
+                    .setMessage("clientId不存在");
+        }
+
         if(!StringUtils.hasText(username)) {
-            throw new RuntimeException("用户名不能为空!");
+            return new HttpResultResponse()
+                    .setCode(HttpStatus.BAD_REQUEST.value())
+                    .setMessage("用户名不能为空");
         }
 
         if(!StringUtils.hasText(password)) {
-            throw new RuntimeException("密码不能为空!");
+            return new HttpResultResponse()
+                    .setCode(HttpStatus.BAD_REQUEST.value())
+                    .setMessage("密码不能为空");
         }
+        //密码加密
+        String encryptPsw = DesUtil.getEncryptData(password);
+
         long curTime = System.currentTimeMillis();
-        return mapper.insert(UserEntity.builder().
+        userEntity = UserEntity.builder().
                 userId(UUID.randomUUID().toString())
                 .username(username)
-                .password(password)
+                .password(encryptPsw)
                 .userType(UserTypeEnum.API.getVal())
                 .createTime(curTime)
                 .updateTime(curTime)
-                .build()) > 0;
+                .clientId(clientId)
+                .build();
+        UserEntity apiUser = getApiUser(clientId);
+        if(apiUser == null) {
+            int cnt = mapper.insert(userEntity);
+            return cnt > 0 ? HttpResultResponse.success():HttpResultResponse.error("添加失败");
+        } else {
+            userEntity.setUsername(username);
+            userEntity.setPassword(encryptPsw);
+            userEntity.setUpdateTime(System.currentTimeMillis());
+            int cnt = mapper.update(userEntity, new LambdaUpdateWrapper<UserEntity>()
+                    .eq(UserEntity::getClientId, clientId)
+                    .eq(UserEntity::getUserId, userEntity.getUserId()));
+            return cnt > 0 ? HttpResultResponse.success():HttpResultResponse.error("更新失败");
+        }
     }
 
     @Override
@@ -282,6 +319,18 @@ public class UserServiceImpl implements IUserService {
                 .eq("username", username));
     }
 
+    private UserEntity getApiUser(String clientId) {
+        return mapper.selectOne(new QueryWrapper<UserEntity>()
+                .eq("client_id", clientId)
+                .eq("user_type",UserTypeEnum.API.getVal()));
+    }
+
+    private UserEntity getClientUser(String clientId) {
+        return mapper.selectOne(new QueryWrapper<UserEntity>()
+                .eq("client_id", clientId)
+                .eq("user_type",UserTypeEnum.CLIENT.getVal()));
+    }
+
     /**
      * Convert database entity objects into user data transfer object.
      * @param entity