package com.dbxml.db.common.security;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * 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: DefaultSecurityManager.java,v 1.3 2004/02/12 00:17:56 bradford Exp $
 */

import com.dbxml.db.core.security.*;

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.Database;
import com.dbxml.db.core.DatabaseEventListener;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.security.SecurityException;

/**
 * DefaultSecurityManager is the default SecurityManager implementation
 * for dbXML.
 */

public final class DefaultSecurityManager extends SecurityManagerBase {
   private static final String NAME = "accessmanager";

   private AccessUtils utils;

   public void setDatabase(Database database) {
      super.setDatabase(database);
      database.addDatabaseEventListener(new DefaultEventListener());
   }

   private AccessUtils getAccessUtils() {
      if ( utils == null ) {
         try {
            userStack.pushCurrentUser(magicUser);
            Collection sysCol = database.getSystemCollection();
            AccessManager manager = (AccessManager)sysCol.getExtensionManager().get(NAME);
            utils = manager.getAccessUtils();
         }
         catch ( DBException e ) {
            System.err.println("FATAL ERROR: Can't retrieve AccessManager Extensions '"+NAME+"'");
            e.printStackTrace(System.err);
            System.exit(1);
         }
         finally {
            userStack.popCurrentUser();
         }
      }
      return utils;
   }

   public void authenticate(String userID, String password) throws SecurityException {
      try {
         userStack.clear();

         User u = readUser(userID);
         if ( !u.checkPassword(password) )
            throw new InvalidCredentialsException("Invalid password for User '"+userID+"'");

         userStack.pushCurrentUser(u);
      }
      catch ( DBException e ) {
         throw new SecurityException(FaultCodes.SEC + FaultCodes.GEN_CRITICAL_ERROR, e);
      }
   }

   public void access(String path, int mask) throws SecurityException {
      User user = userStack.getCurrentUser();

      if ( user == null )
         throw new InvalidUserException("No User has been authenticated");

      if ( user != magicUser ) {
         Access a = readAccess(path);
         String[] roleList = user.listRoles();
         int combined = 0;
         for ( int i = 0 ; i < roleList.length; i++ ) {
				Role role = readRole(roleList[i]);
            combined |= a.getPermissions(role);
			}
         if ( (combined & mask) != mask )
            throw new InvalidAccessException("Insufficient access to '"+path+"' for User '"+user.getId()+"'");
      }
   }

   private User readUser(String userID) throws InvalidUserException {
      try {
         userStack.pushCurrentUser(magicUser);
         return getAccessUtils().readUser(userID);
      }
      finally {
         userStack.popCurrentUser();
      }
   }

   private Role readRole(String RoleID) throws InvalidRoleException {
      try {
         userStack.pushCurrentUser(magicUser);
         return getAccessUtils().readRole(RoleID);
      }
      finally {
         userStack.popCurrentUser();
      }
   }

   private Access readAccess(String path) throws InvalidAccessException {
      try {
         userStack.pushCurrentUser(magicUser);
         return getAccessUtils().readAccess(path);
      }
      finally {
         userStack.popCurrentUser();
      }
   }


   /**
    * DefaultEventListener
    */

   private class DefaultEventListener implements DatabaseEventListener {
      public void createCollection(Collection collection) {
         // NOOP
      }

      public void dropCollection(Collection collection)  {
         try {
            userStack.pushCurrentUser(magicUser);
            getAccessUtils().removeAccess(collection.getCanonicalName());
         }
         catch ( DBException e ) {
            // NOOP
         }
         finally {
            userStack.popCurrentUser();
         }
      }
   }
}



