package cn.quantgroup.xyqb.aspect.accessable;

import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.util.IpUtil;
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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * IP白名单检验
 *
 * @author renwc
 * @date 2017-12-01
 */
@Slf4j
@Aspect
@Component
public class IpValidateAdvisor {

    @Pointcut("execution(public * cn.quantgroup.xyqb.controller.internal..*.*Controller.*(..)) " +
            " || execution(public * cn.quantgroup.xyqb.controller.dust..*.*Controller.*(..)) " +
            " || @annotation(cn.quantgroup.xyqb.aspect.accessable.IpValidator)")
    private void whiteIpMatch() {
    }

    @Around("whiteIpMatch()")
    private Object doWhiteIpMatch(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 客户端IP
        String clientIp = IpUtil.getRemoteIP(request);
        log.error("Lock_ipv4-success: don't match white ip access:{}", clientIp);

        // 白名单
        if (IpUtil.whiteOf(clientIp)) {
            return pjp.proceed();
        }
        IpUtil.logIp(log, request);
        log.error("Lock_ipv4: don't match white ip access:{}", clientIp);
        return JsonResult.buildErrorStateResult("非法访问", null);
    }
}
