//Sample code file: var/ndk/webBuildengine/tmp/viewable_samples/a4ad0b48-dd95-46b6-8289-721e99c8dc76/login_method/mgmt/consoleone/src/com/novell/admin/ndssnapins/loginMethods/CPassword/CPasswordPanel.java //Warning: This code has been marked up for HTML

/*=============================================================================
  CPasswordPanel.java

  Copyright (c) 1999-2002 Novell, Inc. All Rights Reserved.

  THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
  USE AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO THE LICENSE AGREEMENT
  ACCOMPANYING THE SOFTWARE DEVELOPMENT KIT (SDK) THAT CONTAINS THIS WORK.
  PURSUANT TO THE SDK LICENSE AGREEMENT, NOVELL HEREBY GRANTS TO DEVELOPER A
  ROYALTY-FREE, NON-EXCLUSIVE LICENSE TO INCLUDE NOVELL'S SAMPLE CODE IN ITS
  PRODUCT. NOVELL GRANTS DEVELOPER WORLDWIDE DISTRIBUTION RIGHTS TO MARKET,
  DISTRIBUTE, OR SELL NOVELL'S SAMPLE CODE AS A COMPONENT OF DEVELOPER'S
  PRODUCTS. NOVELL SHALL HAVE NO OBLIGATIONS TO DEVELOPER OR DEVELOPER'S
  CUSTOMERS WITH RESPECT TO THIS CODE.
==============================================================================*/
package com.novell.admin.ndssnapins.loginMethods.CPassword;

import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
import com.novell.application.console.widgets.*;
import com.novell.admin.common.ui.*;
import com.novell.admin.ns.*;
import com.novell.admin.ns.nds.*;
import com.novell.admin.common.snapins.*;
import com.novell.admin.common.exceptions.*;
import com.novell.application.console.snapin.*;
import com.novell.utility.nmsgbox.*;

import com.novell.security.japi.nmas.*;

/** CPasswordPanel lets the admin set the user's cleartext password.
*/
public final class CPasswordPanel extends AdminPage
implements ItemListener, ActionListener, KeyListener
{
  // data
   private String treeName, userDN;   // treeName and userDN are passed into CPasswordPanel Constructor
    private NSObject userObj;          // userObj is passed into CPasswordPanel Constructor
   
  // Translated strings
   private String cPasswordLabel = CPassword.getString(CPassword.CPassword_LABEL);
   private String entryLabel = CPassword.getString(CPassword.CPassword_ENTRY_LABEL);
   private String confirmLabel = CPassword.getString(CPassword.CPassword_CONFIRM_LABEL);
   private String allowLabel = CPassword.getString(CPassword.CPassword_ALLOW_LABEL);
   private String cPasswordInstructions = CPassword.getString(CPassword.CPassword_INSTRUCTIONS);
   private String noRightsLabel = CPassword.getString(CPassword.CPassword_NO_RIGHTS_LABEL);
       
  // Attributes
   private NDSObjectAttribute hostServerAttrib = null;  // Case Ignore String
   
  // Controls
   private JCheckBox cPasswordAllowCheck = new JCheckBox(allowLabel, false);
   private JPasswordField entryField = new JPasswordField(20);
    private JPasswordField confirmField = new JPasswordField(20);
    private JLabel entryJLabel = new JLabel(entryLabel);
    private JLabel confirmJLabel = new JLabel(confirmLabel);
    private JPanel entryJPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));//new NVerticalFlowLayout());
    private JPanel confirmJPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));//new NVerticalFlowLayout());
        
  // Private Booleans
   private boolean debug = false;
   private boolean hasAdminRights = false;
   private boolean hasWriteRights = false;
   private boolean cPasswordAllow = false;   
   private boolean allowModified = false;
   private boolean anythingToSave = false;
   private boolean readDataComplete = false;
   
  // Private Colors
   private Color colorOn;
   private Color colorOff;

   /** Constructor
   *
   * @param   InitSnapinInfo
   * @param   AdminPageSnapin
   * @param   NSObject
   * @param   tree
   * @param   user
   * @exception   com.novell.admin.common.exceptions.SPIException
   */
   public CPasswordPanel( InitSnapinInfo snapinInfo,
                     AdminPageSnapin snapin,
                     NSObject obj,
                     String tree,
                     String user)
   {
        super( snapinInfo, snapin, obj );
        printDebuggingLine("tree: " + tree + "   user: " + user);
        treeName = tree;
        userDN = user;
        userObj = obj;
        
        ObjectEntryCollection oec = shell.getCurrentSelections();
        ObjectEntry oe;
        if (oec.hasNoElements())
        {
           oe = shell.getTreeSelection();
        }
        else
        {
           oe = oec.getFirstElement();
        }
        if (null != oe)
        {
            NDSNamespace ns = ((NDSNamespace)oe.getObjectType().getNamespace());
            try 
            {
                ObjectEntry authUserOE = ((AuthenticationNamespace)ns).getAuthenticatedIdentity(oe);
                NDSObjectRights objRights = (NDSObjectRights)ns.getObjectEffectiveRights(oe, authUserOE);
                hasAdminRights = objRights.hasSupervisorRights();
                if (hasAdminRights == true)
                {
                    hasWriteRights = true;
                }
                else
                {
                    hasWriteRights = objRights.hasWriteRights();
                }
            }
            catch (SPIException exception)
            {
                printDebuggingLine("Got exception checking for admin rights.");
            }
        }
        
       // Use BorderLayout with some vertical gap to separate elements
        setLayout( new BorderLayout(0,5) );
   }// constructor

    protected void enableCPasswordEntry()
    {
       entryField.setEnabled(true);
       entryField.setBackground(colorOn);
       entryJLabel.setEnabled(true);
        confirmField.setEnabled(true);
        confirmField.setBackground(colorOn);
        confirmJLabel.setEnabled(true);
    }

    protected void disableCPasswordEntry()
    {
       entryField.setBackground(colorOff);
       entryField.setEnabled(false);
       entryJLabel.setEnabled(false);
        confirmField.setBackground(colorOff);
        confirmField.setEnabled(false);
        confirmJLabel.setEnabled(false);
    }

   /** itemStateChanged is a public method ItemListener to process JCheckBox
    */
   public void itemStateChanged(ItemEvent event)
    {
       printDebuggingLine("itemStateChanged.event: " + event);
        Object src = event.getSource();
        int i;

      if (readDataComplete)
      {
           if (src == cPasswordAllowCheck) 
           {
               anythingToSave = true;
               propertyBook.setModified(true, pageSnapin);
               allowModified = (!allowModified);
               cPasswordAllow = cPasswordAllowCheck.isSelected();
               printDebuggingLine("cPasswordAllow: " + cPasswordAllow);
               if (cPasswordAllow)
               {
                   enableCPasswordEntry();
               }
               else
               {
                   disableCPasswordEntry();
               }
            }
        }
    }

   /** Event Handler for buttons.
   *
   * @param   evt ActionEvent
   */
   public void actionPerformed( ActionEvent evt )
   {
   }
   
  // If they press any keys, the page is dirty
   public void keyReleased(KeyEvent e)
   {
   }
   
  // If they press any keys, the page is dirty
   public void keyTyped(KeyEvent e)
   {
       anythingToSave = true;
       propertyBook.setModified(true, pageSnapin);
   }
   
  // If they press any keys, the page is dirty
   public void keyPressed(KeyEvent e)
   {
   }
   
   /** Check the users rights for each attribute displayed on this page but since this page cannot be
   *  modified then there is no use to check rights
   *
   * @exception   com.novell.admin.common.exceptions.SPIException
   */
   protected void checkRights() throws SPIException
   {
   }
   
   protected void printDebuggingLine(String theLine)
    {
        if(debug)
        {
            System.out.println(theLine);
        }
    }
    
   /** Lays out the controls.
   */
   protected void layoutControls()
   {
      JPanel cPasswordJPanel = null;
      NWrapLabel header = null;
      
      if (hasWriteRights == true)
      {
         // panel for cleartext passwords
            colorOff = entryJLabel.getBackground();
            colorOn = entryField.getBackground();
            
            entryJPanel.add(entryJLabel);
            entryJPanel.add(entryField);
            confirmJPanel.add(confirmJLabel);
            confirmJPanel.add(confirmField);
          
           cPasswordAllowCheck.setSelected(false);
           entryField.setEchoChar('*');
            confirmField.setEchoChar('*');
           disableCPasswordEntry();
           
           // Controls are ready, place them in panels
            NVerticalFlowLayout myFLayout = new NVerticalFlowLayout();
            myFLayout.setExternalPadLeft(10);
            cPasswordJPanel = new JPanel(myFLayout);
            cPasswordJPanel.add(cPasswordAllowCheck);
            cPasswordJPanel.add(entryJPanel);
            cPasswordJPanel.add(confirmJPanel);
            
            cPasswordJPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),cPasswordLabel));
        }
        else// does not have write rights
        {
           // don't create the cPasswordJPanel
        }
            
       // create control panel
      NVerticalFlowLayout vflControl = new NVerticalFlowLayout(false, 0);
      vflControl.setExternalPadLeft(0);
      JPanel controlPanel = new JPanel(vflControl);
      if (cPasswordJPanel != null)
      {
         controlPanel.add(cPasswordJPanel, NVerticalFlowLayout.LEFT);
      }
          
     // Add the top level panels
      
      if (hasAdminRights || hasWriteRights)
      {
         header = new NWrapLabel(cPasswordInstructions);
      }
      else
      {
         header = new NWrapLabel(noRightsLabel);
      }
      
      header.setMaxWidth(615);
      add(header, BorderLayout.NORTH);
      add(controlPanel, BorderLayout.WEST);
    }

    /*
    * This panel saveData() method is called each time the user exits the 
    * panel.  For example, if the user clicks on the tab of another snapin
    * then this saveData() method is called.  To only save data when the user 
    * selects "Ok" or "Apply" we do nothing in this method, and instead 
    * implement a saveData() method in the "Snapin" class.  The snapin level 
    * saveData() method is only called when the user selects "Ok" or "Apply". 
    * The snapin saveData() calls the savePassword() mehtod below.
    */
    public boolean saveData()
   {
       return(true);
   }

   /** Queries each control to find out if they have been modified and then
   *   calls the appropriate method to actually do the write.
   */
   public boolean savePassword()
   {
      int ccode,i;
      
      if (!hasWriteRights && !hasAdminRights)
      {
          printDebuggingLine("Doesn't have write rights.");
          propertyBook.setModified(false, pageSnapin);
          return(true);
      }
      
      if (!anythingToSave)
      {
          printDebuggingLine("Nothing to save.");
          propertyBook.setModified(false, pageSnapin);
          return(true);
      }
      
        if (cPasswordAllow)
      {             
         if (allowModified)
         {
            //  Save the cPasswordAllow flag to Login Config data on the user object
             if ((ccode = NMASWrap.NMAS_PutLoginConfig(treeName, userDN, CPassword.MethodIDLen, CPassword.MethodID, CPassword.AllowTag, CPassword.AllowDataLen, CPassword.AllowData)) != 0)
             {
                   String message = CPassword.getString(CPassword.CPassword_PLC_ERR_MSG) + ccode;
                   NMsgBox msg = new NMsgBox(shell.getShellFrame(), CPassword.getString(CPassword.CPassword_ENTRY_ERR_TITLE), message, NMsgBox.ERROR, null, null);
                    msg.show();
                    return(false);
               }
               allowModified = false;
           }
           
          // Verify Password Entry
           String cPasswordString = new String(entryField.getPassword());
              String cPasswordConfirmString = new String(confirmField.getPassword());

              printDebuggingLine("clear password: " + cPasswordString + "\n clear confirm : " + cPasswordConfirmString);
           if (cPasswordString.equals(cPasswordConfirmString) == false)
           {
                String message = CPassword.getString(CPassword.CPassword_UNEQUAL_ERR_MSG);
              NMsgBox msg = new NMsgBox(shell.getShellFrame(), CPassword.getString(CPassword.CPassword_ENTRY_ERR_TITLE), message, NMsgBox.ERROR, null, null);
                msg.show();
                propertyBook.setModified(true, pageSnapin);
                return(false);
           }

           // Save cPassword to Login Secret data on the user object
           // Note:  Login Secret Data can only be written and deleted.  It cannot be read.
            byte CPasswordData[] = cPasswordString.getBytes();
            if ((ccode = NMASWrap.NMAS_PutLoginSecret(treeName, userDN, CPassword.MethodIDLen, CPassword.MethodID, CPassword.SecretTag, CPasswordData.length, CPasswordData)) != 0)
            {
               String message = CPassword.getString(CPassword.CPassword_PLC_ERR_MSG) + ccode;
               NMsgBox msg = new NMsgBox(shell.getShellFrame(), CPassword.getString(CPassword.CPassword_ENTRY_ERR_TITLE), message, NMsgBox.ERROR, null, null);
                msg.show();
                return(false);
            }
            else
            {
                printDebuggingLine("NMAS_PutLoginSecret returned " + ccode);
                printDebuggingLine("The Clear Password was '" + cPasswordString + "'");
            }
        }
        else// not (CPasswordAllowed)
        {
            if (allowModified) 
            {
            //  Save the cPasswordAllow flag to Login Config data on the user object
             if ((ccode = NMASWrap.NMAS_PutLoginConfig(treeName, userDN, CPassword.MethodIDLen, CPassword.MethodID, CPassword.AllowTag, CPassword.AllowDataLen, CPassword.DoNotAllowData)) != 0)
             {
                   String message = CPassword.getString(CPassword.CPassword_PLC_ERR_MSG) + ccode;
                  NMsgBox msg = new NMsgBox(shell.getShellFrame(), CPassword.getString(CPassword.CPassword_ENTRY_ERR_TITLE), message, NMsgBox.ERROR, null, null);
                    msg.show();
                    return(false);
               }

               // Delete cPassword from Login Secret data on the user object
               // Note:  Login Secret Data can only be written and deleted.  It cannot be read.
               if ((ccode = NMASWrap.NMAS_DeleteLoginSecret(treeName, userDN, CPassword.MethodIDLen, CPassword.MethodID, CPassword.SecretTag)) != 0)
             {
                   String message = CPassword.getString(CPassword.CPassword_DLC_ERR_MSG) + ccode;
                  NMsgBox msg = new NMsgBox(shell.getShellFrame(), CPassword.getString(CPassword.CPassword_ENTRY_ERR_TITLE), message, NMsgBox.ERROR, null, null);
                    msg.show();
                    return(false);
               }
               
               allowModified = false;// Clear the allowModified flag
           }
        }

       // Clear modified flags
        anythingToSave = false;
      propertyBook.setModified(false, pageSnapin);
        return true;
   }

   public void setupMOD()
   {
   }

   /** 
   * readData is required by com.novell.admin.common.ui.AdminPage
   */
   protected void readData()
   {
       int ccode = 0;
      int bytesRead[] = new int[1];
      byte areCPasswordsAllowed[] = new byte[CPassword.AllowDataLen];

       // Read cPasswordAllowed flag from Login Config data on the user object
      if ((ccode = NMASWrap.NMAS_GetLoginConfig(treeName, userDN, CPassword.MethodIDLen, CPassword.MethodID, CPassword.AllowTag, CPassword.AllowDataLen, bytesRead, areCPasswordsAllowed)) != 0)
      {
            printDebuggingLine("Error" + ccode + "from NMAS_GetLoginConfig");
        }
        else if (bytesRead[0] == 0)
        {
            printDebuggingLine("Zero bytes read from NMAS_GetLoginSecret");
        }
        else if (areCPasswordsAllowed[0] == 1)
       {
           cPasswordAllow = true;
           cPasswordAllowCheck.setSelected(true);
           enableCPasswordEntry();
       }
       else
       {
           cPasswordAllow = false;
           cPasswordAllowCheck.setSelected(false);
           disableCPasswordEntry();
       }

       // Add Listeners
        cPasswordAllowCheck.addItemListener(this);
        entryField.addKeyListener(this);
        confirmField.addKeyListener(this);
        
        readDataComplete = true;
   }

  /** Called just before the page is set as the current page.
   *
   * @param   I-isFirstTimeShown   true, if first time page is shown, false otherwise.
   */
   public void setActive(boolean isFirstTimeShown)
   {
      printDebuggingLine("setActive.isFirstTimeShown: " + isFirstTimeShown);
      super.setActive(isFirstTimeShown);
   }

   /** Called just before the page loses the focus.
   *
   * @return  true, if ok to leave this page, false otherwise.
   */
   public boolean killActive()
   {
      printDebuggingLine("killActive");
      return super.killActive();
   }

   /**   Called through the interface on shutdown to clean up listeners, etc.
   */
   public void shutdownSnapin()
   {
      printDebuggingLine("shutdownSnapin");
      super.shutdownSnapin();
   }

   /**
    * Definition of interface AttributeHandler.  
    * Returns all attributes that this PageSnapin is going to handle.
    * getHandledAttributeNames is required by com.novell.admin.common.ui.AdminPage
    * Must have attribute handlers for each attribute.
    *
    * @return  The String[] of the handled attribute names
    *
    * @see  com.novell.admin.common.snapins.AttributeHandler
    */   
   public String[] getHandledAttributeNames()
   {
      String[] attributes = new String[1];
      attributes[0] = "";
      return attributes;
   }
}