package com.uas.finance.filter;

import com.uas.finance.util.FastjsonUtils;
import com.uas.finance.util.SystemSession;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import com.uas.sso.entity.UserAccount;
import com.uas.sso.web.spring.AbstractSSOInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
@Component
public class SSOInterceptor extends AbstractSSOInterceptor {

	@Override
	protected boolean onAuthenticateFailed(HttpServletRequest request, HttpServletResponse response) {
		return false;
	}

	@Override
	protected void onAuthenticateSuccess(HttpServletRequest request, HttpServletResponse response) {
		UserAccount userAccount = (UserAccount) request.getSession().getAttribute("userAccount");
		if (userAccount == null) {
			SSOToken token = SSOHelper.attrToken(request);
			userAccount = getUserByToken(token);
			if (userAccount != null) {
				request.getSession().setAttribute("userAccount", userAccount);
			}
		}
		if (userAccount != null) {
			SystemSession.setUserAccount(userAccount);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		SystemSession.clear();
	}

	private UserAccount getUserByToken(SSOToken token) {
		UserAccount userAccount = null;
		if (token != null && !StringUtils.isEmpty(token.getData())) {
			userAccount = FastjsonUtils.fromJson(token.getData(), UserAccount.class);
		}
		return userAccount;
	}
}
