package com.fdkankan.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Log4j2
@Aspect
@Component
@ConditionalOnProperty(name = "inner.check", havingValue = "true")
@Order(101)
public class CheckInnerApiPermitAspect {

	@Value("${inner.customToken}")
	private String customToken;

	@Pointcut("@annotation(com.fdkankan.web.annotation.CheckInnerApiPermit)")
	public void checkCooperationPermit() {
	}

	/**
	 * 前置通知 用于判断用户协作场景是否有协作权限
	 *
	 * @param joinPoint
	 *            切点
	 * @throws IOException
	 */
	@Before("checkCooperationPermit()")
	public void doBefore(JoinPoint joinPoint) throws Exception {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String customToken = request.getHeader("custom-token");
		if(StrUtil.isEmpty(customToken) || !customToken.equals(this.customToken)){
			throw new BusinessException(ErrorCode.HAVE_NO_RIGHT);
		}
	}

}
