linxk 3 тижнів тому
батько
коміт
6fc502a797

+ 11 - 11
cif-service/pom.xml

@@ -75,18 +75,18 @@
 <!--            <version>0.5.2</version>-->
 <!--        </dependency>-->
 
-<!--        <dependency>-->
-<!--            <groupId>io.jsonwebtoken</groupId>-->
-<!--            <artifactId>jjwt</artifactId>-->
-<!--            <version>0.9.1</version>-->
-<!--        </dependency>-->
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.1</version>
+        </dependency>
 
-<!--        <dependency>-->
-<!--            <groupId>cn.hutool</groupId>-->
-<!--            <artifactId>hutool-all</artifactId>-->
-<!--            <version>RELEASE</version>-->
-<!--            <scope>compile</scope>-->
-<!--        </dependency>-->
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>RELEASE</version>
+            <scope>compile</scope>
+        </dependency>
 
 <!--        <dependency>-->
 <!--            <groupId>com.google.firebase</groupId>-->

+ 160 - 160
cif-service/src/main/java/com/txz/cif/core/AuthService.java

@@ -1,160 +1,160 @@
-//package com.txz.cif.core;
-//
-//import cn.hutool.core.date.DateField;
-//import cn.hutool.core.date.DateUtil;
-//import cn.hutool.json.JSONUtil;
-//import io.jsonwebtoken.Claims;
-//import io.jsonwebtoken.ExpiredJwtException;
-//import io.jsonwebtoken.Jwts;
-//import io.jsonwebtoken.SignatureAlgorithm;
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.commons.lang3.StringUtils;
-//import org.apache.commons.lang3.tuple.ImmutableTriple;
-//import org.apache.commons.lang3.tuple.Triple;
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.stereotype.Service;
-//import org.springframework.web.context.request.RequestContextHolder;
-//import org.springframework.web.context.request.ServletRequestAttributes;
-//
-//import javax.servlet.http.HttpServletRequest;
-//import java.util.*;
-//
-//
-//@Service
-//@Slf4j
-//public class AuthService {
-//
-//    private static final String BEARER = "Bearer ";
-//
-//    /**
-//     * jwt token 密钥,主要用于token解析,签名验证
-//     */
-//    @Value("${spring.security.oauth2.jwt.signingKey}")
-//    private static String signingKey = "txz123456";
-//
-//
-//    public String buildJwtToken( Long userId) {
-//        String KEY = "txz123456";
-//        Date now = DateUtil.date();
-//        Date exp = DateUtil.offset(now, DateField.DAY_OF_YEAR,30);
-//        Map<String, Object> claims = new HashMap<String, Object>();
-//        claims.put("userId", userId);
-//
-//        String jwtToken = Jwts.builder()
-//                .setClaims(claims)
-//                .setId(UUID.randomUUID().toString())
-//                .setIssuedAt(now)
-//                .setSubject("sawa")
-//                .signWith(SignatureAlgorithm.HS256, KEY.getBytes())
-//                .setExpiration(exp).compact();
-//
-//        return "Bearer " +jwtToken;
-//    }
-//
-//    public String buildJwtTokenWithRole( Long userId,Integer role, Integer day) {
-//        String KEY = "123456";
-//        Date now = DateUtil.date();
-//        Date exp = DateUtil.offset(now, DateField.DAY_OF_YEAR,day);
-//        Map<String, Object> claims = new HashMap<String, Object>();
-//        claims.put("userId", userId);
-//        claims.put("role", role);
-//
-//        String jwtToken = Jwts.builder()
-//                .setClaims(claims)
-//                .setId(UUID.randomUUID().toString())
-//                .setIssuedAt(now)
-//                .setSubject("sawa")
-//                .signWith(SignatureAlgorithm.HS256, KEY.getBytes())
-//                .setExpiration(exp).compact();
-//
-//        return "Bearer " +jwtToken;
-//    }
-//
-//    public Claims getClaimsFromToken(String authentication) {
-//        try {
-//            final Claims claims = this.getJwt(authentication);
-//            boolean pass = DateUtil.compare(DateUtil.date(),claims.getExpiration()) < 0;
-//            if (pass){
-//                return claims;
-//            }
-//        } catch (Exception e) {
-//            log.error("get userId from token error:{}", e.getMessage());
-//        }
-//        return null;
-//    }
-//
-//
-//    private static Claims getJwt(String jwtToken) {
-//        if (jwtToken.startsWith(BEARER)) {
-//            jwtToken = StringUtils.substring(jwtToken, BEARER.length());
-//        }
-//        Claims claims;
-//        try {
-//            claims = Jwts.parser()  //得到DefaultJwtParser
-//                    .setSigningKey(signingKey.getBytes()) //设置签名的秘钥
-//                    .parseClaimsJws(jwtToken).getBody();
-//        } catch(ExpiredJwtException e) {
-//            claims = e.getClaims();
-//        }
-//
-//        return claims;
-//    }
-//
-//    public Long getTokenUserId(HttpServletRequest request) {
-//        if (request == null){
-//            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
-//            if (null != sra) {
-//                request = sra.getRequest();
-//            } else {
-//                return null;
-//            }
-//        }
-//        String token = request.getHeader("token");
-//        Claims claims = getJwt(token);
-//        return Long.valueOf(claims.get("userId").toString());
-//    }
-//
-//    /**
-//     * 验证 JWT token 的有效性
-//     * @param token 待验证的 token 字符串(可带或不带 "Bearer " 前缀)
-//     * @return 验证结果对象,包含:
-//     *         - 是否有效(boolean)
-//     *         - 如果无效,错误信息(String)
-//     *         - 如果有效,解析出的 Claims 对象(Claims)
-//     */
-//    public Triple<Boolean, String, Claims> verifyToken(String token) {
-//        try {
-//            // 1. 检查token是否为空
-//            if (StringUtils.isBlank(token)) {
-//                return ImmutableTriple.of(false, "Token不能为空", null);
-//            }
-//
-//            // 2. 解析token获取Claims
-//            Claims claims = getJwt(token);
-//
-//            // 3. 检查token是否过期
-//            if (DateUtil.compare(DateUtil.date(), claims.getExpiration()) >= 0) {
-//                return ImmutableTriple.of(false, "Token已过期", claims);
-//            }
-//
-//            // 4. 检查必要字段(根据业务需求)
-//            if (claims.get("userId") == null) {
-//                return ImmutableTriple.of(false, "无效Token: 缺少userId字段", claims);
-//            }
-//
-//            // 5. 所有检查通过,返回有效
-//            return ImmutableTriple.of(true, null, claims);
-//        } catch (ExpiredJwtException e) {
-//            // 专门处理过期异常,可以获取到过期的claims
-//            return ImmutableTriple.of(false, "Token已过期", e.getClaims());
-//        } catch (Exception e) {
-//            log.error("Token验证失败: {}", e.getMessage());
-//            return ImmutableTriple.of(false, "无效Token: " + e.getMessage(), null);
-//        }
-//    }
-//
-//}
-//
-//
-//
-//
+package com.txz.cif.core;
+
+import cn.hutool.core.date.DateField;
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.json.JSONUtil;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.ExpiredJwtException;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.commons.lang3.tuple.Triple;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.*;
+
+
+@Service
+@Slf4j
+public class AuthService {
+
+    private static final String BEARER = "Bearer ";
+
+    /**
+     * jwt token 密钥,主要用于token解析,签名验证
+     */
+    @Value("${spring.security.oauth2.jwt.signingKey}")
+    private static String signingKey = "txz123456";
+
+
+    public String buildJwtToken( Long userId) {
+        String KEY = "txz123456";
+        Date now = DateUtil.date();
+        Date exp = DateUtil.offset(now, DateField.DAY_OF_YEAR,30);
+        Map<String, Object> claims = new HashMap<String, Object>();
+        claims.put("userId", userId);
+
+        String jwtToken = Jwts.builder()
+                .setClaims(claims)
+                .setId(UUID.randomUUID().toString())
+                .setIssuedAt(now)
+                .setSubject("sawa")
+                .signWith(SignatureAlgorithm.HS256, KEY.getBytes())
+                .setExpiration(exp).compact();
+
+        return "Bearer " +jwtToken;
+    }
+
+    public String buildJwtTokenWithRole( Long userId,Integer role, Integer day) {
+        String KEY = "123456";
+        Date now = DateUtil.date();
+        Date exp = DateUtil.offset(now, DateField.DAY_OF_YEAR,day);
+        Map<String, Object> claims = new HashMap<String, Object>();
+        claims.put("userId", userId);
+        claims.put("role", role);
+
+        String jwtToken = Jwts.builder()
+                .setClaims(claims)
+                .setId(UUID.randomUUID().toString())
+                .setIssuedAt(now)
+                .setSubject("sawa")
+                .signWith(SignatureAlgorithm.HS256, KEY.getBytes())
+                .setExpiration(exp).compact();
+
+        return "Bearer " +jwtToken;
+    }
+
+    public Claims getClaimsFromToken(String authentication) {
+        try {
+            final Claims claims = this.getJwt(authentication);
+            boolean pass = DateUtil.compare(DateUtil.date(),claims.getExpiration()) < 0;
+            if (pass){
+                return claims;
+            }
+        } catch (Exception e) {
+            log.error("get userId from token error:{}", e.getMessage());
+        }
+        return null;
+    }
+
+
+    private static Claims getJwt(String jwtToken) {
+        if (jwtToken.startsWith(BEARER)) {
+            jwtToken = StringUtils.substring(jwtToken, BEARER.length());
+        }
+        Claims claims;
+        try {
+            claims = Jwts.parser()  //得到DefaultJwtParser
+                    .setSigningKey(signingKey.getBytes()) //设置签名的秘钥
+                    .parseClaimsJws(jwtToken).getBody();
+        } catch(ExpiredJwtException e) {
+            claims = e.getClaims();
+        }
+
+        return claims;
+    }
+
+    public Long getTokenUserId(HttpServletRequest request) {
+        if (request == null){
+            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+            if (null != sra) {
+                request = sra.getRequest();
+            } else {
+                return null;
+            }
+        }
+        String token = request.getHeader("token");
+        Claims claims = getJwt(token);
+        return Long.valueOf(claims.get("userId").toString());
+    }
+
+    /**
+     * 验证 JWT token 的有效性
+     * @param token 待验证的 token 字符串(可带或不带 "Bearer " 前缀)
+     * @return 验证结果对象,包含:
+     *         - 是否有效(boolean)
+     *         - 如果无效,错误信息(String)
+     *         - 如果有效,解析出的 Claims 对象(Claims)
+     */
+    public Triple<Boolean, String, Claims> verifyToken(String token) {
+        try {
+            // 1. 检查token是否为空
+            if (StringUtils.isBlank(token)) {
+                return ImmutableTriple.of(false, "Token不能为空", null);
+            }
+
+            // 2. 解析token获取Claims
+            Claims claims = getJwt(token);
+
+            // 3. 检查token是否过期
+            if (DateUtil.compare(DateUtil.date(), claims.getExpiration()) >= 0) {
+                return ImmutableTriple.of(false, "Token已过期", claims);
+            }
+
+            // 4. 检查必要字段(根据业务需求)
+            if (claims.get("userId") == null) {
+                return ImmutableTriple.of(false, "无效Token: 缺少userId字段", claims);
+            }
+
+            // 5. 所有检查通过,返回有效
+            return ImmutableTriple.of(true, null, claims);
+        } catch (ExpiredJwtException e) {
+            // 专门处理过期异常,可以获取到过期的claims
+            return ImmutableTriple.of(false, "Token已过期", e.getClaims());
+        } catch (Exception e) {
+            log.error("Token验证失败: {}", e.getMessage());
+            return ImmutableTriple.of(false, "无效Token: " + e.getMessage(), null);
+        }
+    }
+
+}
+
+
+
+

+ 1 - 6
cif-service/src/main/java/com/txz/cif/web/RechargeRecordApiController.java

@@ -1,7 +1,5 @@
 package com.txz.cif.web;
 import cn.hutool.core.date.DateUtil;
-import cn.hutool.core.lang.generator.SnowflakeGenerator;
-import cn.hutool.core.util.IdUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.json.JSONObject;
 import cn.hutool.json.JSONUtil;
@@ -10,18 +8,16 @@ import com.txz.cif.core.ResultGenerator;
 import com.txz.cif.model.Goods;
 import com.txz.cif.model.RechargeRecord;
 import com.txz.cif.model.User;
-import com.txz.cif.param.RechargeParam;
 import com.txz.cif.service.*;
 
 import com.txz.cif.core.ResultCode;
 
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
-import com.txz.core.AuthService;
+import com.txz.cif.core.AuthService;
 import org.springframework.web.bind.annotation.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import com.txz.core.ServiceException;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 
@@ -31,7 +27,6 @@ import tk.mybatis.mapper.entity.Example.Criteria;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import java.util.List;
-import org.apache.commons.lang.StringUtils;
 
 /**
 * Created by CodeGenerator on 2025/07/15.

+ 1 - 1
cif-service/src/main/java/com/txz/cif/web/UserApiController.java

@@ -22,7 +22,7 @@ import com.txz.cif.web.para.UserInfoForm;
 import com.txz.cif.core.*;
 import com.txz.cif.model.*;
 import com.txz.cif.service.*;
-import com.txz.core.AuthService;
+import com.txz.cif.core.AuthService;
 import io.swagger.annotations.*;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.web.bind.annotation.*;

+ 1 - 3
cif-service/src/main/java/com/txz/cif/web/WithdrawRecordApiController.java

@@ -14,14 +14,13 @@ import com.txz.cif.core.ResultCode;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
 import com.txz.cif.web.para.WithdrawParam;
-import com.txz.core.AuthService;
+import com.txz.cif.core.AuthService;
 import com.txz.operating.dto.ConfigDTO;
 import io.jsonwebtoken.Claims;
 import org.apache.commons.lang3.tuple.Triple;
 import org.springframework.web.bind.annotation.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import com.txz.core.ServiceException;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 
@@ -32,7 +31,6 @@ import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.List;
-import org.apache.commons.lang.StringUtils;
 
 import static com.txz.cif.core.AbstractApiController.X_CLIENT_TOKEN;
 

+ 1 - 1
cif-service/src/main/resources/bootstrap.properties

@@ -11,7 +11,7 @@ test.nacos=172.10.100.40:30848
 pro.nacos=172.10.100.10:30308
 spring.cloud.nacos.discovery.server-addr=${${spring.profiles.active}.nacos}
 spring.cloud.nacos.config.server-addr=${${spring.profiles.active}.nacos}
-dev.file.home=/usr/local/logs/cif
+dev.file.home=./
 test.file.home=/Users/linxk/mydata/temp
 log.home=${${spring.profiles.active}.file.home}