package com.hs.admin.common.aspect;

import com.hs.admin.common.Constants;
import com.hs.admin.common.exceptions.InvalidTokenException;
import com.hs.admin.common.utils.TokenUtil;
import com.hs.common.utils.StringUtil;
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.slf4j.Logger;
import org.springframework.context.annotation.Profile;
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;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order(1)
@Profile({"dev","test","prod"})
public class TokenAspect {
    @Pointcut("@annotation(com.hs.admin.common.annotations.Token)")
    public void tokenAspect() {
    }

    @Around("tokenAspect()")
    public Object verifierToken(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.TOKEN_KEY);

        if(!StringUtil.isNullOrEmpty(token) && TokenUtil.checkToken(token)){
            return joinPoint.proceed();
        }
        String remoteHost = request.getRemoteHost();
        String uri = request.getRequestURI();
        Logger logger = org.slf4j.LoggerFactory.getLogger(joinPoint.getTarget().getClass());
        logger.info(remoteHost + " 访问 " + uri + ", token无效, token：[" + token + "]");

        throw new InvalidTokenException("无效的TOKEN");
    }
}
