package com.ruoyi.web.work.api.config;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.work.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

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


public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenServices tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            ServletUtils.renderString(response, JSONUtils.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "请先登陆")));
            return false;
        }
        User user = tokenService.getLoginUser(token);
        if (user == null) {
            ServletUtils.renderString(response, JSONUtils.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "登录已过期，请重新登陆")));
            return false;
        }
        if (user.getState() == 1) {
            ServletUtils.renderString(response, JSONUtils.toJSONString(AjaxResult.error(HttpStatus.FORBIDDEN, "你的账号被锁定，无法操作")));
            tokenService.delLoginUser(user.getToken());
            return false;
        }
        request.setAttribute("user", user);
        return true;
    }

}
