package com.jiayue.ssi.aspectj;

import cn.hutool.crypto.SmUtil;
import com.jiayue.ssi.annotation.AgainVerify;
import com.jiayue.ssi.annotation.InterfaceLimit;
import com.jiayue.ssi.util.InterfaceLimitUtil;
import com.jiayue.ssi.util.ResponseVO;
import com.jiayue.ssi.util.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
* 重新鉴别
*
* @author xsl
* @since 2023/04/06
*/
@Aspect
@Component
@Slf4j
@Order(3)
public class AgainVerifyAspect {
    /**
     * 层切点
     */
    @Pointcut("@annotation(againVerify)")
    public void controllerAspect(AgainVerify againVerify) {
    }

    @Around("controllerAspect(againVerify)")
    public ResponseVO doAround(ProceedingJoinPoint pjp, AgainVerify againVerify) throws Throwable {
        // 获得request对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String againPwd = request.getParameter("againPwd");
        String decryptPassword = null;
        //加密密码
        try {
            decryptPassword= SmUtil.sm3(againPwd).toUpperCase();
        } catch (Exception e) {
            log.error("鉴别操作加密密码失败",e);
            return ResponseVO.fail("鉴别失败,不能操作");
        }
        if (!decryptPassword.equals(SecurityContextUtil.getSysUser().getPassword())) {
            log.error("鉴别失败,不能操作");
            return ResponseVO.fail("鉴别失败,不能操作");
        }
        // result的值就是被拦截方法的返回值
        ResponseVO result = (ResponseVO)pjp.proceed();
        return result;
    }
}
