23 Commits

Author SHA1 Message Date
KilLze
96b256d46e 加注释 2025-12-28 21:14:30 +08:00
KilLze
fca54a6f97 完成头像和背景上传,优化动态文件上传,修bug 2025-12-28 21:10:55 +08:00
KilLze
0f8f47de8e 用户查询个人信息功能 2025-12-28 19:57:05 +08:00
KilLze
2cb8ae5c3c 修bug,顺便修改接口名 2025-12-28 18:05:47 +08:00
KilLze
7abd6fe27d 修bug,顺便修改接口名 2025-12-28 17:53:16 +08:00
KilLze
dfc9508827 修bug,顺便修改接口名 2025-12-28 16:59:51 +08:00
KilLze
4c70bd3c6f 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
增加token过期验证
2025-12-28 02:17:09 +08:00
KilLze
d3c069967e 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
2025-12-28 02:04:25 +08:00
bao
4a2aff888a 配置redis
(cherry picked from commit ae0cca5437)
2025-12-27 19:37:01 +08:00
bao
0b0959fa80 增加User项目结构
(cherry picked from commit c329eaef79)
2025-12-27 19:28:19 +08:00
KilLze
4401a8a44a 用户密码登录功能完成 2025-12-27 19:25:03 +08:00
KilLze
55c7c9a03a 增加User项目结构 2025-12-27 17:37:35 +08:00
KilLze
a6716e32b6 增加登录返回数据实体类 2025-12-27 16:58:34 +08:00
KilLze
8506fbb7e4 将评论表实体类放入规范位置(李海洋赶紧修你的实体类) 2025-12-27 16:45:48 +08:00
KilLze
64bfb08257 将评论表实体类放入规范位置(李海洋赶紧修你的实体类) 2025-12-26 16:23:58 +08:00
KilLze
71dbb6fc82 在实体类中添加Serializable接口(其实无所谓) 2025-12-26 16:22:53 +08:00
KilLze
b6ac177148 Merge remote-tracking branch 'upstream/master' 2025-12-25 18:38:57 +08:00
KilLze
df463f2a52 修bug(这git怎么这么难用啊😡😡😡) 2025-12-25 18:37:20 +08:00
KilLze
34663e8e84 整合 2025-12-25 18:23:04 +08:00
KilLze
176e133a57 将删除动态优化为批量删除动态 2025-12-25 18:00:56 +08:00
KilLze
fd3a38efb5 为上传的文件分配目录动态的图片
动态图片存放在post/下的/yyyy/MM目录中
2025-12-25 17:54:52 +08:00
KilLze
7d99b30d73 Merge remote-tracking branch 'upstream/master' 2025-12-25 17:28:21 +08:00
KilLze
370e81f3c6 修改遍历图片审查,实现图片全部审察 2025-12-19 02:08:48 +08:00
33 changed files with 717 additions and 84 deletions

View File

@@ -1,14 +1,26 @@
package com.bao.dating.common; package com.bao.dating.common;
/**
* 响应状态码枚举
*/
public enum ResultCode { public enum ResultCode {
/** 成功 */
SUCCESS(200, "成功"), SUCCESS(200, "成功"),
/** 请求已成功处理 */
SUCCESS_REVIEW(201, "请求已成功处理"), SUCCESS_REVIEW(201, "请求已成功处理"),
/** 删除成功 */
SUCCESS_DELETE(204, "删除成功"), SUCCESS_DELETE(204, "删除成功"),
/** 参数错误 */
PARAM_ERROR(400, "参数错误"), PARAM_ERROR(400, "参数错误"),
/** 未登录或 Token 失效 */
UNAUTHORIZED(401, "未登录或 Token 失效"), UNAUTHORIZED(401, "未登录或 Token 失效"),
/** 无权限 */
FORBIDDEN(403, "无权限"), FORBIDDEN(403, "无权限"),
/** 数据不存在 */
NOT_FOUND(404, "数据不存在"), NOT_FOUND(404, "数据不存在"),
/** 系统异常 */
SYSTEM_ERROR(500, "系统异常"), SYSTEM_ERROR(500, "系统异常"),
/** 操作失败 */
FAIL(500, "操作失败"); FAIL(500, "操作失败");
private final int code; private final int code;
@@ -26,4 +38,4 @@ public enum ResultCode {
public String msg() { public String msg() {
return msg; return msg;
} }
} }

View File

@@ -11,6 +11,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Data @Data
@Slf4j @Slf4j
@@ -30,7 +32,6 @@ public class AliOssUtil {
* @return 完整的文件访问URL * @return 完整的文件访问URL
*/ */
public String upload(byte[] bytes, String objectName) { public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。 // 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

View File

@@ -147,3 +147,5 @@ public class SmsUtil {
} }
} }

View File

@@ -0,0 +1,31 @@
package com.bao.dating.config;
import com.bao.dating.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TokenInterceptor tokenInterceptor;
/**
* 添加拦截器到Spring MVC配置中
* @param registry 拦截器注册中心
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器对象
registry.addInterceptor(tokenInterceptor)
// 拦截所有请求
.addPathPatterns("/**")
// 忽略的接口
.excludePathPatterns(
"/user/login"
);
}
}

View File

@@ -0,0 +1,33 @@
package com.bao.dating.context;
/**
* 用户上下文类
* @author lenovo
*/
public class UserContext {
private static final ThreadLocal<Long> userHolder = new ThreadLocal<>();
/**
* 设置当前线程的用户ID
* @param userId 用户ID
*/
public static void setUserId(Long userId) {
userHolder.set(userId);
}
/**
* 获取当前线程的用户ID
* @return 当前用户ID如果未设置则返回null
*/
public static Long getUserId() {
return userHolder.get();
}
/**
* 清除当前线程的用户ID
*/
public static void clear() {
userHolder.remove();
}
}

View File

@@ -1,6 +1,6 @@
package com.bao.dating.controller; package com.bao.dating.controller;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.common.Result; import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode; import com.bao.dating.common.ResultCode;
import com.bao.dating.service.CommentsService; import com.bao.dating.service.CommentsService;

View File

@@ -34,26 +34,25 @@ public class PostController {
/** /**
* 发布动态接口 - JSON格式请求 * 发布动态接口 - JSON格式请求
* @param postDTO 动态信息 * @param postDTO 动态信息
* @param userId 用户ID
* @return 发布的动态对象 * @return 发布的动态对象
*/ */
@PostMapping(consumes = "application/json") @PostMapping( "/createPost")
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO, @RequestParam Long userId) { public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO) {
// 调用 Service 层处理发布动态业务逻辑 // 调用 Service 层处理发布动态业务逻辑
Post result = postService.createPost(userId, postDTO); Post result = postService.createPost(postDTO);
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result); return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
} }
/** /**
* 删除动态 * 批量删除动态
* *
* @param postId 动态ID * @param postIds 动态ID
* @return 删除结果 * @return 删除结果
*/ */
@DeleteMapping("/{postId}") @PostMapping("/deletePost")
public Result<String> deleteById(@PathVariable Long postId){ public Result<String> deleteById(@RequestBody List<Long> postIds){
postService.deletePostById(postId); int deletedCount = postService.deletePostById(postIds);
return Result.success(ResultCode.SUCCESS_DELETE, "动态删除成功", null); return Result.success(ResultCode.SUCCESS_DELETE, deletedCount > 0 ? "成功删除" : "删除失败,该动态不存在", null);
} }
/** /**
@@ -61,7 +60,7 @@ public class PostController {
* @param postId 动态ID * @param postId 动态ID
* @return 动态对象 * @return 动态对象
*/ */
@GetMapping("/{postId}") @PostMapping("/{postId}")
public Result<PostEditVO> getPostById(@PathVariable Long postId) { public Result<PostEditVO> getPostById(@PathVariable Long postId) {
PostEditVO postEditVO = postService.getPostForEdit(postId); PostEditVO postEditVO = postService.getPostForEdit(postId);
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO); return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
@@ -73,7 +72,7 @@ public class PostController {
* @param postRequestDTO 动态信息 * @param postRequestDTO 动态信息
* @return 更新后的动态对象 * @return 更新后的动态对象
*/ */
@PutMapping("/{postId}") @PostMapping("/{postId}/updatePost")
public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) { public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) {
PostEditVO result = postService.updatePost(postId, postRequestDTO); PostEditVO result = postService.updatePost(postId, postRequestDTO);
return Result.success(ResultCode.SUCCESS_REVIEW, "动态更新成功", result); return Result.success(ResultCode.SUCCESS_REVIEW, "动态更新成功", result);

View File

@@ -0,0 +1,66 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.context.UserContext;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 登录
* @param userLoginDTO 登录参数
*/
@PostMapping("/login")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
UserLoginVO userloginVO = userService.userLogin(userLoginDTO);
return Result.success(ResultCode.SUCCESS, "登录成功", userloginVO);
}
/**
* 获取用户信息
* @return 用户信息
*/
@GetMapping("/info")
public Result<UserInfoVO> getUserInfo() {
Long userId = UserContext.getUserId();
UserInfoVO userInfoVO = userService.getUserInfo(userId);
return Result.success(ResultCode.SUCCESS, "获取用户信息成功", userInfoVO);
}
/**
* 上传头像接口
* @param file 头像文件
* @return 上传后的文件URL列表
*/
@PostMapping(value = "/info/uploadAvatar", consumes = "multipart/form-data")
public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
String fileUrl = userService.uploadAvatar(file);
return Result.success(ResultCode.SUCCESS_REVIEW, "头像上传成功", fileUrl);
}
/**
* 上传背景接口
* @param file 背景文件
* @return 上传后的文件URL列表
*/
@PostMapping(value = "/info/uploadBackground", consumes = "multipart/form-data")
public Result<String> uploadBackground(@RequestParam("file") MultipartFile file) {
String fileUrl = userService.uploadBackground(file);
return Result.success(ResultCode.SUCCESS_REVIEW, "背景上传成功", fileUrl);
}
}

View File

@@ -0,0 +1,79 @@
package com.bao.dating.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bao.dating.context.UserContext;
import com.bao.dating.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* HttpToken拦截器类
* 用于拦截请求并验证JWT token的有效性同时从token中解析用户信息
*/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
/**
* 在请求处理之前进行拦截
* 从请求头或URL参数中获取token验证其有效性并将用户ID保存到ThreadLocal中
* @param request HTTP请求对象
* @param response HTTP响应对象
* @param handler 处理器
* @return 验证通过返回true否则返回false
* @throws Exception 异常
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断当前拦截到的是Controller的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
//当前拦截到的不是动态方法,直接放行
return true;
}
// 从 header 获取 token
String token = request.getHeader("token");
try {
log.info("jwt校验: {}", token);
// 验证 token 是否有效(包括是否过期)
if (!JwtUtil.validateToken(token)) {
log.error("Token 无效或已过期");
response.setStatus(401);
return false;
}
// 解析 token
String userId = JwtUtil.getSubjectFromToken(token);
log.info("用户: {}", userId);
// 保存 userId 到 ThreadLocal
UserContext.setUserId(Long.valueOf(userId));
return true;
} catch (Exception e) {
log.error("Token 校验失败: {}", e.getMessage());
response.setStatus(401);
return false;
}
}
/**
* 在请求完成之后执行清理工作
* 清除保存在ThreadLocal中的用户ID防止内存泄漏
* @param request HTTP请求对象
* @param response HTTP响应对象
* @param handler 处理器
* @param ex 异常对象
* @throws Exception 异常
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserContext.clear();
}
}

View File

@@ -1,8 +1,7 @@
package com.bao.dating.mapper; package com.bao.dating.mapper;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.common.Post;
import org.apache.ibatis.annotations.*; import org.apache.ibatis.annotations.*;
import java.util.List; import java.util.List;

View File

@@ -4,6 +4,8 @@ import com.bao.dating.pojo.entity.Post;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper @Mapper
public interface PostMapper { public interface PostMapper {
/** /**
@@ -16,9 +18,9 @@ public interface PostMapper {
/** /**
* 根据ID删除动态 * 根据ID删除动态
* *
* @param postId 动态ID * @param postIds 动态ID
*/ */
void deletePostById(@Param("postId") Long postId); int deletePostByIds(List<Long> postIds);
/** /**
* 根据ID查询动态 * 根据ID查询动态
@@ -26,7 +28,7 @@ public interface PostMapper {
* @param postId * @param postId
* @return * @return
*/ */
Post selectById(@Param("postId") Long postId); Post selectById(Long postId);
/** /**
* 根据ID更新动态 * 根据ID更新动态

View File

@@ -0,0 +1,25 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
/**
* 根据用户名查询用户
*
* @param username 用户名
* @return 用户
*/
User getByUsername(String username);
/**
* 根据用户id查询用户信息
*
* @param userid 用户id
* @return 用户
*/
User selectByUserId(Long userid);
}

View File

@@ -2,13 +2,14 @@ package com.bao.dating.pojo.dto;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
* 动态数据传输对象 * 动态数据传输对象
*/ */
@Data @Data
public class PostRequestDTO { public class PostRequestDTO implements Serializable {
private String content; private String content;
private List<String> mediaOssKeys; private List<String> mediaOssKeys;
private List<String> tags; private List<String> tags;

View File

@@ -0,0 +1,14 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 用户登录数据传输对象
*/
@Data
public class UserLoginDTO implements Serializable {
private String username;
private String password;
}

View File

@@ -1,8 +1,9 @@
package com.bao.dating.common; package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -10,7 +11,7 @@ import java.time.LocalDateTime;
* 评论表 * 评论表
*/ */
@Data @Data
public class Comments { public class Comments implements Serializable {
private Long comment_id; // 评论ID private Long comment_id; // 评论ID
private String content; // 评论内容 private String content; // 评论内容
private Long user_id; // 评论人ID private Long user_id; // 评论人ID

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@@ -10,7 +11,7 @@ import java.util.List;
* @author KilLze * @author KilLze
*/ */
@Data @Data
public class Post { public class Post implements Serializable {
private Long postId; private Long postId;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/** /**
@@ -9,7 +10,7 @@ import java.time.LocalDateTime;
* @author KilLze * @author KilLze
*/ */
@Data @Data
public class PostFavorite { public class PostFavorite implements Serializable {
private Long favoriteId; private Long favoriteId;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/** /**
@@ -9,7 +10,7 @@ import java.time.LocalDateTime;
* @author KilLze * @author KilLze
*/ */
@Data @Data
public class PostLike { public class PostLike implements Serializable {
private Long likeId; private Long likeId;
private Long userId; private Long userId;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -10,7 +11,7 @@ import java.time.LocalDateTime;
* @author KilLze * @author KilLze
*/ */
@Data @Data
public class User { public class User implements Serializable {
private Long userId; private Long userId;
@@ -37,4 +38,8 @@ public class User {
private LocalDateTime createdAt; private LocalDateTime createdAt;
private LocalDateTime updatedAt; private LocalDateTime updatedAt;
private String userEmail;
private String userPhone;
} }

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.vo;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@@ -9,7 +10,7 @@ import java.util.List;
* 修改内容查询返回数据 * 修改内容查询返回数据
*/ */
@Data @Data
public class PostEditVO { public class PostEditVO implements Serializable {
private Long postId; private Long postId;
private String content; private String content;
private List<String> mediaOssKeys; private List<String> mediaOssKeys;

View File

@@ -0,0 +1,24 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户信息VO
*/
@Data
public class UserInfoVO {
private Long userId;
private String nickname;
private String avatarUrl;
private String backgroundUrl;
private Integer gender;
private LocalDate birthday;
private List<String> hobbies;
private String signature;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,14 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.io.Serializable;
/**
* 登录返回数据
*/
@Data
public class UserLoginVO implements Serializable {
private Long userId;
private String nickname;
private String token;
}

View File

@@ -1,7 +1,7 @@
package com.bao.dating.service; package com.bao.dating.service;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import java.util.List; import java.util.List;

View File

@@ -17,20 +17,18 @@ public interface PostService {
/** /**
* 创建动态 * 创建动态
* @param userId 用户ID
* @param postRequestDTO 动态数据传输对象 * @param postRequestDTO 动态数据传输对象
* @return 创建的动态对象 * @return 创建的动态对象
*/ */
Post createPost(Long userId, PostRequestDTO postRequestDTO); Post createPost(PostRequestDTO postRequestDTO);
/** /**
* 删除动态 * 批量删除动态
* @param postId 动态ID * @param postIds 动态ID
* @return 删除的动态对象 * @return 删除的动态对象
*/ */
void deletePostById(Long postId); int deletePostById(List<Long> postIds);
void deletePostById(Integer postId);
/** /**
* 查询动态详情(用于编辑) * 查询动态详情(用于编辑)

View File

@@ -0,0 +1,38 @@
package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.vo.PostEditVO;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface UserService {
/**
* 登录
* @param userLoginDTO 登录参数
* @return 登录结果
*/
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
/**
* 查询个人信息
* @param userId 动态ID
*/
UserInfoVO getUserInfo(Long userId);
/**
* 上传头像
* @param file 头像文件
* @return 上传后的文件URL列表
*/
String uploadAvatar(MultipartFile file);
/**
* 上传背景
* @param file 背景文件
* @return 上传后的文件URL列表
*/
String uploadBackground(MultipartFile file);
}

View File

@@ -1,6 +1,6 @@
package com.bao.dating.service.impl; package com.bao.dating.service.impl;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.mapper.CommentsMapper; import com.bao.dating.mapper.CommentsMapper;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.service.impl;
import com.bao.dating.common.aliyun.GreenImageScan; import com.bao.dating.common.aliyun.GreenImageScan;
import com.bao.dating.common.aliyun.GreenTextScan; import com.bao.dating.common.aliyun.GreenTextScan;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.PostMapper; import com.bao.dating.mapper.PostMapper;
import com.bao.dating.pojo.dto.PostRequestDTO; import com.bao.dating.pojo.dto.PostRequestDTO;
import com.bao.dating.pojo.entity.Post; import com.bao.dating.pojo.entity.Post;
@@ -12,14 +13,14 @@ import com.bao.dating.util.FileUtil;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.time.format.DateTimeFormatter;
import java.util.List; import java.util.*;
import java.util.Map;
import java.util.UUID;
/** /**
* 动态服务实现类 * 动态服务实现类
@@ -48,46 +49,70 @@ public class PostServiceImpl implements PostService {
*/ */
@Override @Override
public List<String> uploadMedia(MultipartFile[] files) { public List<String> uploadMedia(MultipartFile[] files) {
// 如果没有文件,则返回空列表
if (files == null || files.length == 0) {
return Collections.emptyList();
}
// 创建媒体文件列表
List<String> mediaUrls = new ArrayList<>(); List<String> mediaUrls = new ArrayList<>();
if (files != null && files.length > 0) {
for (MultipartFile file : files) { for (MultipartFile file : files) {
if (!file.isEmpty()) { // 跳过空文件
if (file == null || file.isEmpty()) {
continue;
}
// 获取文件名并跳过空文件
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
continue;
}
// 校验文件类型
String fileType = FileUtil.getFileType(originalFilename);
if (!"image".equals(fileType) && !"video".equals(fileType)) {
throw new RuntimeException("不支持的文件类型:" + originalFilename);
}
// 创建目录
String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
// 获取文件扩展名
String extension = FileUtil.getFileExtension(originalFilename);
// 生成唯一文件名
String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
// 获取用户ID
Long userId = UserContext.getUserId();
// 创建文件名
String fileName = "post/" + userId + "/" + dir + "/" + newFileName;
try { try {
// 根据文件扩展名判断文件类型
String fileType = FileUtil.getFileType(file.getOriginalFilename());
// 生成唯一文件名
String fileName = UUID.randomUUID().toString() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
// 获取文件字节数据 // 获取文件字节数据
byte[] fileBytes = file.getBytes(); byte[] fileBytes = file.getBytes();
// 根据文件类型处理 // 上传图片或视频
String ossUrl = ""; String ossUrl = ossUtil.upload(fileBytes, fileName);
if ("image".equals(fileType) || "video".equals(fileType)) { if (ossUrl == null || ossUrl.isEmpty()) {
// 上传图片或视频 throw new RuntimeException("文件上传失败:" + originalFilename);
ossUrl = ossUtil.upload(fileBytes, fileName);
} }
// 添加上传后的 URL // 添加上传后的 URL
mediaUrls.add(ossUrl); mediaUrls.add(ossUrl);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); // 统一异常处理
throw new RuntimeException("上传媒体文件失败:" + originalFilename, e);
} }
} }
}
}
return mediaUrls; return mediaUrls;
} }
/** /**
* 创建动态 * 创建动态
* *
* @param userId 用户ID
* @param postRequestDTO 动态数据传输对象 * @param postRequestDTO 动态数据传输对象
* @return 创建的动态对象 * @return 创建的动态对象
*/ */
@Override @Override
public Post createPost(Long userId, PostRequestDTO postRequestDTO) { public Post createPost(PostRequestDTO postRequestDTO) {
// 创建动态对象 // 创建动态对象
Post post = new Post(); Post post = new Post();
Long userId = UserContext.getUserId();
post.setUserId(userId); post.setUserId(userId);
post.setContent(postRequestDTO.getContent()); post.setContent(postRequestDTO.getContent());
post.setTags(postRequestDTO.getTags()); post.setTags(postRequestDTO.getTags());
@@ -106,9 +131,6 @@ public class PostServiceImpl implements PostService {
} }
String textSuggestion = (String) textResult.get("suggestion"); String textSuggestion = (String) textResult.get("suggestion");
if ("block".equals(textSuggestion)) {
throw new RuntimeException("动态内容违规,禁止发布");
}
// 2. 图片审核(如果有) // 2. 图片审核(如果有)
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) { if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
@@ -153,29 +175,50 @@ public class PostServiceImpl implements PostService {
return post; return post;
} }
@Override
public void deletePostById(Long postId) {
postMapper.deletePostById(postId);
}
/** /**
* 删除动态 * 批量删除动态
* *
* @param postId 动态ID * @param postIds 动态ID
* @return 删除的动态对象 * @return 删除的动态对象
*/ */
@Override @Override
public void deletePostById(Integer postId) { @Transactional(rollbackFor = Exception.class)
postMapper.deletePostById(Long.valueOf(postId)); public int deletePostById(List<Long> postIds) {
// 判断用户权限
Long userId = UserContext.getUserId();
// 遍历所有要删除的帖子ID验证权限
for (Long postId : postIds) {
Post post = postMapper.selectById(postId);
if (post == null) {
throw new RuntimeException("动态不存在");
}
// 验证用户权限
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
throw new RuntimeException("无权限删除此动态");
}
}
// 批量删除动态
return postMapper.deletePostByIds(postIds);
} }
/**
* 查询动态详情(用于编辑)
*
* @param postId 动态ID
* @return 动态详情
*/
@Override @Override
public PostEditVO getPostForEdit(Long postId) { public PostEditVO getPostForEdit(Long postId) {
Post post = postMapper.selectById(postId); Post post = postMapper.selectById(postId);
if (post == null) { if (post == null) {
throw new RuntimeException("动态不存在"); throw new RuntimeException("动态不存在");
} }
// 判断用户权限
Long userId = UserContext.getUserId();
if (post.getUserId() == null || !post.getUserId().equals(userId)){
throw new RuntimeException("无权限查看此动态");
}
PostEditVO postEditVO = new PostEditVO(); PostEditVO postEditVO = new PostEditVO();
BeanUtils.copyProperties(post, postEditVO); BeanUtils.copyProperties(post, postEditVO);
return postEditVO; return postEditVO;
@@ -185,7 +228,7 @@ public class PostServiceImpl implements PostService {
* 修改动态 * 修改动态
* @param postId 动态ID * @param postId 动态ID
* @param postRequestDTO 修改的动态数据传输对象 * @param postRequestDTO 修改的动态数据传输对象
* @return * @return 修改的动态对象
*/ */
@Override @Override
public PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO) { public PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO) {
@@ -194,10 +237,14 @@ public class PostServiceImpl implements PostService {
if (post == null) { if (post == null) {
throw new RuntimeException("动态不存在"); throw new RuntimeException("动态不存在");
} }
post.setContent(postRequestDTO.getContent()); // 判断用户权限
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) { Long userId = UserContext.getUserId();
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys()); if (post.getUserId() == null || !post.getUserId().equals(userId)){
throw new RuntimeException("无权限修改此动态");
} }
post.setContent(postRequestDTO.getContent());
// 如果请求中的mediaOssKeys不为null即使是空列表则更新为新值
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
// 1. 文本内容审核 // 1. 文本内容审核
Map textResult; Map textResult;
@@ -209,11 +256,11 @@ public class PostServiceImpl implements PostService {
// 文本审核结果 // 文本审核结果
String textSuggestion = (String) textResult.get("suggestion"); String textSuggestion = (String) textResult.get("suggestion");
// 2. 图片审核(如果有) // 2. 图片审核(如果有媒体文件
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) { if (post.getMediaOssKeys() != null && !post.getMediaOssKeys().isEmpty()) {
Map imageResult; Map imageResult;
try { try {
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaOssKeys()); imageResult = greenImageScan.imageScan(post.getMediaOssKeys());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@@ -0,0 +1,160 @@
package com.bao.dating.service.impl;
import com.bao.dating.common.aliyun.AliOssUtil;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.UserMapper;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
import com.bao.dating.util.FileUtil;
import com.bao.dating.util.JwtUtil;
import com.bao.dating.util.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private AliOssUtil ossUtil;
@Autowired
private UserMapper userMapper;
/**
* 用户登录
* @param userLoginDTO
* @return 登录信息
*/
@Override
public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
// 参数校验
if (userLoginDTO == null || userLoginDTO.getUsername() == null || userLoginDTO.getPassword() == null) {
throw new RuntimeException("用户名或密码不能为空");
}
// 查询用户
User user = userMapper.getByUsername(userLoginDTO.getUsername());
if (user == null){
throw new RuntimeException("用户不存在");
}
// 密码校验
boolean match = MD5Util.verifyWithSalt(
userLoginDTO.getPassword(),
user.getSalt(),
user.getPasswordHash()
);
if (!match){
throw new RuntimeException("密码错误");
}
// 生成token
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
// 封装返回
UserLoginVO userLoginVO = new UserLoginVO();
userLoginVO.setUserId(user.getUserId());
userLoginVO.setNickname(user.getNickname());
userLoginVO.setToken(token);
return userLoginVO;
}
/**
* 获取用户信息
* @param userId
* @return 用户信息
*/
@Override
public UserInfoVO getUserInfo(Long userId) {
User user = userMapper.selectByUserId(userId);
if (user == null){
throw new RuntimeException("用户不存在");
}
UserInfoVO userInfoVO = new UserInfoVO();
BeanUtils.copyProperties(user, userInfoVO);
return userInfoVO;
}
@Override
public String uploadAvatar(MultipartFile file) {
// 参数校验
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片不存在");
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
throw new RuntimeException("文件名非法");
}
String fileType = FileUtil.getFileType(originalFilename);
if (!"image".equals(fileType)) {
throw new RuntimeException("仅支持图片上传");
}
//生成 OSS 路径
String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
String extension = FileUtil.getFileExtension(originalFilename);
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
Long userId = UserContext.getUserId();
String objectKey = "user/" + userId + "/avatar/" + fileName;
try {
byte[] fileBytes = file.getBytes();
String ossUrl = ossUtil.upload(fileBytes, objectKey);
if (ossUrl == null || ossUrl.isEmpty()) {
throw new RuntimeException("图片上传失败");
}
return ossUrl;
} catch (Exception e) {
throw new RuntimeException("上传图片失败", e);
}
}
@Override
public String uploadBackground(MultipartFile file) {
// 参数校验
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片不存在");
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
throw new RuntimeException("文件名非法");
}
String fileType = FileUtil.getFileType(originalFilename);
if (!"image".equals(fileType)) {
throw new RuntimeException("仅支持图片上传");
}
//生成 OSS 路径
String extension = FileUtil.getFileExtension(originalFilename);
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
Long userId = UserContext.getUserId();
String objectKey = "user/" + userId + "/background/" + fileName;
try {
byte[] fileBytes = file.getBytes();
String ossUrl = ossUtil.upload(fileBytes, objectKey);
if (ossUrl == null || ossUrl.isEmpty()) {
throw new RuntimeException("图片上传失败");
}
return ossUrl;
} catch (Exception e) {
throw new RuntimeException("上传图片失败", e);
}
}
}

View File

@@ -89,3 +89,5 @@ public class MD5Util {
} }
} }

View File

@@ -7,6 +7,19 @@ spring:
username: root username: root
password: JoyeeServe2025 password: JoyeeServe2025
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
redis:
host: 127.0.0.1
port: 6379
password: ""
database: 0
timeout: 10000
# 连接池配置lettuce是Spring Boot默认Redis客户端性能更优
lettuce:
pool:
max-active: 8 # 连接池最大连接数默认8可根据业务并发调整
max-wait: -1 # 连接池最大阻塞等待时间(毫秒,-1表示无限制
max-idle: 8 # 连接池最大空闲连接数默认8
min-idle: 1 # 连接池最小空闲连接数默认0建议设置1-4提高连接复用率
# 邮箱SMTP配置 # 邮箱SMTP配置
mail: mail:
host: smtp.163.com # QQ邮箱SMTP服务器地址 host: smtp.163.com # QQ邮箱SMTP服务器地址
@@ -46,9 +59,9 @@ aliyun:
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
scenes: antispam scenes: antispam
# 阿里云短信服务配置 # 阿里云短信服务配置
# sms: sms:
# access-key-id: LTAI5t5vpcbCZwweNHEDDDaF access-key-id: LTAI5t5vpcbCZwweNHEDDDaF
# access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
# region-id: cn-hangzhou region-id: cn-hangzhou
# sign-name: sign-name: 速通互联验证码
# template-code: SMS_123456789 template-code: 100001

View File

@@ -29,8 +29,23 @@
</insert> </insert>
<!--动态删除--> <!--动态删除-->
<delete id="deletePostById"> <delete id="deletePostByIds">
DELETE FROM post WHERE post_id = #{postId} DELETE FROM post WHERE post_id IN
<foreach item="postId" index="index" collection="postIds" separator="," open="(" close=")">
#{postId}
</foreach>
</delete>
<!--删除收藏记录-->
<delete id="1">
DELETE FROM post_favorite WHERE post_id = #{postId}
</delete>
<!--删除点赞记录-->
<delete id="2">
DELETE FROM post_like WHERE post_id = #{postId}
</delete>
<!--动态评论删除-->
<delete id="3">
DELETE FROM comments WHERE post_id = #{postId}
</delete> </delete>
<!--动态查询--> <!--动态查询-->

View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.UserMapper">
<!--根据用户名查询用户-->
<select id="getByUsername" resultType="com.bao.dating.pojo.entity.User">
SELECT
user_id,
user_name,
password_hash,
salt,
nickname
FROM user WHERE user_name = #{userName}
</select>
<!--根据用户id查询用户信息-->
<resultMap id="UserResultMap" type="com.bao.dating.pojo.entity.User">
<id property="userId" column="user_id"/>
<result property="nickname" column="nickname"/>
<result property="avatarUrl" column="avatar_url"/>
<result property="backgroundUrl" column="background_url"/>
<result property="gender" column="gender"/>
<result property="birthday" column="birthday"/>
<result property="hobbies" column="hobbies" typeHandler="com.bao.dating.handler.ListToVarcharTypeHandler"/>
<result property="signature" column="signature"/>
<result property="createdAt" column="created_at"/>
<result property="updatedAt" column="updated_at"/>
</resultMap>
<select id="selectByUserId" resultMap="UserResultMap">
SELECT
user_id,
nickname,
avatar_url,
background_url,
gender,
birthday,
hobbies,
signature,
created_at,
updated_at
FROM user WHERE user_id = #{userId}
</select>
</mapper>

View File

@@ -73,3 +73,5 @@ public class EmailAndSmsTest {
} }