/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems.interceptor;

import nuts.aems.constant.COOKIE;
import nuts.aems.constant.REQ;
import nuts.aems.model.bean.User;
import nuts.core.bind.json.Jsons;
import nuts.core.lang.StringEncrypts;
import nuts.core.log.Log;
import nuts.core.log.Logs;
import nuts.core.servlet.HttpServletUtils;
import nuts.exts.struts2.interceptor.AuthenticateInterceptor;
import nuts.exts.struts2.util.StrutsContextUtils;
import nuts.exts.xwork2.util.ContextUtils;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


/**
 * 
 */
@SuppressWarnings("serial")
public class UserAuthenticationInterceptor extends AuthenticateInterceptor {

	private static Log log = Logs.getLog(UserAuthenticationInterceptor.class);

	/**
	 * secure user session validate time: 30m 
	 */
	protected static final long SESSION_AGE = 30 * 60 * 1000; 
	
	/**
	 * hasPermission
	 * @param user user
	 * @param namespace namespace
	 * @param action action
	 * @return true if user has permit to access the action
	 */
	public static boolean hasPermission(User user, String namespace, String action) {
		return hasPermission(user.getGroupPermits(), namespace, action);
	}

	@Override
	protected Object getSessionUser() {
		User u = (User)StrutsContextUtils.getRequest().get(USER_ATTRIBUTE);
		if (u == null) {
			HttpServletRequest req = StrutsContextUtils.getServletRequest();
			Cookie c = HttpServletUtils.getCookie(req, COOKIE.USER_TICKET);
			if (c != null) {
				String ticket = c.getValue();
				try {
					ticket = StringEncrypts.decrypt(ticket);
					u = Jsons.fromJson(ticket, User.class);
					ContextUtils.getRequest().put(REQ.USER, u);
				}
				catch (Exception e) {
					log.warn("Incorrect " + COOKIE.USER_TICKET 
							+ ": " + ticket, e);
				}
			}
		}
		
		return u;
	}

	@Override
	protected boolean isSecureSessionUser(Object su) {
		Long lt = ((User)su).getLoginTime();
		if (lt != null) {
			return System.currentTimeMillis() - lt < SESSION_AGE;
		}
		return false;
	}
	
	@Override
	protected List<String> getUserPermits(Object su) {
		return ((User)su).getGroupPermits();
	}
}
