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.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
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;

/**
 * 需要在 SecurityConfig 设置 （它只会走自己的方法，不再走自定义的 login 了）
 * 没有使用
 * httpSecurity.formLogin().loginProcessingUrl(CommonConst.WEB_REST_SERVICE_PREFICX + "auth" + loginPath).failureHandler(jwtAuthenticationFailureHandler);
 *
 * @Description:如果身份验证失败时调用
 * @author
 */
@Component("jwtAuthenticationFailureHandler")
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(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", "Forbidden");
        responsemap.put("status", HttpStatus.UNAUTHORIZED);
        responsemap.put("timestamp", new Date());
        responsemap.put("path", httpServletRequest.getRequestURI());
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(responsemap));
    }
}

