package com.lutao.cloud.common.security.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lutao.cloud.common.core.constant.CommonConstants;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.StringUtil;
import com.lutao.cloud.common.security.sso.SSOAuthenticationToken;
import com.lutao.cloud.common.security.util.CloudSecurityMessageSourceUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 异常处理{@link org.springframework.security.core.AuthenticationException } 不同细化异常处理
 *

 * @date 2020-06-14
 */
@Slf4j
@Component
public class CloudCommenceAuthExceptionEntryPoint implements AuthenticationEntryPoint{
	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private TokenStore tokenStore;

	@Override
	@SneakyThrows
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException){
		response.setCharacterEncoding(CommonConstants.UTF8);
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		MessageInfo<String> result = new MessageInfo<>();
		result.setMsg(authException.getMessage());
		result.setData("/");
		result.setCode(CommonConstants.FAIL);

		try {
			String authHeader = request.getHeader("Authorization");
			if (StringUtil.isNoneBlank(authHeader)) {
				String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
				OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
				if (accessToken != null) {
					OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
					if (auth2Authentication.getUserAuthentication() instanceof SSOAuthenticationToken) {
					} else {
						result.setData("/#/login");
					}
				}
			}
		} catch (Exception e) {
			log.error("cloud commence auth exception Authorization error", e);
		}

		if (authException instanceof CredentialsExpiredException
				|| authException instanceof InsufficientAuthenticationException){
			String msg = CloudSecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage());
			result.setMsg(msg);
		}

		if (authException instanceof UsernameNotFoundException){
			String msg = CloudSecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.noopBindAccount", authException.getMessage());
			result.setMsg(msg);
		}

		if (authException instanceof BadCredentialsException){
			String msg = CloudSecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.badClientCredentials", authException.getMessage());
			result.setMsg(msg);
		}

		response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(objectMapper.writeValueAsString(result));
	}

}
