Skip to content

Commit

Permalink
feat: content security check
Browse files Browse the repository at this point in the history
  • Loading branch information
Pleasurecruise committed Nov 19, 2024
1 parent b08005f commit 55ad617
Show file tree
Hide file tree
Showing 21 changed files with 409 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,13 @@ public class MessageConstant {
public static final String ACCOUNT_EXIST = "账号已存在";
public static final String UNKNOWN_ERROR = "未知错误";
public static final String USER_NOT_LOGIN = "用户未登录";
public static final String CATEGORY_BE_RELATED_BY_SETMEAL = "当前分类关联了套餐,不能删除";
public static final String CATEGORY_BE_RELATED_BY_DISH = "当前分类关联了菜品,不能删除";
public static final String SHOPPING_CART_IS_NULL = "购物车数据为空,不能下单";
public static final String ADDRESS_BOOK_IS_NULL = "用户地址为空,不能下单";
public static final String LOGIN_FAILED = "登录失败";
public static final String UPLOAD_FAILED = "文件上传失败";
public static final String SETMEAL_ENABLE_FAILED = "套餐内包含未启售菜品,无法启售";
public static final String PASSWORD_EDIT_FAILED = "密码修改失败";
public static final String DISH_ON_SALE = "起售中的菜品不能删除";
public static final String SETMEAL_ON_SALE = "起售中的套餐不能删除";
public static final String DISH_BE_RELATED_BY_SETMEAL = "当前菜品关联了套餐,不能删除";
public static final String ORDER_STATUS_ERROR = "订单状态错误";
public static final String ORDER_NOT_FOUND = "订单不存在";
public static final String CONTENT_UNSECURED = "内容含违规信息";

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package cn.yiming1234.NottinghamWall.exception;

public class TeapotException extends BaseException {
public TeapotException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ public class AliOssUtil {

/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {

Expand Down Expand Up @@ -69,8 +65,6 @@ public String upload(byte[] bytes, String objectName) {

/**
* 文件删除
*
* @param objectName
*/
public void delete(String objectName) {
// 创建OSSClient实例。
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package cn.yiming1234.NottinghamWall.utils;

import cn.yiming1234.NottinghamWall.constant.MessageConstant;
import cn.yiming1234.NottinghamWall.exception.TeapotException;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
* 内容安全性检测工具类
*/
@Data
@Slf4j
@Component
public class ContentCheckUtil {

private static final String WX_TEXT_SEC_CHECK = "https://api.weixin.qq.com/wxa/msg_sec_check";
private static final String WX_MEDIA_SEC_CHECK = "https://api.weixin.qq.com/wxa/media_check_async";

/**
* 检查文本内容的安全性
* @param content 需检测的文本内容
* @param scene 场景值(1-资料;2-评论;3-论坛;4-社交日志)
* @param Openid 用户的openid
* @param AccessToken 用户的access_token
* @return true表示内容安全,false表示内容有风险
*/
public boolean checkTextContent(String content, int scene, String Openid, String AccessToken) {
try {
Map<String, String> params = new HashMap<>();
params.put("content", content);
params.put("version", "2");
params.put("scene", String.valueOf(scene));
params.put("openid", Openid);

String response = HttpClientUtil.doPost4Json(WX_TEXT_SEC_CHECK + "?access_token=" + AccessToken, params);
JSONObject jsonResponse = JSONObject.parseObject(response);
int errcode = jsonResponse.getIntValue("errcode");

if (errcode != 0) {
String errmsg = jsonResponse.getString("errmsg");
throw new TeapotException(MessageConstant.CONTENT_UNSECURED + ": " + errmsg);
}

JSONObject result = jsonResponse.getJSONObject("result");
String suggest = result.getString("suggest");
log.info("检测结果:" + suggest);
return "pass".equals(suggest);
} catch (Exception e) {
log.info("检测文本内容失败:{}",e.getMessage());
throw new TeapotException(MessageConstant.CONTENT_UNSECURED);
}
}

/**
* 检查图片内容的安全性
* @param mediaUrl 要检测的图片或音频的URL
* @param scene 场景值(1-资料;2-评论;3-论坛;4-社交日志)
* @param Openid 用户的openid
* @param AccessToken 用户的access_token
* @return true表示图片安全,false表示图片有风险
*/
public boolean checkImageContent(String mediaUrl, int scene, String Openid, String AccessToken) {
try {
Map<String, String> params = new HashMap<>();
params.put("media_url", mediaUrl);
params.put("media_type", "2");
params.put("version", "2");
params.put("scene", String.valueOf(scene));
params.put("openid", Openid);

String response = HttpClientUtil.doPost4Json(WX_MEDIA_SEC_CHECK + "?access_token=" + AccessToken, params);
JSONObject jsonResponse = JSONObject.parseObject(response);
int errcode = jsonResponse.getIntValue("errcode");

if (errcode != 0) {
String errmsg = jsonResponse.getString("errmsg");
throw new TeapotException(MessageConstant.CONTENT_UNSECURED + ": " + errmsg);
}

JSONObject result = jsonResponse.getJSONObject("result");
String suggest = result.getString("suggest");
log.info("检测结果:" + suggest);
return "pass".equals(suggest);
} catch (Exception e) {
log.info("检测图片内容失败:{}",e.getMessage());
throw new TeapotException(MessageConstant.CONTENT_UNSECURED);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ public class HttpClientUtil {

/**
* 发送GET方式请求
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url,Map<String,String> paramMap){
// 创建Httpclient对象
Expand Down Expand Up @@ -75,10 +72,6 @@ public static String doGet(String url,Map<String,String> paramMap){

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
Expand Down Expand Up @@ -122,10 +115,6 @@ public static String doPost(String url, Map<String, String> paramMap) throws IOE

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,9 @@ public Result update(@RequestBody StudentDTO studentDTO, HttpServletRequest requ
Student student = studentService.getById(id);
log.info("当前学生信息:{}", student);
studentDTO.setId(id);
studentDTO.setUsername(Optional.ofNullable(studentDTO.getUsername()).orElse(student.getUsername()));
studentDTO.setAvatar(Optional.ofNullable(studentDTO.getAvatar()).orElse(student.getAvatar()));
studentDTO.setSex(Optional.ofNullable(studentDTO.getSex()).orElse(student.getSex()));
studentDTO.setStudentid(Optional.ofNullable(studentDTO.getStudentid()).orElse(student.getStudentid()));
studentService.update(studentDTO);
log.info("更新学生信息:{}", studentDTO);
Student updatedStudent = studentService.update(studentDTO);
return Result.success(updatedStudent);
return Result.success();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public TopicController(TopicService topicService, AliOssUtil aliOssUtil, JwtProp

/**
* 从请求头中提取用户id
* @param request 请求
*/
private Integer extractUserId(HttpServletRequest request) {
return getaLong(request, jwtProperties, log);
Expand All @@ -59,6 +60,8 @@ static Integer getaLong(HttpServletRequest request, JwtProperties jwtProperties,

/**
* 创建话题
* @param topicDTO 话题DTO
* @param request 请求
*/
@PostMapping("/post/topic")
@ApiOperation(value = "创建话题")
Expand All @@ -72,6 +75,7 @@ public Result<Void> createTopic(@RequestBody TopicDTO topicDTO, HttpServletReque

/**
* 删除话题
* @param id 话题id
*/
@DeleteMapping("/delete/topic/{id}")
@ApiOperation(value = "删除话题")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package cn.yiming1234.NottinghamWall.handler;

import cn.yiming1234.NottinghamWall.constant.MessageConstant;
import cn.yiming1234.NottinghamWall.exception.BaseException;
import cn.yiming1234.NottinghamWall.exception.TeapotException;
import cn.yiming1234.NottinghamWall.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
* 全局异常处理器,处理项目中抛出的业务异常
*/
Expand All @@ -18,24 +17,19 @@ public class GlobalExceptionHandler {

/**
* 捕获业务异常
* @param ex
* @return
*/
@ExceptionHandler
public Result exceptionHandler(BaseException ex){
log.error("异常信息:{}", ex.getMessage());
return Result.error(ex.getMessage());
}

public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
String message = ex.getMessage();
if(message.contains("Duplicate entry")){
String[] split = message.split("'");
String username = split[2];
String msg = username + MessageConstant.ACCOUNT_EXIST;
return Result.error(msg);
}else{
return Result.error(MessageConstant.UNKNOWN_ERROR);
}
/**
* 捕获TeapotException异常
*/
@ExceptionHandler(TeapotException.class)
public Result teapotExceptionHandler(TeapotException ex){
log.error("异常信息:{}", ex.getMessage());
return Result.error(ex.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,55 @@ public interface StudentMapper {

/**
* 插入学生信息
* @param student 学生信息
*/
void insert(Student student);

/**
* 根据用户名查询管学生
* @param username 用户名
*/
Student getByUsername(String username);

/**
* 根据id查询学生
* @param id 学生id
*/
Student getById(Integer id);

/**
* 根据id查询openid
* @param id 学生id
*/
String getOpenidById(Integer id);

/**
* 根据openid查询学生
* @param openid openid
*/
Student findByOpenid(String openid);

/**
* 根据学号查询学生
* @param studentid 学号
*/
Student getByStudentId(Integer studentid);

/**
* 分页查询学生
* @param pageQueryDTO 分页查询条件
*/
Page<Student> pageQuery(PageQueryDTO pageQueryDTO);

/**
* 根据邮箱查询学生
* @param email 邮箱
*/
Student getByEmail(String email);

/**
* 更新学生信息
* @param student 学生信息
*/
void updateById(Student student);

Expand Down
Loading

0 comments on commit 55ad617

Please sign in to comment.