初始化项目

This commit is contained in:
ah--desktop
2025-09-10 00:33:25 +08:00
commit a305dcdc3f
1406 changed files with 114976 additions and 0 deletions
@@ -0,0 +1,102 @@
package top.xyquan.ecomdmbbackend.utils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
/**
* 当前用户上下文工具类
* 提供更安全的当前用户信息获取方式
*/
@Component
public class CurrentUserContext {
private final JwtUtils jwtUtils;
public CurrentUserContext(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
* 获取当前用户Token负载信息
*
* @return Token负载信息
* @throws BusinessException 如果无法获取用户信息
*/
public TokenPayload getCurrentUserPayload() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication.getCredentials() == null) {
throw new BusinessException("用户未登录");
}
String token = authentication.getCredentials().toString();
return jwtUtils.getPayloadFromToken(token);
}
/**
* 获取当前用户公司ID
*
* @return 公司ID
* @throws BusinessException 如果无法获取公司信息
*/
public Long getCurrentCompanyId() {
TokenPayload payload = getCurrentUserPayload();
if (payload.getCompanyId() == null) {
throw new BusinessException("无法获取公司信息");
}
return payload.getCompanyId();
}
/**
* 获取当前用户ID
*
* @return 用户ID
* @throws BusinessException 如果无法获取用户信息
*/
public Long getCurrentUserId() {
TokenPayload payload = getCurrentUserPayload();
try {
return Long.parseLong(payload.getUserId());
} catch (NumberFormatException e) {
throw new BusinessException("用户ID格式错误");
}
}
/**
* 获取当前用户角色
*
* @return 用户角色
*/
public String getCurrentUserRole() {
return getCurrentUserPayload().getRole();
}
/**
* 获取当前用户岗位ID
*
* @return 岗位ID
*/
public Long getCurrentUserPositionId() {
return getCurrentUserPayload().getPositionId();
}
/**
* 获取当前用户认证信息
*
* @return 认证信息
*/
public Authentication getCurrentAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 检查是否已登录
*
* @return 是否已登录
*/
public boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && authentication.isAuthenticated();
}
}
@@ -0,0 +1,129 @@
package top.xyquan.ecomdmbbackend.utils;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
/**
* 文件上传工具类
*/
public class FileUploadUtils {
// 静态资源目录
private static final String UPLOAD_DIR = "static/uploads";
// 图片目录
private static final String IMAGE_DIR = "images";
// 文件目录
private static final String FILE_DIR = "files";
/**
* 上传图片
*/
public static String uploadImage(MultipartFile file) {
return uploadFile(file, IMAGE_DIR);
}
/**
* 上传文件
*/
public static String uploadFile(MultipartFile file) {
return uploadFile(file, FILE_DIR);
}
/**
* 上传文件到指定目录
*/
private static String uploadFile(MultipartFile file, String subDir) {
if (file == null || file.isEmpty()) {
throw new BusinessException("文件不能为空");
}
// 检查文件大小(限制为50MB)
if (file.getSize() > 50 * 1024 * 1024) {
throw new BusinessException("文件大小不能超过50MB");
}
try {
// 创建上传目录
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
String uploadPath = UPLOAD_DIR + "/" + subDir + "/" + datePath;
Path dirPath = Paths.get(uploadPath);
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath);
}
// 生成唯一文件名
String originalFilename = file.getOriginalFilename();
String extension = "";
if (originalFilename != null && originalFilename.contains(".")) {
extension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String filename = UUID.randomUUID().toString().replace("-", "") + extension;
// 保存文件
Path filePath = dirPath.resolve(filename);
Files.copy(file.getInputStream(), filePath);
// 返回相对路径
return "/" + uploadPath + "/" + filename;
} catch (IOException e) {
throw new BusinessException("文件上传失败: " + e.getMessage());
}
}
/**
* 删除文件
*/
public static void deleteFile(String filePath) {
if (filePath == null || filePath.isEmpty()) {
return;
}
try {
// 移除开头的斜杠
if (filePath.startsWith("/")) {
filePath = filePath.substring(1);
}
Path path = Paths.get(filePath);
if (Files.exists(path)) {
Files.delete(path);
}
} catch (IOException e) {
// 删除失败不影响主流程
System.err.println("删除文件失败: " + e.getMessage());
}
}
/**
* 获取文件扩展名
*/
public static String getFileExtension(String filename) {
if (filename == null || filename.isEmpty()) {
return "";
}
int lastDotIndex = filename.lastIndexOf(".");
if (lastDotIndex > 0) {
return filename.substring(lastDotIndex + 1).toLowerCase();
}
return "";
}
/**
* 检查是否为图片文件
*/
public static boolean isImageFile(String filename) {
String extension = getFileExtension(filename);
return extension.matches("(jpg|jpeg|png|gif|bmp|webp)");
}
}
@@ -0,0 +1,197 @@
package top.xyquan.ecomdmbbackend.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
/**
* JWT工具类
*/
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secretKey;
@Value("${jwt.expiration}")
private long expirationTime;
private SecretKey key;
/**
* 初始化SecretKey
*/
private void initKey() {
if (key == null) {
this.key = Keys.hmacShaKeyFor(secretKey.getBytes());
}
}
/**
* 生成JWT令牌
*
* @param payload Token负载信息
* @return JWT令牌
*/
public String generateToken(TokenPayload payload) {
initKey();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expirationTime * 1000); // 转换为毫秒
return Jwts.builder()
.setSubject(payload.getUserId())
.claim("companyId", payload.getCompanyId())
.claim("role", payload.getRole())
.claim("positionId", payload.getPositionId())
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
/**
* 生成JWT令牌(兼容旧版本)
*
* @param userId 用户ID
* @param companyId 公司ID
* @return JWT令牌
*/
public String generateToken(String userId, Long companyId) {
TokenPayload payload = TokenPayload.builder()
.userId(userId)
.companyId(companyId)
.build();
return generateToken(payload);
}
/**
* 从JWT令牌中获取完整的负载信息
*
* @param token JWT令牌
* @return Token负载信息
*/
public TokenPayload getPayloadFromToken(String token) {
initKey();
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
return TokenPayload.builder()
.userId(claims.getSubject())
.companyId(getLongFromClaims(claims, "companyId"))
.role(getStringFromClaims(claims, "role"))
.positionId(getLongFromClaims(claims, "positionId"))
.build();
}
/**
* 从JWT令牌中获取用户ID
*
* @param token JWT令牌
* @return 用户ID
*/
public String getUserIdFromToken(String token) {
return getPayloadFromToken(token).getUserId();
}
/**
* 从JWT令牌中获取公司ID
*
* @param token JWT令牌
* @return 公司ID
*/
public Long getCompanyIdFromToken(String token) {
return getPayloadFromToken(token).getCompanyId();
}
/**
* 从JWT令牌中获取用户角色
*
* @param token JWT令牌
* @return 用户角色
*/
public String getRoleFromToken(String token) {
return getPayloadFromToken(token).getRole();
}
/**
* 从JWT令牌中获取岗位ID
*
* @param token JWT令牌
* @return 岗位ID
*/
public Long getPositionIdFromToken(String token) {
return getPayloadFromToken(token).getPositionId();
}
/**
* 从Claims中安全获取Long值
*/
private Long getLongFromClaims(Claims claims, String key) {
Object value = claims.get(key);
if (value != null) {
if (value instanceof Integer) {
return ((Integer) value).longValue();
} else if (value instanceof Long) {
return (Long) value;
}
}
return null;
}
/**
* 从Claims中安全获取String值
*/
private String getStringFromClaims(Claims claims, String key) {
Object value = claims.get(key);
return value != null ? value.toString() : null;
}
/**
* 验证JWT令牌
*
* @param token JWT令牌
* @return 是否有效
*/
public boolean validateToken(String token) {
try {
initKey();
Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 检查令牌是否过期
*
* @param token JWT令牌
* @return 是否过期
*/
public boolean isTokenExpired(String token) {
try {
initKey();
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
return claims.getExpiration().before(new Date());
} catch (Exception e) {
return true;
}
}
}
@@ -0,0 +1,100 @@
package top.xyquan.ecomdmbbackend.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.sys.service.PermissionCheckService;
/**
* 权限控制工具类
* 提供静态方法进行权限检查
*/
@Component
public class PermissionUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
PermissionUtils.applicationContext = applicationContext;
}
/**
* 检查当前用户是否有指定权限
*
* @param permissionCode 权限码
* @return 是否有权限
*/
public static boolean hasPermission(String permissionCode) {
try {
PermissionCheckService permissionCheckService = applicationContext.getBean(PermissionCheckService.class);
CurrentUserContext currentUserContext = applicationContext.getBean(CurrentUserContext.class);
String role = currentUserContext.getCurrentUserPayload().getRole();
Long positionId = currentUserContext.getCurrentUserPayload().getPositionId();
Long companyId = currentUserContext.getCurrentCompanyId();
return permissionCheckService.hasPermissionByRole(role, permissionCode, positionId, companyId);
} catch (Exception e) {
return false;
}
}
/**
* 检查当前用户是否有指定角色
*
* @param role 角色
* @return 是否有角色
*/
public static boolean hasRole(String role) {
try {
CurrentUserContext currentUserContext = applicationContext.getBean(CurrentUserContext.class);
String currentRole = currentUserContext.getCurrentUserPayload().getRole();
return role.equals(currentRole);
} catch (Exception e) {
return false;
}
}
/**
* 检查当前用户是否是超级管理员
*
* @return 是否是超级管理员
*/
public static boolean isSuper() {
return hasRole("super");
}
/**
* 检查当前用户是否是公司管理员
*
* @return 是否是公司管理员
*/
public static boolean isCompany() {
return hasRole("company");
}
/**
* 检查当前用户是否是普通用户
*
* @return 是否是普通用户
*/
public static boolean isUser() {
return hasRole("user");
}
/**
* 获取当前用户角色
*
* @return 用户角色
*/
public static String getCurrentRole() {
try {
CurrentUserContext currentUserContext = applicationContext.getBean(CurrentUserContext.class);
return currentUserContext.getCurrentUserPayload().getRole();
} catch (Exception e) {
return null;
}
}
}
@@ -0,0 +1,66 @@
package top.xyquan.ecomdmbbackend.utils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Security工具类
*/
public class SecurityUtils {
/**
* 获取当前登录用户ID
*
* @return 用户ID
*/
public static Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() != null) {
String userId = authentication.getPrincipal().toString();
try {
return Long.parseLong(userId);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
/**
* 获取当前登录用户公司ID
*
* @return 公司ID
*/
public static Long getCurrentUserCompanyId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getCredentials() != null) {
String token = authentication.getCredentials().toString();
try {
JwtUtils jwtUtils = new JwtUtils();
return jwtUtils.getCompanyIdFromToken(token);
} catch (Exception e) {
return null;
}
}
return null;
}
/**
* 获取当前登录用户认证信息
*
* @return 认证信息
*/
public static Authentication getCurrentAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 检查是否已登录
*
* @return 是否已登录
*/
public static boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && authentication.isAuthenticated();
}
}
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.utils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* JWT Token负载信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TokenPayload {
/**
* 用户ID
*/
private String userId;
/**
* 公司ID
*/
private Long companyId;
/**
* 用户角色
*/
private String role;
/**
* 岗位ID
*/
private Long positionId;
}