package com.xjrsoft.common.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * magicapi web页面 使用系统的登录
 *
 * @Author: tzx
 * @Date: 2022/11/1 12:16
 */
@Component
public class MagicApiWebLoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 根据parameter 判断是否有权限
        String parameter = request.getParameter(StpUtil.getTokenName());

        if (StrUtil.isBlank(parameter)) {
            //根据Referer 判断是否有权限
            String refererKey = "Referer";
            String referer = request.getHeader(refererKey);

            if (StrUtil.isBlank(referer)) {
                return false;
            } else {
                UrlBuilder urlBuilder = UrlBuilder.ofHttp(referer, CharsetUtil.CHARSET_UTF_8);
                CharSequence param = urlBuilder.getQuery().get(StpUtil.getTokenName());
                if (StrUtil.isBlank(param)) {
                    return false;
                } else {
                    Object loginIdByToken = StpUtil.getLoginIdByToken(param.toString());
                    return !ObjectUtil.isNull(loginIdByToken);
                }
            }
        }
        else {
            Object loginIdByToken = StpUtil.getLoginIdByToken(parameter);
            return !ObjectUtil.isNull(loginIdByToken);
        }



    }
}
