This commit is contained in:
Mrhongxing committed 2026-11-12 02:49:08 +08:00
1 parent 68780851dd
commit 619e5665e2
16 files changed
+368 -45

No files matched your search

@@ -12,6 +12,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.tianze.www.dto.Jwt;
import com.tianze.www.entity.LoginUser;
import com.tianze.www.util.JwtUtil;
@@ -20,13 +21,13 @@ import java.util.List;
/**
* 旁路式 JWT 过滤器:
* - 有合法 token → 把认证信息塞进 SecurityContext
* - 无 token / token 无效 → 什么都不做,直接放行
* - 从不抛异常、从不返回 401
* - 有合法 token → 把认证信息塞进 SecurityContext
* - 无 token / token 无效 → 什么都不做,直接放行
* - 从不抛异常、从不返回 401
* 因此对现有 Controller 逻辑零影响。
*/
@Component //声明这是一个组件类,Spring 会自动扫描并注册为 Bean
@RequiredArgsConstructor //自动生成构造函数,注入依赖
@Component // 声明这是一个组件类,Spring 会自动扫描并注册为 Bean
@RequiredArgsConstructor // 自动生成构造函数,注入依赖
public class JwtAuthenticationFilter extends OncePerRequestFilter {
public static final String HEADER = "Authorization";
@@ -36,8 +37,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain chain) throws ServletException, IOException {
@NonNull HttpServletResponse response,
@NonNull FilterChain chain) throws ServletException, IOException {
// 预检请求不带 Authorization,直接放行
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
@@ -47,14 +48,15 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
String header = request.getHeader(HEADER);
if (header != null && header.startsWith(PREFIX)) {
LoginUser loginUser = jwtUtil.parse(header.substring(PREFIX.length()));
if (loginUser != null
Jwt jwt = jwtUtil.parse(header.substring(PREFIX.length()));
if (jwt != null
&& SecurityContextHolder.getContext().getAuthentication() == null) {
// 根据角色设置权限
String role = loginUser.getRole() != null && loginUser.getRole() == "1"
? "ROLE_ADMIN" : "ROLE_USER";
String role = jwt.getRole() != null && jwt.getRole().equals("admin")
? "ROLE_ADMIN"
: "ROLE_USER";
var auth = new UsernamePasswordAuthenticationToken(
loginUser, null, List.of(new SimpleGrantedAuthority(role)));
jwt, null, List.of(new SimpleGrantedAuthority(role)));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
@@ -9,7 +9,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("cyou.tianshu.charging.mapper") // 扫描mapper接口
@MapperScan("com.tianze.www.mapper") // 扫描mapper接口
public class MybatisPlusConfig {
/**
@@ -44,7 +44,7 @@ public class SecurityConfig {
// ← 授权规则:两种模式二选一,见下文
.authorizeHttpRequests(authz -> authz
.requestMatchers("/apiForChargingStation/user/login", "/apiForChargingStation/user/register", "/error").permitAll()
.requestMatchers("/apiForTianze/login", "/apiForTianze/register", "/error", "/apiForTianze/addUser", "/apiForTianze/loginByToken").permitAll()
.anyRequest().authenticated()
)
@@ -0,0 +1,93 @@
package com.tianze.www.controller;
import com.tianze.www.service.UserService;
import com.tianze.www.util.JwtUtil;
import com.tianze.www.dto.LoginResponse;
import com.tianze.www.dto.SearchRequest;
import com.tianze.www.dto.SearchResponse;
import com.tianze.www.dto.UserList;
import com.tianze.www.entity.UserInfo;
import com.tianze.www.dto.AddUserRequest;
import com.tianze.www.dto.LoginRequest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController // @RestController注解表示这是一个控制器类,处理HTTP请求
@RequestMapping ("apiForTianze") // @RequestMapping注解指定了该控制器类的基础URL路径为"/user"
public class UserController {
@Autowired // @Autowired注解用于自动注入UserService实例
private UserService userService;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login") // @PostMapping注解表示该方法处理HTTP POST请求,路径为"/login"
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
LoginResponse response = new LoginResponse();
UserInfo UserInfo = userService.login(loginRequest); // 调用UserService的login方法进行登录验证
if (UserInfo != null) {
response.setId(UserInfo.getId());
response.setPlateNumber(UserInfo.getPlateNumber());
response.setRole(UserInfo.getRole());
response.setToken(jwtUtil.generate(UserInfo)); // 登录成功,返回令牌
return ResponseEntity.ok(response);
} else {
response.setToken("login-failed"); // 登录失败,返回空令牌
return ResponseEntity.status(202).body(response); // 登录失败,返回401 Unauthorized状态码
}
}
@PostMapping ("/loginByToken") // @PostMapping注解表示该方法处理HTTP POST请求,路径为"/register"
public ResponseEntity<LoginResponse> loginByToken(@RequestParam String token) {
LoginResponse response = new LoginResponse();
UserInfo UserInfo = userService.loginByToken(token); // 调用UserService的login方法进行登录验证
if (UserInfo != null) {
response.setId(UserInfo.getId());
response.setPlateNumber(UserInfo.getPlateNumber());
response.setRole(UserInfo.getRole());
response.setToken(jwtUtil.generate(UserInfo)); // 登录成功,返回令牌
return ResponseEntity.ok(response);
} else {
response.setToken("login-failed"); // 登录失败,返回空令牌
return ResponseEntity.status(202).body(response); // 登录失败,返回401 Unauthorized状态码
}
}
@PostMapping ("/register") // @PostMapping注解表示该方法处理HTTP POST请求,路径为"/register"
public ResponseEntity<String> register(@RequestBody UserInfo userInfo) {
// 这里可以调用UserService的注册方法进行用户注册
// 例如:userService.register(userInfo);
return ResponseEntity.ok("User registered successfully");
}
@PostMapping ("/addUser") // @PostMapping注解表示该方法处理HTTP POST请求,路径为"/update"
public ResponseEntity<String> addUser(@RequestBody AddUserRequest addUserRequest) {
boolean success = userService.addUser(addUserRequest);
if (!success) {
return ResponseEntity.status(202).body("Failed to add user");
}
return ResponseEntity.ok("User added successfully");
}
@PostMapping ("/users") // @PostMapping注解表示该方法处理HTTP POST请求,路径为"/update"
public ResponseEntity<SearchResponse> getUsers(@RequestBody SearchRequest searchRequest) {
// 这里可以调用UserService的方法获取用户列表
// 例如:List<UserInfo> users = userService.getAllUsers();
List<UserInfo> users = userService.getUsers(searchRequest.getKeyword(), searchRequest.getPage(), searchRequest.getPageSize());
long totalCount = userService.countUsers(searchRequest.getKeyword());
List<UserList> userList = users.stream().map(user -> {
UserList userListItem = new UserList();
userListItem.setId(user.getId());
userListItem.setPlateNumber(user.getPlateNumber());
userListItem.setStatus(user.getStatus());
userListItem.setUpdatedAt(user.getUpdatedAt());
return userListItem;
}).toList();
SearchResponse response = new SearchResponse();
response.setList(userList);
response.setTotal((int) totalCount);
return ResponseEntity.ok(response);
}
}
@@ -0,0 +1,14 @@
package com.tianze.www.dto;
import lombok.Data;
@Data
public class AddUserRequest {
private String plateNumber;
private String password;
private String role;
private String status;
private String carModel;
private String carColor;
private Integer purchaseYear;
}
+15
View File
@@ -0,0 +1,15 @@
package com.tianze.www.dto;
import lombok.Data;
@Data
public class Jwt {
private Long id;
private String plateNumber;
private String role;
public Jwt(Long id, String plateNumber, String role) {
this.id = id;
this.plateNumber = plateNumber;
this.role = role;
}
}
@@ -0,0 +1,10 @@
package com.tianze.www.dto;
import lombok.Data;
@Data
public class LoginRequest {
private String plateNumber;
private String password;
private Boolean remember;
}
@@ -0,0 +1,11 @@
package com.tianze.www.dto;
import lombok.Data;
@Data
public class LoginResponse {
private Long id;
private String plateNumber;
private String role;
private String token;
}
@@ -0,0 +1,10 @@
package com.tianze.www.dto;
import lombok.Data;
@Data
public class SearchRequest {
private Integer page;
private Integer pageSize;
private String keyword;
}
@@ -0,0 +1,11 @@
package com.tianze.www.dto;
import java.util.List;
import lombok.Data;
@Data
public class SearchResponse {
private List<UserList> list;
private Integer total;
}
@@ -0,0 +1,13 @@
package com.tianze.www.dto;
import java.time.LocalDateTime;
import lombok.Data;
@Data
public class UserList {
private Long id;
private String plateNumber;
private String status;
private LocalDateTime updatedAt;
}
@@ -1,5 +1,7 @@
package com.tianze.www.entity;
import java.time.LocalDate;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
@@ -10,40 +12,38 @@ import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor // 添加无参构造函数
@AllArgsConstructor // 添加全参构造函数
@TableName("smart_charging_user")
@TableName("customer_vehicle")
public class UserInfo {
@TableId(type=IdType.AUTO)
private Long id;// 用户ID
@TableField("name")
private String name;// 用户名
@TableField("email")
private String email;// 用户邮箱
@TableField("plate_number")
private String plateNumber;// 用户名
@TableField("password")
private String password;// 用户密码
@TableField("role")
private String role;// 用户角色
@TableField("created_at")
private java.time.LocalDateTime created_at;// 创建时间
private java.time.LocalDateTime createdAt;// 创建时间
@TableField("updated_at")
private java.time.LocalDateTime updated_at;// 更新时间
@TableField("phone")
private String phone;// 用户手机号
@TableField("car_type")
private String carType;// 用户车型
@TableField("car_brand")
private String carBrand;// 用户车品牌
public UserInfo(String username, String password) {
this.name = username;
private java.time.LocalDateTime updatedAt;// 更新时间
@TableField("status")
private String status;// 用户状态
@TableField("car_model")
private String carModel;// 用户车型
@TableField("car_color")
private String carColor;// 用户车颜色
@TableField("purchase_year")
private Integer purchaseYear;// 用户购车日期
@TableField("oil_type")
private String oilType;// 用户油类型
@TableField ("oil_cycle")
private String oilCycle;// 用户油耗周期
@TableField("last_oil_date")
private LocalDate lastOilDate;// 用户上次换油日期
@TableField("next_oil_date")
private LocalDate nextOilDate;// 用户下次换油日期
public UserInfo(String plateNumber, String password) {
this.plateNumber = plateNumber;
this.password = password;
}
public UserInfo(String username, String password, String phone) {
this.name = username;
this.password = password;
this.phone = phone;
}
public UserInfo(Long id, String phone, String role) {
this.id = id;
this.phone = phone;
this.role = role;
}
}
@@ -0,0 +1,82 @@
package com.tianze.www.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tianze.www.entity.UserInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserInfoMapper extends BaseMapper<UserInfo> {
/**
* 方式1:注解SQL(简单查询)
*/
@Select("<script>" +
"SELECT * FROM customer_vehicle " +
"<where>" +
" <if test='keyword != null and keyword != \"\"'>" +
" plate_number LIKE CONCAT('%', #{keyword}, '%') " +
" </if>" +
"</where>" +
"ORDER BY updated_at DESC " +
"LIMIT #{offset}, #{pageSize}" +
"</script>")
List<UserInfo> getUsers(@Param("keyword") String keyword,
@Param("offset") int offset,
@Param("pageSize") int pageSize);
@Select("<script>" +
"SELECT COUNT(*) FROM customer_vehicle " +
"<where>" +
" <if test='keyword != null and keyword != \"\"'>" +
" plate_number LIKE CONCAT('%', #{keyword}, '%') " +
" </if>" +
"</where>" +
"</script>")
long countUsers(@Param("keyword") String keyword);
@Select("SELECT * FROM customer_vehicle WHERE plate_number = #{plate_number} ORDER BY created_at DESC")
UserInfo findByPlateNumber(@Param("plate_number") String plateNumber);
@Select("SELECT * FROM customer_vehicle WHERE phone = #{phone} ORDER BY created_at DESC")
UserInfo findByPhone(@Param("phone") String phone);
@Select("SELECT COUNT(*) FROM customer_vehicle WHERE email = #{email}")
boolean existsByEmail(@Param("email") String email);
@Select("SELECT COUNT(*) FROM customer_vehicle WHERE phone = #{phone}")
boolean existsByPhone(@Param("phone") String phone);
@Insert("INSERT INTO customer_vehicle (" +
"plate_number, password, role, status, " +
"car_model, car_color, purchase_date, " +
"oil_type, oil_cycle, last_oil_date, next_oil_date" +
") VALUES (" +
"#{plateNumber}, #{password}, #{role}, #{status}, " +
"#{carModel}, #{carColor}, #{purchaseDate}, " +
"#{oilType}, #{oilCycle}, #{lastOilDate}, #{nextOilDate}" +
")")
@Options(useGeneratedKeys = true, keyProperty = "id") // 将自增ID返回给实体类的id属性
int insertUser(UserInfo userInfo);
/**
* 方式2:注解SQL带条件
*/
/*
* @Select("SELECT " +
* " DATE(start_time) as date, " +
* " COUNT(*) as totalCount, " +
* " SUM(consumption) as totalConsumption, " +
* " SUM(amount) as totalAmount " +
* "FROM charging_record " +
* "WHERE start_time BETWEEN #{startDate} AND #{endDate} " +
* "GROUP BY DATE(start_time)")
* List<ChargingStatisticsVO> statisticsByDate(@Param("startDate") String
* startDate,
*
* @Param("endDate") String endDate);
*/
}
@@ -0,0 +1,62 @@
package com.tianze.www.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tianze.www.dto.AddUserRequest;
import com.tianze.www.dto.Jwt;
import com.tianze.www.dto.LoginRequest;
import com.tianze.www.entity.UserInfo;
import com.tianze.www.mapper.UserInfoMapper;
import com.tianze.www.util.JwtUtil;
import com.tianze.www.util.PasswordUtil;
@Service
public class UserService {
@Autowired
private PasswordUtil passwordUtil;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserInfoMapper userInfoMapper;
public UserInfo login(LoginRequest loginRequest) {
UserInfo userInfo = userInfoMapper.findByPlateNumber(loginRequest.getPlateNumber());
if (userInfo != null && passwordUtil.matches(loginRequest.getPassword(), userInfo.getPassword())) {
return userInfo; // 返回用户信息
}
return null; // 返回null表示未找到用户
}
public UserInfo loginByToken(String token) {
Jwt jwt = jwtUtil.parse(token);
UserInfo userInfo = userInfoMapper.findByPlateNumber(jwt.getPlateNumber());
if (userInfo != null) {
return userInfo; // 返回用户信息
}
return null; // 返回null表示未找到用户
}
public boolean register(UserInfo userInfo) {
// 这里可以添加注册逻辑,例如保存用户信息到数据库
// 例如:userInfoMapper.insert(userInfo);
return true; // 返回true表示注册成功
}
public boolean addUser(AddUserRequest addUserRequest) {
UserInfo userInfo = new UserInfo();
userInfo.setPlateNumber(addUserRequest.getPlateNumber());
userInfo.setPassword(passwordUtil.encodePassword(addUserRequest.getPassword()));
userInfo.setRole(addUserRequest.getRole());
userInfo.setStatus(addUserRequest.getStatus());
userInfo.setCarModel(addUserRequest.getCarModel());
userInfo.setCarColor(addUserRequest.getCarColor());
userInfo.setPurchaseYear(addUserRequest.getPurchaseYear());
int rowsAffected = userInfoMapper.insert(userInfo);
return rowsAffected > 0; // 返回true表示插入成功,false表示插入失败
}
public List<UserInfo> getUsers(String keyword, int page, int pageSize) {
return userInfoMapper.getUsers(keyword, (page) * pageSize, pageSize);
}
public long countUsers(String keyword) {
return userInfoMapper.countUsers(keyword);
}
}
@@ -1,6 +1,6 @@
package com.tianze.www.util;
import com.tianze.www.entity.LoginUser;
import com.tianze.www.dto.Jwt;
import com.tianze.www.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
@@ -35,7 +35,7 @@ public class JwtUtil {
Instant now = Instant.now();
return Jwts.builder()
.subject(String.valueOf(user.getId()))
.claim("phone", user.getPhone())
.claim("phone", user.getPlateNumber())
.claim("role", user.getRole())
.issuedAt(Date.from(now))
.expiration(Date.from(now.plusMillis(expireMillis)))
@@ -47,7 +47,7 @@ public class JwtUtil {
* 解析失败(过期 / 签名错 / 格式错)统一返回 null。
* 让调用方(过滤器)保持"静默失败"语义,不抛异常。
*/
public LoginUser parse(String token) {
public Jwt parse(String token) {
try {
Claims c = Jwts.parser()
.verifyWith(key)
@@ -56,10 +56,10 @@ public class JwtUtil {
.getPayload();
String role = c.get("role", String.class); // JSON 数字反序列化可能是 Integer 或 Long
return new LoginUser(
return new Jwt(
Long.valueOf(c.getSubject()),
c.get("phone", String.class),
role == null ? null : role);
role);
} catch (JwtException | IllegalArgumentException e) {
return null;
}