Commit 74585ef0 by 章家宝

feat:检测端代码创建

1 parent 46ea97d5
Showing 23 changed files with 1031 additions and 8 deletions
# 开发环境配置
server:
port: 6904
logging:
location: /Users/gonglei/aus
spring:
task:
execution:
pool:
core-size: 2
max-size: 10
queue-capacity: 100
keep-alive: 60s
allow-core-thread-timeout: true
shutdown:
await-termination: true
await-termination-period: 30s
thread-name-prefix: task-
# 开发环境配置
server:
port: 6901
servlet:
context-path: /app
spring:
task:
execution:
pool:
core-size: 2
max-size: 10
queue-capacity: 100
keep-alive: 60s
allow-core-thread-timeout: true
shutdown:
await-termination: true
await-termination-period: 30s
thread-name-prefix: task-
logging:
location: /data/java_log/aus
...@@ -31,6 +31,14 @@ public interface InspectorRepository extends BaseRepository<Inspector, Long>, Jp ...@@ -31,6 +31,14 @@ public interface InspectorRepository extends BaseRepository<Inspector, Long>, Jp
* @param phone 手机号 * @param phone 手机号
* @return 检测师信息 * @return 检测师信息
*/ */
Optional<Inspector> findByStatusAndPhoneAndDeleteFlag(Integer statue, String phone, String deletedFlag);
/**
* 根据手机号查询检测师
*
* @param phone 手机号
* @return 检测师信息
*/
List<Inspector> findByPhone(String phone); List<Inspector> findByPhone(String phone);
/** /**
......
...@@ -9,16 +9,12 @@ import com.glsx.usedcar.converts.InspectorConverter; ...@@ -9,16 +9,12 @@ import com.glsx.usedcar.converts.InspectorConverter;
import com.glsx.usedcar.enums.common.DeleteFlag; import com.glsx.usedcar.enums.common.DeleteFlag;
import com.glsx.usedcar.module.inspect.dao.InspectorOpLogRepository; import com.glsx.usedcar.module.inspect.dao.InspectorOpLogRepository;
import com.glsx.usedcar.module.inspect.dao.InspectorRepository; import com.glsx.usedcar.module.inspect.dao.InspectorRepository;
import com.glsx.usedcar.module.inspect.entity.Inspector; import com.glsx.usedcar.module.inspect.entity.*;
import com.glsx.usedcar.module.inspect.entity.InspectorOpLog;
import com.glsx.usedcar.module.inspect.entity.Inspector_;
import com.glsx.usedcar.module.inspect.vo.*; import com.glsx.usedcar.module.inspect.vo.*;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page; import org.springframework.data.domain.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -27,8 +23,7 @@ import org.summerframework.core.exception.BusinessCodeException; ...@@ -27,8 +23,7 @@ import org.summerframework.core.exception.BusinessCodeException;
import org.summerframework.core.util.StringUtils; import org.summerframework.core.util.StringUtils;
import org.summerframework.orm.paging.Pagination; import org.summerframework.orm.paging.Pagination;
import java.util.List; import java.util.*;
import java.util.Objects;
/** /**
* 检测师服务 * 检测师服务
...@@ -262,4 +257,8 @@ public class InspectorService { ...@@ -262,4 +257,8 @@ public class InspectorService {
return baseRequest.withSort(Sort.by(Sort.Order.desc(JpaQueryConstants.Inspector.UPDATE_TIME))); return baseRequest.withSort(Sort.by(Sort.Order.desc(JpaQueryConstants.Inspector.UPDATE_TIME)));
} }
public Inspector findByPhone(String phone) {
Optional<Inspector> byPhoneAndDeleteFlag = inspectorRepository.findByStatusAndPhoneAndDeleteFlag(1, phone, DeleteFlag.NOT_DELETED.getCode());
return byPhoneAndDeleteFlag.orElse(null);
}
} }
package com.glsx.usedcar.util;
import cn.hutool.core.util.RandomUtil;
import com.glsx.usedcar.gsc.GscApiInvoker;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* 短信验证码工具类(含防刷逻辑)
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsCodeUtil {
private final RedisCacheUtil redisCacheUtil;
@Lazy
@Resource
private GscApiInvoker gscApiInvoker;
@Value("${sms.code-expire:300}") // 验证码有效期5分钟(秒)
private int codeExpire;
@Value("${sms.code-length:6}") // 验证码长度
private int codeLength;
@Value("${sms.cool-down:60}") // 冷却期:60秒内禁止重复发送(秒)
private long coolDownSeconds;
@Value("${sms.time-window:300}") // 次数限流时间窗口:5分钟(秒)
private long timeWindowSeconds;
@Value("${sms.max-count:3}") // 时间窗口内最大发送次数
private int maxSendCount;
/**
* 校验验证码发送频率(防刷核心方法)
* @param phone 手机号
* @throws RuntimeException 频率超限则抛出异常(前端捕获提示)
*/
public void checkSendFrequency(String phone) {
// 1. 构建Redis Key
String coolDownKey = "SMS_COOL_DOWN:" + phone;
String countKey = "SMS_SEND_COUNT:" + phone;
// 2. 检查冷却期:60秒内是否已发送过
if (redisCacheUtil.existsKey(coolDownKey)) {
throw new RuntimeException("验证码发送过于频繁,请" + coolDownSeconds + "秒后再试");
}
// 3. 检查时间窗口内发送次数(5分钟内最多3次)
Integer sendCount = redisCacheUtil.getCache(countKey, Integer.class);
if (sendCount != null && sendCount >= maxSendCount) {
throw new RuntimeException("验证码发送次数过多,请" + timeWindowSeconds / 60 + "分钟后再试");
}
// 4. 次数累加(首次发送则设为1,否则+1)
int newCount = sendCount == null ? 1 : sendCount + 1;
redisCacheUtil.setCacheWithExpire(countKey, newCount, timeWindowSeconds, TimeUnit.SECONDS);
}
/**
* 生成并存储验证码(需先调用checkSendFrequency校验频率)
* @param phone 手机号
* @return 生成的验证码
*/
public String generateAndSaveCode(String phone) {
// 1. 生成6位数字验证码
String code = RandomUtil.randomNumbers(codeLength);
// 2. 存储验证码(5分钟过期)
String codeKey = "SMS_CODE:" + phone;
redisCacheUtil.setCacheWithExpire(codeKey, code, codeExpire, TimeUnit.SECONDS);
// 3. 设置冷却期(60秒过期)
String coolDownKey = "SMS_COOL_DOWN:" + phone;
redisCacheUtil.setCacheWithExpire(coolDownKey, System.currentTimeMillis(), coolDownSeconds, TimeUnit.SECONDS);
String msg = "【广联赛讯】您的验证码:%s, 该验证码 %s 分钟内有效。";
gscApiInvoker.sendMsg(phone, String.format(msg, code, codeExpire / 60));
// 4. 发送短信
log.info("向手机号{}发送验证码:{}(冷却期{}秒,5分钟内已发送{}次)",
phone, code, coolDownSeconds,
redisCacheUtil.getCache("SMS_SEND_COUNT:" + phone, Integer.class));
return code;
}
/**
* 验证验证码是否正确
* @param phone 手机号
* @param code 前端提交的验证码
* @return 是否正确
*/
public boolean validateCode(String phone, String code) {
String codeKey = "SMS_CODE:" + phone;
String redisCode = redisCacheUtil.getCache(codeKey, String.class);
if (redisCode == null) {
return false;
}
// 验证通过后删除验证码(防止重复使用)
boolean isValid = redisCode.equals(code);
if (isValid) {
redisCacheUtil.deleteCache(codeKey);
}
return isValid;
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.util;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.summerframework.web.config.JwtProperties;
import java.util.concurrent.TimeUnit;
/**
* Token缓存工具类:Redis存储Token
*/
@Component
@RequiredArgsConstructor
public class TokenCacheUtil {
private final RedisCacheUtil redisCacheUtil;
private final static String CACHE_PREFIX = "TOKEN:%s";
private final JwtProperties jwtProperties;
/**
* 缓存Token(key=TOKEN_手机号,value=Token,有效期30天)
*/
public void cacheToken(String phone, String token) {
redisCacheUtil.setCacheWithExpire(genKey(phone), token, jwtProperties.getExpiration(), TimeUnit.DAYS);
}
/**
* 校验Token是否有效(Redis中存在且匹配)
*/
public boolean validateToken(String phone, String token) {
String cachedToken = redisCacheUtil.getCache(genKey( phone), String.class);
return token != null && token.equals(cachedToken);
}
/**
* 移除Token(退出登录)
*/
public void removeToken(String phone) {
redisCacheUtil.deleteCache(genKey( phone));
}
private String genKey(String phone) {
return String.format(CACHE_PREFIX, phone);
}
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.glsx.aus</groupId>
<artifactId>aus</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>aus-inspector</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 内部模块依赖 -->
<dependency>
<groupId>com.glsx.aus</groupId>
<artifactId>aus-framework</artifactId>
</dependency>
<dependency>
<groupId>com.glsx.aus</groupId>
<artifactId>aus-core</artifactId>
</dependency>
<dependency>
<groupId>com.glsx.aus</groupId>
<artifactId>aus-gsc</artifactId>
</dependency>
<!-- 第三方基础依赖 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
</dependency>
<!-- Spring Boot 核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Cloud 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<!-- 序列化/JSON 相关依赖 -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5-jakarta</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!-- Thymeleaf 扩展依赖 -->
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<!-- 安全/工具类依赖 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 微信/企业微信相关依赖 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
</dependency>
<dependency>
<groupId>io.github.swalikh</groupId>
<artifactId>wework-wehook-starter</artifactId>
</dependency>
<!-- Excel 处理依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
<!-- 数据库驱动(运行时依赖) -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok(编译时依赖) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- Spring Boot 配置处理器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.github.xingfudeshi</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<finalName>aus-admin-1.0.0</finalName>
<plugins>
<!-- 编译插件:配置Lombok和Spring Boot配置处理器 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring.boot.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<!-- Spring Boot 打包插件(核心配置) -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
<!-- 排除slf4j-simple依赖 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>exclude-slf4j-simple</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<excludeGroupIds>org.slf4j</excludeGroupIds>
<excludeArtifactIds>slf4j-simple</excludeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.summerframework.orm.BaseRepositoryFactoryBean;
@EnableJpaRepositories(basePackages = {"com.glsx.usedcar.module", "org.summerframework"}, repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class)
@EnableAsync
@EnableCaching
@EntityScan(basePackages = {"com.glsx.usedcar", "org.summerframework"})
@ComponentScan(basePackages = {"com.glsx.usedcar", "org.summerframework.core", "org.summerframework.orm", "org.summerframework.web",
"org.summerframework.cache", "org.summerframework.storage", "org.summerframework.log", "org.summerframework.security", "org.summerframework.pay", "com.sayalala"})
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@EnableScheduling
@EnableJpaAuditing
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解:标记需要登录认证的接口
*/
@Target({ElementType.METHOD, ElementType.TYPE}) // 可标记在方法/类上
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
public @interface RequireLogin {
// 可扩展属性,比如是否忽略认证(默认false)
boolean required() default true;
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* <pre>
* Knife4j/OpenAPI配置类
* 用于启用和配置Swagger文档
* 访问地址:<a href="http://localhost:6903/admin/doc.html">aus-admin API文档</a>
* </pre>
* @author yangwei
* @since 2026/2/9 18:25
*/
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenApi() {
return new OpenAPI()
.info(new Info()
.title("aus-admin API文档")
.version("1.0.0")
.description("专电优拍后台管理系统API接口文档")
.contact(new Contact()
.name("开发团队")
.email("yangwei@didihu.com.cn")
.url("https://gitee.com/foutouren/aus.git"))
.license(new License()
.name("Apache 2.0")
.url("http://www.apache.org/licenses/LICENSE-2.0.html")));
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.config;
import com.glsx.usedcar.interceptor.LoginInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Web配置:注册拦截器
*/
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册登录拦截器,拦截所有请求(排除登录/注册/发送验证码接口)
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(
"/api/auth/send-code",
"/api/auth/login"
);
}
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.controller;
import com.glsx.usedcar.annotation.RequireLogin;
import com.glsx.usedcar.req.LoginByCodeReq;
import com.glsx.usedcar.req.VerifyCodeReq;
import com.glsx.usedcar.resp.LoginByCodeResp;
import com.glsx.usedcar.token.JwtProvider;
import com.glsx.usedcar.module.inspect.entity.Inspector;
import com.glsx.usedcar.module.inspect.service.InspectorService;
import com.glsx.usedcar.resp.BaseResp;
import com.glsx.usedcar.util.SmsCodeUtil;
import com.glsx.usedcar.util.TokenCacheUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import static com.glsx.usedcar.conts.Constants.LOGIN_INSPECTOR;
/**
* 认证控制器:登录/注册/测试接口
*/
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final JwtProvider jwtProvider;
private final SmsCodeUtil smsCodeUtil;
private final TokenCacheUtil tokenCacheUtil;
private final InspectorService inspectorService;
@Value("${sms.code-expire:300}") // 验证码有效期5分钟(秒)
private int codeExpire;
/**
* 发送验证码(带防刷控制)
*/
@PostMapping("/send-code")
public BaseResp<Boolean> sendCode(@RequestBody @Valid VerifyCodeReq req) {
try {
// 校验用户是否存在
Inspector inspector = inspectorService.findByPhone(req.getPhone());
if (inspector == null) {
return BaseResp.fail("用户不存在");
}
// 校验发送频率
smsCodeUtil.checkSendFrequency(req.getPhone());
// 频率校验通过,生成并存储验证码
smsCodeUtil.generateAndSaveCode(req.getPhone());
return BaseResp.success(true);
} catch (RuntimeException e) {
// 捕获防刷异常,返回友好提示
log.warn("手机号{}发送验证码失败:{}", req.getPhone(), e.getMessage());
return BaseResp.fail("发送验证码失败");
}
}
/**
* 验证码登录
*/
@PostMapping("/login")
public BaseResp<LoginByCodeResp> login(@RequestBody LoginByCodeReq loginRequest) {
String phone = loginRequest.getPhone();
Inspector inspector = inspectorService.findByPhone(phone);
if (inspector == null) {
return BaseResp.fail("用户不存在");
}
String code = loginRequest.getVerifyCode();
if (!smsCodeUtil.validateCode(phone, code)) {
return BaseResp.fail("验证码错误或已过期");
}
Date expireTime = jwtProvider.getExpireTime();
String token = jwtProvider.generateUser(phone, expireTime);
tokenCacheUtil.cacheToken(phone, token);
LoginByCodeResp resp = new LoginByCodeResp();
resp.setToken(token);
resp.setPhone(phone);
resp.setExpireTime(expireTime);
return BaseResp.success(resp);
}
/**
* 退出登录(需要Token)
*/
@PostMapping("/logout")
@RequireLogin
public BaseResp<Boolean> logout(HttpServletRequest request) {
String phone = (String) request.getAttribute(LOGIN_INSPECTOR);
tokenCacheUtil.removeToken(phone);
return BaseResp.success(true);
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.controller;
import com.glsx.usedcar.annotation.RequireLogin;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
public class TestController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
@RequireLogin
@RequestMapping("/hello2")
public String hello2() {
return "hello world2";
}
}
package com.glsx.usedcar.conts;
/**
* 常量
*/
public interface Constants {
String LOGIN_INSPECTOR = "LOGIN_INSPECTOR";
}
package com.glsx.usedcar.interceptor;
import com.glsx.usedcar.annotation.RequireLogin;
import com.glsx.usedcar.token.JwtProvider;
import com.glsx.usedcar.util.TokenCacheUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.PrintWriter;
import static com.glsx.usedcar.conts.Constants.LOGIN_INSPECTOR;
/**
* 登录认证拦截器:处理@RequireLogin注解,校验Token
*/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginInterceptor implements HandlerInterceptor {
private final JwtProvider jwtProvider;
private final TokenCacheUtil tokenCacheUtil;
@Value("${jwt.header:Authorization }")
private String jwtHeader;
@Value("${jwt.token-prefix:Bearer }")
private String tokenPrefix;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
RequireLogin classAnnotation = handlerMethod.getBeanType().getAnnotation(RequireLogin.class);
RequireLogin methodAnnotation = handlerMethod.getMethodAnnotation(RequireLogin.class);
RequireLogin requireLogin = methodAnnotation != null ? methodAnnotation : classAnnotation;
if (requireLogin == null || !requireLogin.required()) {
return true;
}
// 有@RequireLogin注解,校验Token
String authHeader = request.getHeader(jwtHeader);
if (authHeader == null || !authHeader.startsWith(tokenPrefix)) {
returnErrorResponse(response, "未登录或Token格式错误");
return false;
}
// 4. 解析Token(去掉前缀)
String token = authHeader.substring(tokenPrefix.length()).trim();
String phone = jwtProvider.verify(token);
if (phone == null) {
returnErrorResponse(response, "Token无效或已过期");
return false;
}
if (tokenCacheUtil.validateToken(phone, token)) {
returnErrorResponse(response, "Token无效或已过期");
return false;
}
request.setAttribute(LOGIN_INSPECTOR, phone);
return true;
}
/**
* 返回统一的401错误响应(JSON格式)
*/
private void returnErrorResponse(HttpServletResponse response, String message) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 401状态码
try (PrintWriter writer = response.getWriter()) {
writer.write(String.format("{\"code\":401,\"message\":\"%s\"}", message));
writer.flush();
} catch (Exception e) {
log.error("返回认证错误响应失败:", e);
}
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.req;
import lombok.Data;
@Data
public class LoginByCodeReq {
private String phone;
private String verifyCode;
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.req;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
// 验证码请求参数
@Data
public class VerifyCodeReq {
@NotNull
@Pattern(
regexp = "^1[3-9]\\d{9}$",
message = "手机号格式错误,请输入11位有效手机号"
)
private String phone;
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.resp;
import lombok.Data;
import java.util.Date;
/**
*
*/
@Data
public class LoginByCodeResp {
private String token;
private Date expireTime;
private String phone;
}
package com.glsx.usedcar.security;
import com.glsx.usedcar.module.security.dao.*;
import com.glsx.usedcar.module.security.entity.User;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.summerframework.security.IPermission;
import org.summerframework.security.SecurityProvider;
import java.util.List;
import java.util.Objects;
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class SecurityService extends SecurityProvider {
@Resource
private UserDao userDao;
@Resource
private RoleDao roleDao;
@Resource
private PermissionDao permissionDao;
@Override
public List<? extends IPermission> getAllPermissions() {
return permissionDao.findDetailPermissions();
}
@Override
public List<String> getPrivilegeCodesByUserName(String userName) {
return permissionDao.findPrivilegeCodesByUserName(userName);
}
@Override
public List<UserDetails> getUsersByUserNameIn(List<String> userNames) {
return null;
}
@Override
public User getUserByUserName(String userName) {
return userDao.findTopByUserName(userName);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findTopByUserName(username);
if (Objects.isNull(user)) {
throw new UsernameNotFoundException("User name " + username + " not found.");
}
return user;
}
}
package com.glsx.usedcar.token;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.summerframework.web.auth.AbstractJwtProvider;
import java.util.Date;
/**
* JWT认证服务
*/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class JwtProvider extends AbstractJwtProvider {
/**
* 生成token
*
* @return token
*/
public String generateUser(String phone, Date expireTime) {
try {
return JWT.create()
.withIssuer(jwtProperties.getIssuer())
.withIssuedAt(new Date())
.withExpiresAt(expireTime)
.withJWTId(phone)
.withSubject(phone)
.sign(algorithm);
} catch (IllegalArgumentException | TokenExpiredException e) {
return null;
}
}
public Date getExpireTime() {
return new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000);
}
/**
* 解析token
*
* @param token token
* @return phone
*/
public String verify(String token) {
if (token == null) {
return null;
}
try {
DecodedJWT jwt = verifier.verify(token);
return jwt.getSubject();
} catch (Exception e) {
return null;
}
}
}
logging:
level:
org.springframework.web: info
org.springframework.security: info
config: classpath:logback-config.xml
spring:
application:
#应用名称
name: aus-inspector
cloud:
config:
#配置文件前导名称
name: common,aus-inspector
#配置文件后导名称
profile: dev
#配置中心地址
uri: http://127.0.0.1:6900
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<contextName>logback</contextName>
<!-- 读取环境变量 APP_LOG_DIR,若未配置则使用默认值 ./logs -->
<springProperty scope="context" name="LOG_DIR" source="logging.location"/>
<property name="CONSOLE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss SSS} | %highlight(%-5level) | %boldGreen(%logger) | %msg%n"/>
<property name="PACKET_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss SSS} | %msg%n"/>
<!--输出到控制台-->
<appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="fileAllLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径-->
<fileNamePattern>${LOG_DIR}/aus-inspector/all%d.log</fileNamePattern>
<maxHistory>40</maxHistory>
</rollingPolicy>
</appender>
<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<file>${LOG_DIR}/aus-inspector/error.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss SSS} [%thread] %logger{36} - %msg%n</pattern>
</encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径-->
<fileNamePattern>${LOG_DIR}/aus-inspector/error%d.log</fileNamePattern>
<maxHistory>40</maxHistory>
</rollingPolicy>
</appender>
<appender name="consoleErrorLog" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss SSS} [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileAllLog"/>
<appender-ref ref="fileErrorLog"/>
<appender-ref ref="consoleErrorLog"/>
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
...@@ -90,6 +90,7 @@ ...@@ -90,6 +90,7 @@
<module>aus-framework</module> <module>aus-framework</module>
<module>aus-gsc</module> <module>aus-gsc</module>
<module>aus-task</module> <module>aus-task</module>
<module>aus-inspector</module>
</modules> </modules>
<repositories> <repositories>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!