package com.skr.mdm.authentication.admin;

import com.skr.mdm.authentication.TokenExpireException;
import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
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;

/**
 * @author nfq
 * @date 2020/7/17 11:00
 */
@Component
public class AdminAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = ResponseResult.failure(ResultCodeEnum.LOGIN_NONE);
        if (authException instanceof TokenExpireException) {
            result = ResponseResult.failure(ResultCodeEnum.TOKEN_EXPIRE);
        }
        if (authException instanceof VerifyCodeException) {
            if (StringUtils.equals(ResultCodeEnum.VERIFY_CODE_EMPTY.getCode(), ((VerifyCodeException) authException).getCode())) {
                result = ResponseResult.failure(ResultCodeEnum.VERIFY_CODE_EMPTY);
            }
            if (StringUtils.equals(ResultCodeEnum.VERIFY_CODE_EXPIRE.getCode(), ((VerifyCodeException) authException).getCode())) {
                result = ResponseResult.failure(ResultCodeEnum.VERIFY_CODE_EXPIRE);
            }
            if (StringUtils.equals(ResultCodeEnum.VERIFY_CODE_ERROR.getCode(), ((VerifyCodeException) authException).getCode())) {
                result = ResponseResult.failure(ResultCodeEnum.VERIFY_CODE_ERROR);
            }
        }
        ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), result);
    }
}
