完善登录令牌,密码加密等相关模块

This commit is contained in:
HMY 2024-09-09 17:25:26 +08:00
parent 6d4416a510
commit a0ab50c656
19 changed files with 250 additions and 37 deletions

View File

@ -114,7 +114,7 @@ public class TokenService
/**
* 验证令牌有效期相差不足20分钟自动刷新缓存
*
* @param token 令牌
* @param loginUser 令牌
* @return 令牌
*/
public void verifyToken(LoginUser loginUser)

View File

@ -2,6 +2,7 @@ package com.ruoyi.framework.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.project.hit.service.PupuEquipmentService;
import com.ruoyi.project.hit.util.Util1;
import com.ruoyi.project.hit.util.webSocket.WsServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
@ -22,6 +23,8 @@ public class RyTask
{
@Autowired
private WsServerEndpoint wsServerEndpoint;
@Autowired
private PupuEquipmentService pupuEquipmentService;
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
{
@ -38,6 +41,7 @@ public class RyTask
System.out.println("执行无参方法");
}
//定时任务每15s对设备进行一次检测超过30s未运行返回异常信息给前端同时将该设备运行状态改为停用
public void reportCurrentTime1() {
// System.out.println("11");
long l = System.currentTimeMillis();
@ -45,6 +49,7 @@ public class RyTask
for (Map.Entry<Integer, Long> entry : upsMap.entrySet()) {
if(l-entry.getValue()>=30000){
System.out.println(entry.getKey());
pupuEquipmentService.updateEquipmentStatus(entry.getKey(),1);
WsServerEndpoint wsServerEndpoint=new WsServerEndpoint();
try {
wsServerEndpoint.sendAllUser("id"+entry.getKey()+"设备异常");

View File

@ -5,10 +5,7 @@ import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.hit.domain.vo.SelectLogVO;
import com.ruoyi.project.hit.service.PupuLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
@ -24,7 +21,7 @@ public class PupuLogController extends BaseController {
* @param selectLogVO
* @return
*/
@GetMapping("/select")
@PostMapping("/select")
public TableDataInfo select(@RequestBody SelectLogVO selectLogVO){
List<HashMap> select = pupuLogService.select(selectLogVO);
return getDataTable(select);

View File

@ -64,7 +64,7 @@ public class PupuUpsHistoryController extends BaseController {
* @param upsHistoryVOupsId,startTime,endTime,pageNum,pageSize
* @return
*/
@GetMapping("/select")
@PostMapping("/select")
public TableDataInfo select(@RequestBody UpsHistoryVO upsHistoryVO){
startPage();
List<HashMap> select = pupuUpsHistoryService.select(upsHistoryVO);

View File

@ -5,14 +5,15 @@ import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.hit.domain.PupuUser;
import com.ruoyi.project.hit.domain.vo.UserLoginVO;
import com.ruoyi.project.hit.service.PupuUserService;
import com.ruoyi.project.hit.util.AESUtil;
import com.ruoyi.project.hit.util.JwtUtil;
import com.ruoyi.project.hit.util.webSocket.WsServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@ -26,18 +27,35 @@ public class PupuUserController extends BaseController {
@PostMapping("/login")
public AjaxResult login(@RequestBody UserLoginVO userLoginVO){
String encrypt = null;
try {
encrypt = AESUtil.encrypt(userLoginVO.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
userLoginVO.setPassword(encrypt);
PupuUser loginer = pupuUserService.login(userLoginVO);
if(loginer!=null){
String token = JwtUtil.generateToken(userLoginVO.getUserName());
System.out.println("token:"+token);
redisTemplate.opsForValue().set(token,loginer,60, TimeUnit.MILLISECONDS);
return AjaxResult.success(token);
// System.out.println("登录token:"+token);
// redisTemplate.opsForValue().set(token,loginer.toString(),60,TimeUnit.MINUTES);
Map<String,String> map=new HashMap<>();
map.put("Token",token);
return AjaxResult.success(map);
}else {
return AjaxResult.error("账号或密码错误");
}
}
@PostMapping("/register")
public AjaxResult register(@Validated @RequestBody PupuUser pupuUser){
//加密存储
String encrypt = null;
try {
encrypt = AESUtil.encrypt(pupuUser.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
pupuUser.setPassword(encrypt);
return toAjax(pupuUserService.register(pupuUser));
}

View File

@ -20,6 +20,9 @@ public class PupuEquipment implements Serializable {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Integer storeId;
private Integer status;

View File

@ -6,6 +6,7 @@ import com.ruoyi.project.hit.domain.vo.UpsHistoryVO;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author HP
@ -18,6 +19,8 @@ public interface PupuUpsHistoryMapper extends BaseMapper<PupuUpsHistory> {
List<HashMap> select(UpsHistoryVO upsHistoryVO);
List<HashMap> selectLatestHistory(Integer upsId);
Map<String,Object> getFirstRunTime(Integer upsId);
}

View File

@ -17,4 +17,12 @@ public interface PupuEquipmentService extends IService<PupuEquipment> {
int del(Integer equipmentId);
List<PupuEquipment> selectByStoreId(Integer storeId);
/**
* 修改设备状态
* @param equipmentId
* @param i status状态
* @return
*/
int updateEquipmentStatus(Integer equipmentId,int i);
}

View File

@ -19,5 +19,12 @@ public interface PupuUpsHistoryService extends IService<PupuUpsHistory> {
Map<String, Object> selectLatestHistory(Integer upsId);
/**
* 拿到当前设备第一次运行时间
* @param upsId
* @return
*/
Map<String,Object> getFirstRunTime(Integer upsId);
}

View File

@ -62,6 +62,15 @@ public class PupuEquipmentServiceImpl extends ServiceImpl<PupuEquipmentMapper, P
wrapper.eq(PupuEquipment::getStoreId,storeId);
return pupuEquipmentMapper.selectList(wrapper);
}
@Override
public int updateEquipmentStatus(Integer equipmentId, int i) {
LambdaQueryWrapper<PupuEquipment> wrapper=new LambdaQueryWrapper<>();
wrapper.eq(PupuEquipment::getEquipmentId,equipmentId);
PupuEquipment equipment=new PupuEquipment();
equipment.setStatus(i);
return pupuEquipmentMapper.update(equipment,wrapper);
}
}

View File

@ -1,8 +1,11 @@
package com.ruoyi.project.hit.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.project.hit.domain.PupuEquipment;
import com.ruoyi.project.hit.domain.PupuUpsHistory;
import com.ruoyi.project.hit.domain.vo.UpsHistoryVO;
import com.ruoyi.project.hit.mapper.PupuEquipmentMapper;
import com.ruoyi.project.hit.service.PupuUpsHistoryService;
import com.ruoyi.project.hit.mapper.PupuUpsHistoryMapper;
import org.springframework.stereotype.Service;
@ -22,6 +25,8 @@ public class PupuUpsHistoryServiceImpl extends ServiceImpl<PupuUpsHistoryMapper,
implements PupuUpsHistoryService{
@Resource
PupuUpsHistoryMapper pupuUpsHistoryMapper;
@Resource
private PupuEquipmentMapper pupuEquipmentMapper;
@Override
public List<HashMap> select(UpsHistoryVO upsHistoryVO) {
return pupuUpsHistoryMapper.select(upsHistoryVO);
@ -34,8 +39,23 @@ public class PupuUpsHistoryServiceImpl extends ServiceImpl<PupuUpsHistoryMapper,
for (HashMap map : list) {
objectMap.put((String) map.get("identifier"),map.get("value"));
}
Map<String, Object> runTime = getFirstRunTime(upsId);
objectMap.putAll(runTime);
return objectMap;
}
@Override
public Map<String, Object> getFirstRunTime(Integer upsId) {
Map<String,Object> map=new HashMap<>();
PupuEquipment pupuEquipment = pupuEquipmentMapper.selectById(upsId);
if(pupuEquipment.getStatus()==1){
map.put("firstRunTime",null);
}else {
Map<String, Object> f = pupuUpsHistoryMapper.getFirstRunTime(upsId);
map.put("firstRunTime",f.get("time"));
}
return map;
}
}

View File

@ -0,0 +1,95 @@
package com.ruoyi.project.hit.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AESUtil {
// AES算法名称
private static final String AES_ALGORITHM = "AES";
private static final SecretKey AES_SecretKey=generateFixAESKey();
/**
* 生成AES密钥
*
* @return SecretKey AES密钥
* @throws NoSuchAlgorithmException 当AES算法不可用时抛出
*/
public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM);
keyGenerator.init(128); // 设置密钥长度为128位
return keyGenerator.generateKey();
}
/**
* 生成AES特定密钥
*
* @return SecretKey AES密钥
* @throws NoSuchAlgorithmException 当AES算法不可用时抛出
*/
public static SecretKey generateFixAESKey(){
// 定义一个16字节字符串key
String fixedKey = "gpnknbndfdgzgwhh";
// 使用固定的字节数组(128位)创建DES密钥
return new SecretKeySpec(fixedKey.getBytes(StandardCharsets.UTF_8), "AES");
}
/**
* 使用AES算法加密
*
* @param data 待加密的数据
* @return 加密后的数据Base64编码
* @throws Exception 加密过程中的异常
*/
public static String encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, AES_SecretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
/**
* 使用AES算法解密
*
* @param data 加密的数据Base64编码
* @return 解密后的数据
* @throws Exception 解密过程中的异常
*/
public static String decrypt(String data) throws Exception {
byte[] encryptedData = Base64.getDecoder().decode(data);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, AES_SecretKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData);
}
// 主方法用于测试工具类
public static void main(String[] args) {
try {
// 生成AES密钥
// SecretKey secretKey = generateFixAESKey();
// System.out.println(secretKey);
// javax.crypto.spec.SecretKeySpec@14a23
// 加密数据
String originalString = "Aa123456?";
String encryptedString = encrypt(originalString);
System.out.println("Encrypted: " + encryptedString);
// 解密数据
String decryptedString = decrypt(encryptedString);
System.out.println("Decrypted: " + decryptedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -6,36 +6,33 @@ import java.util.Date;
public class JwtUtil {
private static final String SECRET_KEY = "your_secret_key"; // 用于签名的密钥
private static final String SECRET_KEY = "your_secret_keys"; // 用于签名的密钥
// 生成JWT
public static String generateToken(String username) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + 1000 * 60 * 60 * 1); // 有效期1小时
public static String generateToken(String subject) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiryDate)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 1)) // 有效期1小时
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
// 解析JWT
public static Claims parseToken(String token) {
// 验证JWT
public static Claims myParseToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
// 验证JWT
public static boolean isTokenValid(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
public static void main(String[] args) {
String str="laowang";
String s = generateToken(str);
System.out.println(s);
Claims claims = myParseToken(s);
System.out.println(claims);
}
}

View File

@ -51,10 +51,10 @@ public class Util1 {
public static PupuUpsHistory getHistoryFromMap(Map<String, Object> map) {
PupuUpsHistory history=null;
history = new PupuUpsHistory(1,(String) map.get("identifier"),new Date((Long) map.get("time")) ,
history = new PupuUpsHistory(11,(String) map.get("identifier"),new Date((Long) map.get("time")) ,
(String) map.get("value"),(String) map.get("data_type"),(String) map.get("name"),(String) map.get("access_mode"));
upsMap.put(1, (Long) map.get("time"));
upsMap.put(11, (Long) map.get("time"));
return history;
}

View File

@ -3,6 +3,8 @@ package com.ruoyi.project.hit.util.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.project.hit.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@ -14,21 +16,56 @@ public class HitInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Override
/* @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
System.out.println("token:" +token);
String path = request.getRequestURI();
System.out.println("拦截");
if (path.startsWith("/hit") && !"/hit/user/register".equals(path) && !"/hit/user/login".equals(path) && token != null) {
// 拦截除了/hit/user之外的所有/hit开头的请求
// 这里可以添加你的处理逻辑比如重定向返回错误信息等
if(redisTemplate.hasKey(token)){
System.out.println("放行");
return true;
}
System.out.println("打回");
return false; // 返回false表示拦截器链中断不再继续执行后续的Controller
}
// 放行/hit/user请求
return true;
}*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
if (path.startsWith("/hit/log/select") && !"/hit/user/register".equals(path) && !"/hit/user/login".equals(path)) {
System.out.println("拦截");
String token = request.getHeader("Token");
System.out.println(token);
if (token == null || !token.startsWith("Bearer ")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
System.out.println("打回1");
return false;
}
// 去除"Bearer "前缀
token = token.substring(7);
try {
JwtUtil.myParseToken(token);// 验证token
System.out.println("放行1");
return true;
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
System.out.println("打回2");
return false;
}
}
System.out.println("放行2");
return true;
}
@Override

View File

@ -8,14 +8,14 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
/*@Autowired
@Autowired
private HitInterceptor hitInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(hitInterceptor)
.addPathPatterns("/hit/**") // 拦截所有/hit开头的请求
.addPathPatterns("/hit/log/select") // 拦截所有/hit开头的请求
.excludePathPatterns("/hit/user/register")
.excludePathPatterns("/hit/user/login"); // 但不拦截/hit/user
}*/
}
}

View File

@ -63,7 +63,7 @@ spring:
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
database: 1
# 密码
#password: 123456
# 连接超时时间

View File

@ -8,6 +8,7 @@
<id property="equipmentId" column="equipment_id" jdbcType="INTEGER"/>
<result property="serialNumber" column="serial_number" jdbcType="VARCHAR"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
<result property="storeId" column="store_id" jdbcType="INTEGER"/>
<result property="status" column="status" jdbcType="INTEGER"/>
</resultMap>

View File

@ -80,4 +80,17 @@
WHERE
ph.ups_id = #{upsId};
</select>
<select id="getFirstRunTime" resultType="java.util.HashMap">
SELECT pupu_ups_history.time
FROM pupu_ups_history
WHERE ups_id = #{upsId}
AND time > (
SELECT update_time
FROM pupu_equipment
WHERE equipment_id = #{upsId}
)
ORDER BY time ASC
LIMIT 1;
</select>
</mapper>