package com.skr.mdm.authentication.user;

import com.skr.mdm.authentication.user.imei.ImeiAuthenticationException;
import com.skr.mdm.authentication.user.oaid.OaidAuthenticationException;
import com.skr.mdm.authentication.user.qr.NumberLimitException;
import com.skr.mdm.authentication.user.uuid.UuidAuthenticationException;
import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

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

/**
 * @author nfq
 * @date 2020/7/15 11:52
 */
@Component
public class UserAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        ResponseResult result = ResponseResult.failure(ResultCodeEnum.LOGIN_FAILURE);
        if (exception instanceof ImeiAuthenticationException) {
            result = ResponseResult.failure(ResultCodeEnum.IMEI_NONE);
        }
        if (exception instanceof OaidAuthenticationException) {
            result = ResponseResult.failure(ResultCodeEnum.OAID_NONE);
        }
        if (exception instanceof UuidAuthenticationException) {
            result = ResponseResult.failure(ResultCodeEnum.UUID_NONE);
        }
        if (exception instanceof NumberLimitException) {
            result = ResponseResult.failure(ResultCodeEnum.NUMBER_OVER);
        }
        if (exception instanceof InternalAuthenticationServiceException) {
            result = ResponseResult.failure("当前设备信息已注册");
        }
        ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), result);
    }



}
