package com.philisense.www.handler;

import com.alibaba.fastjson.JSON;
import com.philisense.www.constant.HttpStatus;
import com.philisense.www.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 认证失败处理类 返回未授权
 *
 * @Description:它负责启动未经过身份验证的用户的身份验证过程(当他们试图访问受保护的资源
 * @author
 */
@Component("jwtAuthenticationEntryPoint")
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String,Object> responsemap = new HashMap<>();
        responsemap.put("success", false);
        responsemap.put("message", "未登陆或者登陆超时，无法访问该资源!");
        responsemap.put("error", "Non-authoritative Information,So Forbidden");
        responsemap.put("status", HttpStatus.UNAUTHORIZED_INFO);
        responsemap.put("timestamp", new Date());
        responsemap.put("path", httpServletRequest.getRequestURI());
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(responsemap));
    }
}
