自定义注解、aop实现(项目笔记)

1.自定义注解:@DesensitizationDecrypt

package com.zkinginfo.utils.desensitization;

import com.zkinginfo.common.enums.BusinessType;
import com.zkinginfo.common.enums.OperatorType;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;

/**
 * Author 王天佑
 * email: 2102376305@qq.com
 * Date: 2023/4/12
 * Time: 10:24
 */
@Target({ElementType.METHOD}) // 作用域
@Retention(RetentionPolicy.RUNTIME) //
public @interface DesensitizationDecrypt {

    BusinessType businessType() default BusinessType.OTHER; // 业务类型(0其它 1新增 2修改 3删除)

    String title() default "订单列表脱敏数据还原"; // 模块标题

    OperatorType operatorType() default OperatorType.MANAGE; // 操作类别(0其它 1后台用户 2手机端用户)

    boolean isSaveRequestData() default true;

}

2.aop切面:DesensitizationDecryptAop

package com.zkinginfo.utils.desensitization;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zkinginfo.common.annotation.Log;
import com.zkinginfo.common.core.domain.model.LoginUser;
import com.zkinginfo.common.enums.BusinessStatus;
import com.zkinginfo.common.enums.HttpMethod;
import com.zkinginfo.common.utils.ServletUtils;
import com.zkinginfo.common.utils.StringUtils;
import com.zkinginfo.common.utils.ip.IpUtils;
import com.zkinginfo.common.utils.spring.SpringUtils;
import com.zkinginfo.framework.manager.AsyncManager;
import com.zkinginfo.framework.manager.factory.AsyncFactory;
import com.zkinginfo.framework.web.service.TokenService;
import com.zkinginfo.system.domain.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * Author 王天佑
 * email: 2102376305@qq.com
 * Date: 2023/4/12
 * Time: 10:35
 * 数据脱敏Aop切面
 */
@Aspect
@Component
@Slf4j
public class DesensitizationDecryptAop {

    @Pointcut("@annotation(com.zkinginfo.utils.desensitization.DesensitizationDecrypt)")
    public void pointcut(){}


    @AfterReturning(
            pointcut = "pointcut()",
            returning = "jsonResult"
    )
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        this.handleLog(joinPoint, (Exception)null, jsonResult);
    }

    protected void handleLog(JoinPoint joinPoint, Exception e, Object jsonResult) {
        try {
            DesensitizationDecrypt controllerLog = this.getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            LoginUser loginUser = ((TokenService) SpringUtils.getBean(TokenService.class)).getLoginUser(ServletUtils.getRequest());
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            operLog.setJsonResult(JSON.toJSONString(jsonResult));
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUsername());
            }

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }

            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            this.getControllerMethodDescription(joinPoint, controllerLog, operLog);
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception var10) {
            log.error("==前置通知异常==");
            log.error("异常信息:{}", var10.getMessage());
            var10.printStackTrace();
        }

    }

    public void getControllerMethodDescription(JoinPoint joinPoint, DesensitizationDecrypt log, SysOperLog operLog) throws Exception {
        operLog.setBusinessType(log.businessType().ordinal());
        operLog.setTitle(log.title());
        operLog.setOperatorType(log.operatorType().ordinal());
        if (log.isSaveRequestData()) {
            this.setRequestValue(joinPoint, operLog);
        }

    }

    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        String requestMethod = operLog.getRequestMethod();
        if (!HttpMethod.PUT.name().equals(requestMethod) && !HttpMethod.POST.name().equals(requestMethod)) {
            Map<?, ?> paramsMap = (Map)ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        } else {
            String params = this.argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        }

    }

    private DesensitizationDecrypt getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method method = methodSignature.getMethod();
        return method != null ? (DesensitizationDecrypt)method.getAnnotation(DesensitizationDecrypt.class) : null;
    }

    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for(int i = 0; i < paramsArray.length; ++i) {
                if (!this.isFilterObject(paramsArray[i])) {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params = params + jsonObj.toString() + " ";
                }
            }
        }

        return params.trim();
    }

    public boolean isFilterObject(Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }


    /*@Around(value = "pointcut()")
    public Object around (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //类名
        String clsName=proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName();
        //方法名
        String modName= proceedingJoinPoint.getSignature().getName();
        //参数
        Object[] args = proceedingJoinPoint.getArgs();
        //接口返回结果,该结果可在业务前或业务后执行
        Object proceed = proceedingJoinPoint.proceed();

        System.out.print(proceed);
        return proceed;
    }*/


}


3.使用

/**
     * 还原脱敏数据
     * @param desensitizationDecryptReq
     * @return AjaxResult
     */
    @ApiOperation("脱敏数据还原")
    @GetMapping("/desensitizationDecrypt")
    @DesensitizationDecrypt(title = "脱敏数据还原")
    public AjaxResult desensitizationDecrypt(@Valid DesensitizationDecryptReq desensitizationDecryptReq){
        BizCustDetailedDTO detail = iBizCustService.selectBizCustById(desensitizationDecryptReq.getCustId());
        if (ObjectUtil.isNull(detail)) {
            return AjaxResult.error("查询失败,请检查正确参数!");
        }
        JSONObject msgObj = new JSONObject();
        msgObj.put("currentOperation",desensitizationDecryptReq.getCurrentOperation());
        msgObj.put("phone",detail.getCustPhone());
        msgObj.put("userName",detail.getCustName());
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        msgObj.put("tag",detail.getCustName()+"【"+desensitizationDecryptReq.getCustId()+"】"+"在"+formatter.format(date)+"的时候查看了脱敏数据:"+detail.getCustPhone());
        return AjaxResult.success(msgObj);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值