package examples.security.acl;

import java.security.acl.*;
import java.util.*;
import javax.naming.*;
import weblogic.rmi.*;
import weblogic.security.acl.*;
import weblogic.security.audit.Audit;

/**
 * Class FrobImpl illustrates how to use an ACL to
 * protect an RMI object's method. You will see either a success
 * message or a SecurityException from the frob method.
 *
 * @author Copyright (c) 1997-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class FrobImpl implements Frobable {

  final static String ACL_NAME = "aclexample";
  final static String PERMISSION_NAME = "frob";
  final static String REALM_NAME = "weblogic";

  /**
   * Illustrates two ways to check access permissions of an RMI object.
   * Checking permission is a single static method call for ACLs in
   * the WebLogic Realm. Also shown here is a general
   * method of checking security for the current user in the
   * current Realm.
   */
  public void frob() throws RemoteException {

    // For ACLs in the weblogic realm, you can use static methods in Security.
    Security.checkPermission("Frob",
			     Security.getCurrentUser(), 
			     ACL_NAME, 
			     Security.getRealm().getPermission(PERMISSION_NAME),
			     '.');

    // In general, the following works, but you're better off using
    // the static methods because they will audit for you.
    User p = Security.getCurrentUser();
    BasicRealm realm = Realm.getRealm(REALM_NAME);
    Acl acl = realm.getAcl(ACL_NAME);
    Permission perm = realm.getPermission(PERMISSION_NAME);
    boolean result = acl == null || !acl.checkPermission(p, perm);
    
    Audit.checkPermission("Frob", acl, p, perm, !result);
    
    if (result) {
      Security.logAndThrow(PERMISSION_NAME + " denied for user " + p);
    }
    System.out.println("User " + p + " frobbed successfully");
  }    
  
  /**
   * Creates a FrobImpl and binds in JNDI as <tt>frob target</tt>.
   */
  public static void main(String args[]) {
    Context ctx = null;
    try {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,
              "weblogic.jndi.WLInitialContextFactory");
      ctx = new InitialContext(env);
      ctx.bind("frobtarget", new FrobImpl());
    }
    catch (Throwable t) {
      t.printStackTrace();
    }
    finally {
      try {ctx.close();}
      catch (Exception e) {
        // Deal with any failure
      }
    }
  }
}
