package com.skr.mdm.authentication.user;

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/16 14:36
 */
@Component
public class UserAuthenticationEntryPoint 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) {
            if (StringUtils.equals(ResultCodeEnum.TOKEN_EXPIRE.getCode(), ((TokenExpireException) authException).getCode())) {
                result = ResponseResult.failure(ResultCodeEnum.TOKEN_EXPIRE);
            }
            if (StringUtils.equals(ResultCodeEnum.TOKEN_ILLEGAL.getCode(), ((TokenExpireException) authException).getCode())) {
                result = ResponseResult.failure(ResultCodeEnum.TOKEN_ILLEGAL);
            }
        }
        if (authException instanceof UserTimeCheckException) {
            result = ResponseResult.failure(ResultCodeEnum.TIME_CHECK);
        }
        if (authException instanceof IllegalUserRequestException) {
            result = ResponseResult.failure(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), result);
    }
}
