package com.tofly.feesapi.security.compent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
@AllArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding(CommonConstants.UTF8);
        httpServletResponse.setContentType(CommonConstants.CONTENT_TYPE);
        ResultRespone<String> result = new ResultRespone<>();
        result.setCode(HttpStatus.UNAUTHORIZED.value());
        if (e != null) {
            result.setMessage("没有访问权限："+e.getMessage());
        }
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
