package com.hc.gpweb.aspect;

import com.hc.gpcore.exception.UserAuthorizeException;
import com.hc.gpcore.utils.redis.RedisUtil;
import com.hc.gpcore.utils.tool.Verification;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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;
import java.util.Objects;

/**
 * @author JIA
 */

@Aspect
@Component
@Slf4j
public class BackUserAspect {

    private final RedisUtil redisUtil;

    public BackUserAspect(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }


    @Pointcut(" execution (public * com.hc.gpweb.controller.back..*.*(..))" +
            "&& ! execution (public * com.hc.gpweb.controller.back.BackUserAdminController.userAdminLogin(..))"
    )

    public void verify() {

    }

    @Before("verify()")
    public void doVerify() {

        //获取请求信息
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        //从请求头中获取token
        String token = request.getHeader("token");

        if (!Objects.isNull(token)) {

            //身份识别

            //获取redis中的token 查看token是否过期
            if (Verification.verificationString((String) redisUtil.get(token))) {
                log.info("back 请求-token正常");
            } else {
                log.info("back 请求-redis中的token已过期，请重新登录");
                throw new UserAuthorizeException();
            }

        } else {
            log.info("Back request-token is null");
            throw new UserAuthorizeException();
        }
    }

}
