package com.ximai.framework.security.handle;


import com.ximai.common.utils.data.StringUtils;
import com.ximai.framework.config.properties.HttpBasicAuthProperties;
import com.ximai.framework.security.BasicAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

	@Autowired
    ApplicationContext applicationContext;

	@Autowired
	HttpBasicAuthProperties httpBasicAuthProperties;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean basicAuth = false;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;

			if (handlerMethod.getBean() instanceof ErrorController) {
				return true;
			}

			Method method = handlerMethod.getMethod();
			if (!method.isAnnotationPresent(BasicAuth.class)) {
				return true;
			}

			if (method.isAnnotationPresent(BasicAuth.class)) {
				basicAuth = true;
			}
		}

		String authorization = request.getHeader("Authorization");

		try {
			if (basicAuth) {
				checkBasicAuth(authorization);
			}
		} catch (RuntimeException e) {
			response.sendError(401, e.getMessage());
			return false;
		}
		return true;
	}

	private void checkBasicAuth(String authorization) {
		if (authorization == null || authorization.isEmpty()) {
			throw new RuntimeException("无Authorization，请登录");
		}
		if (!authorization.toUpperCase().startsWith("BASIC ")) {
			throw new RuntimeException("不支持的验证方式，请使用Basic ");
		}
		authorization = authorization.substring(6, authorization.length());
		String decodedAuth = StringUtils.base64Decode(authorization);
		if (decodedAuth == null || "".equals(decodedAuth)) {
			decodedAuth = "";
		}
		String[] useAuth = decodedAuth.split(":");
		if (useAuth.length < 2) {
			throw new RuntimeException("BasicAuth验证失败");
		}
		String userName = useAuth[0];
		String password = useAuth[1];
		if (userName.compareTo(httpBasicAuthProperties.getUserName()) != 0
				|| password.compareTo(httpBasicAuthProperties.getPassword()) != 0) {
			throw new RuntimeException("BasicAuth验证失败，用户名或密码错误");
		}

	}


}
