1、接收用户信息UserFull的resoures类型改为Object,线上会出现resoures为null

2、新增发送任务审核状态修改 发送给外部系统功能(暂未使用)
3、用户信息存入reids
This commit is contained in:
PushM
2024-07-31 01:49:51 +08:00
parent 86cfec0eef
commit cfa60e66ea
6 changed files with 181 additions and 22 deletions

View File

@@ -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;

View File

@@ -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) {

View File

@@ -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"); // 确保路径正确

View File

@@ -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;
}
}
}