package ink.wgink.login.base.handler;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.login.base.consts.IUserCenterConst;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

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

/**
 * @ClassName: LoginFailureHandler
 * @Description: 登录失败
 * @Author: WangGeng
 * @Date: 2019-05-30 11:19
 * @Version: 1.0
 **/
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    public LoginFailureHandler(String defaultFailureUrl) {
        super(defaultFailureUrl);
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            JSONObject errorOb = new JSONObject();
            errorOb.put(IUserCenterConst.ERROR_MESSAGE, exception.getMessage());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().write(errorOb.toJSONString());
        } else {
            request.getSession().setAttribute(IUserCenterConst.ERROR_MESSAGE, exception.getMessage());
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
