/* ===================================================================
 * RecipeSecurityInterceptor.java
 * 
 * Created Oct 11, 2004 4:57:27 PM
 * 
 * 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: RecipeSecurityInterceptor.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.RecipeDao;
import magoffin.matt.ieat.domain.Recipe;
import magoffin.matt.ieat.domain.User;

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

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

public class RecipeSecurityInterceptor implements MethodInterceptor {
	
	private final Logger log = Logger.getLogger(RecipeSecurityInterceptor.class);
	
	private RecipeDao recipeDao;

	/* (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 Recipe or Integer recipeId and BizContext
		Long recipeId = null;
		Integer ownerId = null;
		boolean fromRecipe = false;
		BizContext context = null;
		for ( int i = 0; i < args.length && (recipeId == null || context == null); i++ ) {
			if ( args[i] instanceof Recipe ) {
				recipeId = ((Recipe)args[i]).getRecipeId();
				User owner = ((Recipe)args[i]).getOwner();
				if ( owner != null ) {
					ownerId = owner.getUserId();
				}
				fromRecipe = true;
			} else if ( args[i] instanceof Long ) {
				// throw exception if recipeId already set from another Long 
				// because we don't know which Long is supposed to be recipeId
				if ( recipeId != null ) {
					if ( !fromRecipe ) {
						throw new RuntimeException("Multiple Long objects found in method arguments: "
							+invocation.toString());
					}
					recipeId = (Long)args[i];
				} else {
					recipeId = (Long)args[i];
				}
			} else if ( args[i] instanceof BizContext ) {
				context = (BizContext)args[i];
			}
		}
		
		if ( fromRecipe && ownerId == null ) {
			return invocation.proceed(); // skip when recipe has no owner (assume storing)
		}
		
		if ( recipeId == null || context == null || context.getActingUser() == null ) {
			throw new IllegalActionException("Recipe ID or acting user not available.");
		}
		
		if ( ownerId == null ) {
			// get owner from recipe ID
			Recipe recipe = recipeDao.get(recipeId);
			if ( recipe.getOwner() != null ) {
				ownerId = recipe.getOwner().getUserId();
			}
			if ( ownerId == null ) {
				// set to acting user, perhaps recipe owner has been deleted, 
				// so at least an admin user should be able to delete recipe
				ownerId = context.getActingUser().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 recipe "
							+recipeId +" denied, recipe owner is " +ownerId);
					throw new IllegalActionException();
				}
			}
		}
		
		return invocation.proceed();
	}
	
	/**
	 * @return the recipeDao
	 */
	public RecipeDao getRecipeDao() {
		return recipeDao;
	}
	
	/**
	 * @param recipeDao the recipeDao to set
	 */
	public void setRecipeDao(RecipeDao recipeDao) {
		this.recipeDao = recipeDao;
	}
	
}
