package com.example.system.advice;

import com.example.system.model.Result;
import com.example.system.utils.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@CrossOrigin
@Slf4j
@Component
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行拦截器");
        String toKen =request.getHeader("Authorization");
        if (toKen == null) {
            setResponse(response);
            return false;
        }
        Claims claims = JWTUtil.checkToken(toKen);
        if (claims == null) {
            setResponse(response);
            return false;
        }
        return true;
    }

    @SneakyThrows
    private void setResponse(HttpServletResponse response) {
        response.setStatus(200);
        response.setContentType("application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        String ret = objectMapper.writeValueAsString(Result.notLogin());
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(ret);
        writer.flush();
    }
}

