summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPushM <[email protected]>2024-07-31 01:49:51 +0800
committerPushM <[email protected]>2024-07-31 01:49:51 +0800
commitcfa60e66ea2842c3791b8afd76ca07993e2ad195 (patch)
treedad3c3cfee527584282091f562425754cd2e997e
parent86cfec0eef7e5c8fee134337b4f84372dc207954 (diff)
1、接收用户信息UserFull的resoures类型改为Object,线上会出现resoures为null
2、新增发送任务审核状态修改 发送给外部系统功能(暂未使用) 3、用户信息存入reids
-rw-r--r--src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java16
-rw-r--r--src/main/java/com/realtime/protection/server/task/TaskService.java67
-rw-r--r--src/main/java/com/realtime/protection/server/user/login/LoginController.java20
-rw-r--r--src/main/java/com/realtime/protection/server/user/login/LoginService.java50
-rw-r--r--src/main/resources/mappers/CommandMapper.xml10
-rw-r--r--src/test/java/com/realtime/protection/server/user/LoginServiceTest.java40
6 files changed, 181 insertions, 22 deletions
diff --git a/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java b/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java
index 77c20e0..4170673 100644
--- a/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java
+++ b/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java
@@ -4,10 +4,12 @@ import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.Data;
/**
* @author Yixiang Zhao
**/
+@Data
public class UserFull {
public String ticket;
public List<Group> groups;
@@ -19,7 +21,10 @@ public class UserFull {
public String uid;
public String employeeNumber;
public String name;
- public List<String> resoures;
+ public Object resoures;
+
+
+
public String getOrgCode() {
if (orgs.size() > 0) {
@@ -42,7 +47,7 @@ public class UserFull {
return "";
}
}
-
+@Data
class Group {
public int groupId;
public int applicationId;
@@ -51,7 +56,7 @@ class Group {
public String groupTag; // Assume it's a JSON String, otherwise it could be List<Tag> or similar
public String groupRemark;
}
-
+@Data
class Role {
public int roleId;
public int applicationId;
@@ -60,9 +65,10 @@ class Role {
public String roleRemark;
public String roleTag; // Same assumption as above
public List<String> res; // Assuming a Resource class exists
- public List<String> resources; // Assuming a Resource class exists
+// public List<String> resources; // Assuming a Resource class exists
+ public Object resources;
}
-
+@Data
class Org {
public String orgName;
public String orgDescription;
diff --git a/src/main/java/com/realtime/protection/server/task/TaskService.java b/src/main/java/com/realtime/protection/server/task/TaskService.java
index 4d69297..22c66ce 100644
--- a/src/main/java/com/realtime/protection/server/task/TaskService.java
+++ b/src/main/java/com/realtime/protection/server/task/TaskService.java
@@ -19,8 +19,13 @@ import com.realtime.protection.server.command.CommandMapper;
import com.realtime.protection.server.rule.dynamicrule.DynamicRuleMapper;
import com.realtime.protection.server.rule.staticrule.StaticRuleMapper;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.reactive.function.client.WebClient;
+import org.springframework.web.reactive.function.client.WebClientResponseException;
+import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@@ -29,6 +34,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -325,12 +331,17 @@ public class TaskService {
throw new IllegalArgumentException("无法找到任务ID为" + taskId + "的任务,也许任务不存在?");
}
+
if (AuditStatusValidator.setOriginal(originalAuditStatus).checkValidate(taskAuditStatus))
taskMapper.changeTaskAuditStatusWithAudior(taskId, taskAuditStatus, auditUserName, auditUserId, auditUserDepart);
else return false;
insertTaskStatusLog(taskId);
+
+
return true;
}
+
+
@Transactional
public Boolean changeTaskAuditStatus(Long taskId, Integer taskAuditStatus) {
Integer originalAuditStatus = taskMapper.queryTaskAuditStatus(taskId);
@@ -342,10 +353,64 @@ public class TaskService {
taskMapper.changeTaskAuditStatus(taskId, taskAuditStatus);
else return false;
insertTaskStatusLog(taskId);
-
+// sendTaskStatusChangeToOtherSystem(taskId,taskAuditStatus);
return true;
}
+ public Boolean sendTaskStatusChangeToOtherSystem(Long taskId, Integer taskAuditStatus) {
+ WebClient ddos_sytem = WebClient.builder()
+ .baseUrl("http://10.58.72.140:8089")
+ .build();
+
+ AtomicReference<Boolean> success = new AtomicReference<>(false);
+
+ Map<String, String> sendBody = new HashMap<>();
+ sendBody.put("taskId", String.valueOf(taskId));
+ sendBody.put("taskAuditStatus", String.valueOf(taskAuditStatus));
+
+ Mono<Map> mono = ddos_sytem.post()
+ .uri("/task/status")
+ .bodyValue(sendBody)
+ .accept(MediaType.APPLICATION_JSON)
+ .exchangeToMono(res -> {
+ if (res.statusCode().equals(HttpStatus.OK)) {
+ return res.bodyToMono(Map.class);
+ }
+ return res.createError();
+ })
+ .doOnError(WebClientResponseException.class, res -> success.set(false));
+
+// Map<String, Integer> response = mono.block(Duration.ofSeconds(5));
+
+ // 异步处理响应
+ mono.subscribe(
+ response -> {
+ // 成功响应处理
+ System.out.println("响应: " + response);
+ success.set(true);
+ },
+ error -> {
+ // 错误响应处理
+ System.err.println("错误: " + error.getMessage());
+ success.set(false);
+ }
+ );
+
+// if (response == null) {
+// log.info("指令首次查询RCP返回为null");
+// return false;
+// }
+// response.forEach((commandUUID, responseCode) -> {
+// log.info("指令首次查询RCP成功, 指令uuid: " + commandUUID + ", responseCode: " + responseCode);
+// if (responseCode != 0) {
+// log.warn("指令首次查询RCP失败, 指令uuid: " + commandUUID + ", responseCode: " + responseCode);
+// }
+// });
+
+ success.set(true);
+
+ return success.get();
+ }
public Boolean deleteTask(Long taskId) {
Task task = taskMapper.queryTask(taskId);
if (task == null) {
diff --git a/src/main/java/com/realtime/protection/server/user/login/LoginController.java b/src/main/java/com/realtime/protection/server/user/login/LoginController.java
index b71f574..1f4e587 100644
--- a/src/main/java/com/realtime/protection/server/user/login/LoginController.java
+++ b/src/main/java/com/realtime/protection/server/user/login/LoginController.java
@@ -2,9 +2,12 @@ package com.realtime.protection.server.user.login;
import javax.security.auth.login.LoginException;
+import com.realtime.protection.configuration.utils.EntityUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.HashOperations;
+import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -19,6 +22,10 @@ import com.realtime.protection.configuration.response.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
// Just for example, not in production environment
@RestController
@RequestMapping("/user")
@@ -63,6 +70,19 @@ public class LoginController {
String sessionId = session.getId();
+ Map<String, String> userRedisMap = new HashMap<>();
+ userRedisMap.put("sessionData", sessionData);
+ userRedisMap.put("userId", userFull.uid);
+ userRedisMap.put("userName", userFull.name);
+ userRedisMap.put("userRole", userFull.getRoleKey());
+ userRedisMap.put("UserDepartmentName", userFull.getOrgName());
+ userRedisMap.put("UserDepartmentCode", userFull.getOrgCode());
+
+
+ if (!loginService.storeUserFullToRedis(userRedisMap)){
+ throw new LoginException("登录失败,无法存储用户信息到Redis");
+ }
+
// 设置JSESSIONID Cookie
Cookie sessionCookie = new Cookie("JSESSIONID", sessionId);
sessionCookie.setPath("/api"); // 确保路径正确
diff --git a/src/main/java/com/realtime/protection/server/user/login/LoginService.java b/src/main/java/com/realtime/protection/server/user/login/LoginService.java
index 4b3083e..1da500f 100644
--- a/src/main/java/com/realtime/protection/server/user/login/LoginService.java
+++ b/src/main/java/com/realtime/protection/server/user/login/LoginService.java
@@ -1,10 +1,13 @@
package com.realtime.protection.server.user.login;
import com.realtime.protection.configuration.utils.OkHttpUtil;
+import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import javax.security.auth.login.LoginException;
+import org.springframework.data.redis.core.HashOperations;
+import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -23,15 +26,22 @@ import io.micrometer.common.util.StringUtils;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
@Service
+@Slf4j
// just for example, not for production environment
public class LoginService {
-
+ private static final String LOGIN_USER_ID = "login_user_id::";
+ private static final long LOGIN_USER_TTL = 1200L;
private final LoginMapper loginMapper;
+ private final StringRedisTemplate stringRedisTemplate;
- public LoginService(LoginMapper loginMapper) {
+ public LoginService(LoginMapper loginMapper, StringRedisTemplate stringRedisTemplate) {
this.loginMapper = loginMapper;
+ this.stringRedisTemplate = stringRedisTemplate;
}
public Integer login(User user) throws LoginException {
@@ -52,11 +62,11 @@ public class LoginService {
// 获取 ACCESS_TOKEN
ObjectMapper objectMapper = new ObjectMapper();
- // OkHttpClient client = new OkHttpClient();
+ // OkHttpClient client = new OkHttpClient();
//不做证书验证的OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
- .sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(),OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509)
+ .sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(), OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509)
.hostnameVerifier(OkHttpUtil.getIgnoreSslHostnameVerifier())
.build();
@@ -69,7 +79,7 @@ public class LoginService {
.header("Authorization", "Basic TlNBRERAWlguT1JHOm5IUWxOczd5S3lXeW8yTnNiZjZOaEZhYWJpVllJQVNTbHViUWd6VGg4TlNsTlJBNVdsUFExdz09")
.post(okhttp3.internal.Util.EMPTY_REQUEST)
.build();
- try {
+ try {
Response response = client.newCall(request).execute();
String rsp = response.body().string();
System.out.println("rsp:" + rsp);
@@ -88,16 +98,16 @@ public class LoginService {
}
// 校验 SESSION_DATA
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
- .addFormDataPart("sessionData", sessionData).build();
+ .addFormDataPart("sessionData", sessionData).build();
request = new Request.Builder()
// .url("https://passport.zx.com:10217/passport/accessApplication")
// .url("https://114.243.134.122:10217/passport/accessApplication")
// .url("https://passport.iam.pub/passport/accessApplication")
- .url("http://10.60.15.14:8080/passport/accessApplication")
- .header("Authorization", "Bearer " + accessToken)
- .header("Content-Type", "application/x-www-form-urlencoded")
- .post(body)
- .build();
+ .url("http://10.60.15.14:8080/passport/accessApplication")
+ .header("Authorization", "Bearer " + accessToken)
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .post(body)
+ .build();
try {
Response response = client.newCall(request).execute();
String rsp = response.body().string();
@@ -119,5 +129,23 @@ public class LoginService {
}
+ public boolean storeUserFullToRedis( Map<String, String> userRedisMap) {
+ try {
+ String uid = userRedisMap.get("userId");
+
+ HashOperations<String, String, String> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash();
+ stringObjectObjectHashOperations.putAll(LOGIN_USER_ID +uid, userRedisMap);
+// 设置有效时间,问题:该方式说明无论你是否操作一但过了120分钟,就会被认定为未登录,所以我们应该在拦截器中设置每次操作更新token的存活时间
+ stringRedisTemplate.expire(LOGIN_USER_ID + uid, LOGIN_USER_TTL, TimeUnit.MINUTES);
+ // 获取 HashMap
+ Map<String, String> storedHashMap = stringObjectObjectHashOperations.entries(LOGIN_USER_ID +uid);
+ log.info("存储用户信息到redis成功,User信息: {}", storedHashMap);
+ return true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ log.error("存用户信息到redis出错 error: {},User信息: {}", e.getMessage(), userRedisMap);
+ return false;
+ }
+ }
}
diff --git a/src/main/resources/mappers/CommandMapper.xml b/src/main/resources/mappers/CommandMapper.xml
index 56fb82d..0f7eca5 100644
--- a/src/main/resources/mappers/CommandMapper.xml
+++ b/src/main/resources/mappers/CommandMapper.xml
@@ -514,7 +514,7 @@
</select>
<update id="stopCommandsByTaskId">
- UPDATE t_command
+ UPDATE t_command_status
SET IS_VALID = FALSE,
LAST_UPDATE = NOW()
WHERE TASK_ID = #{task_id}
@@ -522,7 +522,7 @@
</update>
<update id="startCommandsByTaskId">
- UPDATE t_command
+ UPDATE t_command_status
SET IS_VALID = TRUE,
LAST_UPDATE = NOW()
WHERE TASK_ID = #{task_id}
@@ -530,7 +530,7 @@
</update>
<update id="removeCommandsByTaskId">
- UPDATE t_command
+ UPDATE t_command_status
SET IS_DELETED = TRUE,
LAST_UPDATE = NOW()
WHERE TASK_ID = #{task_id}
@@ -538,7 +538,7 @@
</update>
<update id="setCommandJudged">
- UPDATE t_command
+ UPDATE t_command_status
SET IS_JUDGED = #{is_judged},
LAST_UPDATE = NOW()
WHERE COMMAND_ID = #{command_id}
@@ -560,7 +560,7 @@
and expire_time = NULL
</update>
<update id="updateCommandIsJudgedIfIgnoreThisTime">
- update t_command
+ update t_command_status
set IS_JUDGED = 0
where COMMAND_ID = #{command_id}
</update>
diff --git a/src/test/java/com/realtime/protection/server/user/LoginServiceTest.java b/src/test/java/com/realtime/protection/server/user/LoginServiceTest.java
new file mode 100644
index 0000000..e64044d
--- /dev/null
+++ b/src/test/java/com/realtime/protection/server/user/LoginServiceTest.java
@@ -0,0 +1,40 @@
+package com.realtime.protection.server.user;
+
+import com.realtime.protection.ProtectionApplicationTests;
+import com.realtime.protection.configuration.entity.user.UserFull;
+import com.realtime.protection.server.user.login.LoginService;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@SpringBootTest
+public class LoginServiceTest extends ProtectionApplicationTests {
+
+ private final LoginService loginService;
+
+ @Autowired
+ LoginServiceTest(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+
+ @Test
+ void testStoreUserFullToRedis() {
+ // test code here
+
+ Map<String, String> userRedisMap = new HashMap<>();
+ userRedisMap.put("sessionData", "sessionData22222222222222222222222222222222222222222222");
+ userRedisMap.put("userId", "111111");
+ userRedisMap.put("userName", "张三");
+ userRedisMap.put("userRole", "admin");
+ userRedisMap.put("UserDepartmentName", "二处");
+ userRedisMap.put("UserDepartmentCode", "2");
+
+
+ assert loginService.storeUserFullToRedis(userRedisMap);
+
+ }
+}