package com.uas.account.web.filter;

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

import org.springframework.util.StringUtils;

import com.uas.account.core.util.FastjsonUtils;
import com.uas.account.entity.User;
import com.uas.account.support.SystemSession;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import com.uas.sso.web.spring.AbstractSSOInterceptor;

public class SSOInterceptor extends AbstractSSOInterceptor {

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

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

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

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

}
