/* ===================================================================
 * MealSecurityInterceptor.java
 * 
 * Created Nov 10, 2004 11:17:41 AM
 * 
 * Copyright (c) 2004 Matt Magoffin (spamsqr@msqr.us)
 * 
 * This program 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 2 of 
 * the License, or (at your option) any later version.
 * 
 * This program 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 this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
 * 02111-1307 USA
 * ===================================================================
 * $Id: MealSecurityInterceptor.java 39 2009-05-06 03:30:47Z msqr $
 * ===================================================================
 */

package magoffin.matt.ieat.aop;

import magoffin.matt.ieat.IllegalActionException;
import magoffin.matt.ieat.biz.BizContext;
import magoffin.matt.ieat.biz.UserBiz;
import magoffin.matt.ieat.dao.MealDao;
import magoffin.matt.ieat.domain.Meal;
import magoffin.matt.ieat.domain.User;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

/**
 * Security interceptor for Meal actions.
 * 
 * <p>Makes sure for a given Meal and BizContext that the 
 * <code>actingUser</code> is either an admin or the owner 
 * of the Meal.</p>
 * 
 * @author Matt Magoffin (spamsqr@msqr.us)
 * @version $Revision: 39 $ $Date: 2009-05-06 15:30:47 +1200 (Wed, 06 May 2009) $
 */

public class MealSecurityInterceptor implements MethodInterceptor {

	private final Logger log = Logger.getLogger(MealSecurityInterceptor.class);
	
	private MealDao mealDao;

	/* (non-Javadoc)
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
	 */
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object[] args = invocation.getArguments();

		// look for Meal or Integer mealId and BizContext
		Long mealId = null;
		Integer ownerId = null;
		boolean fromMeal = false;
		BizContext context = null;
		for ( int i = 0; i < args.length && (mealId == null || context == null); i++ ) {
			if ( args[i] instanceof Meal ) {
				mealId = ((Meal)args[i]).getMealId();
				User owner = ((Meal)args[i]).getOwner();
				if ( owner != null ) {
					ownerId = owner.getUserId();
				}
				fromMeal = true;
			} else if ( args[i] instanceof Long ) {
				// throw exception if mealId already set from another Long 
				// because we don't know which Long is supposed to be mealId
				if ( mealId != null ) {
					if ( !fromMeal ) {
						throw new RuntimeException("Multiple Long objects found in method arguments: "
							+invocation.toString());
					}
					mealId = (Long)args[i];
				} else {
					mealId = (Long)args[i];
				}
			} else if ( args[i] instanceof BizContext ) {
				context = (BizContext)args[i];
			}
		}
		
		if ( fromMeal && ownerId == null ) {
			return invocation.proceed(); // skip when meal has no owner (assume storing)
		}
		
		if ( mealId == null || context == null || context.getActingUser() == null ) {
			throw new IllegalActionException("Meal ID or acting user not available.");
		}
		
		if ( ownerId == null ) {
			// get owner from meal ID
			Meal meal = mealDao.get(mealId);
			ownerId = meal.getOwner().getUserId();
		}
		
		if ( ownerId != null ) {
			User actingUser = context.getActingUser();
			if ( !ownerId.equals(actingUser.getUserId()) ) {
				// if user not admin, throw exception
				if ( actingUser.getAccessLevel() == null || 
						((actingUser.getAccessLevel().intValue() & UserBiz.ACCESS_ADMIN) != 1) ) {
					log.warn("Acting user " +actingUser.getUserId() +" access to meal "
							+mealId +" denied, meal owner is " +ownerId);
					throw new IllegalActionException();
				}
			}
		}
		
		return invocation.proceed();
	}
	
	/**
	 * @return the mealDao
	 */
	public MealDao getMealDao() {
		return mealDao;
	}
	
	/**
	 * @param mealDao the mealDao to set
	 */
	public void setMealDao(MealDao mealDao) {
		this.mealDao = mealDao;
	}

}
