All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hfg.security.CredentialsMgr Maven / Gradle / Ivy

There is a newer version: 20240423
Show newest version
package com.hfg.security;

import com.hfg.util.StringUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

//------------------------------------------------------------------------------
/**
 * Simple login store to keep passwords out of the source code.
 * Unless otherwise specified the default file is called '.credMgr' and is found
 * in the user's home directory. The file should only be readable by the account owner.
 * The contents lines are expected to be three whitespace-separated fields: the key, the login, and the password.
 *
 * @author J. Alex Taylor, hairyfatguy.com
 */
//------------------------------------------------------------------------------
// com.hfg XML/HTML Coding Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
// [email protected]
//------------------------------------------------------------------------------

public class CredentialsMgr
{
   private File mFile;

   private static String sDefaultFilename = ".credMgr";

   //###########################################################################
   // CONSTRUCTORS
   //###########################################################################

   //---------------------------------------------------------------------------
   public CredentialsMgr()
   {
      this(new File(System.getProperty("user.home"), sDefaultFilename));
   }

   //---------------------------------------------------------------------------
   public CredentialsMgr(File inFile)
   {
      mFile = inFile;
   }

   //###########################################################################
   // PUBLIC METHODS
   //###########################################################################

   //---------------------------------------------------------------------------
   public File getFile()
   {
      return mFile;
   }

   //---------------------------------------------------------------------------
   public LoginCredentials get(String inKey)
      throws SecurityException
   {
      LoginCredentials credentials = null;

      if (! mFile.exists())
      {
         throw new SecurityException("The CredentialsMgr file " + StringUtil.singleQuote(mFile.getPath()) + " doesn't exist!");
      }
      else if (! mFile.canRead())
      {
         throw new SecurityException("No permissions for reading the CredentialsMgr file " + StringUtil.singleQuote(mFile.getPath()) + "!");
      }

      BufferedReader reader = null;
      try
      {
         try
         {
            reader = new BufferedReader(new FileReader(getFile()));
            String line;
            while ((line = reader.readLine()) != null)
            {
               line = line.trim();
               if (line.startsWith("#"))
               {
                  continue; // Allow comment lines
               }

               String fields[] = parseLine(line);
               if (fields.length >= 3
                   && fields[0].equals(inKey))
               {
                  credentials = new LoginCredentials(fields[1], fields[2].toCharArray());
                  break;
               }
            }
         }
         finally
         {
            if (reader != null)
            {
               reader.close();
            }
         }
      }
      catch (Exception e)
      {
         throw new SecurityException("Problem accessing the CredentialsMgr file " + StringUtil.singleQuote(mFile.getPath()) + "!", e);
      }

      if (null == credentials)
      {
         throw new SecurityException("The key " + StringUtil.singleQuote(inKey)
                                     + " couldn't be found in the CredentialsMgr file " + StringUtil.singleQuote(mFile.getPath()) + "!");
      }

      return credentials;
   }

   //---------------------------------------------------------------------------
   private String[] parseLine(String inLine)
   {
      List fields = new ArrayList<>();

      boolean inQuotedValue = false;
      int quoteCount = 0;
      char currentQuoteChar = ' ';
      StringBuilder currentValue = new StringBuilder();

      int index = 0;
      while (index < inLine.length())
      {
         int theChar = inLine.charAt(index);

         if (inQuotedValue)
         {
            if (theChar == currentQuoteChar)
            {
               quoteCount++;

               if (2 == quoteCount)
               {
                  // Skip
                  quoteCount = 0;
               }
               else if ((index == inLine.length() - 1 || inLine.charAt(index + 1) != currentQuoteChar)
                     && (0 == currentValue.length() || currentValue.charAt(currentValue.length() - 1) != '\\'))
               {
                  inQuotedValue = false;
                  String unescapedValue = StringUtil.replaceAll(currentValue, "\\" + currentQuoteChar, currentQuoteChar + "");
                  currentValue.setLength(0);
                  currentValue.append(unescapedValue);
               }
               else
               {
                  currentValue.append((char) theChar);
               }
            }
            else
            {
               currentValue.append((char) theChar);
               quoteCount = 0;
            }
         }
         else if (Character.isWhitespace(theChar))
         {
            if (currentValue.length() > 0)
            {
               fields.add(currentValue.toString().trim());
               currentValue.setLength(0);
            }
         }
         else if ((theChar == '\''
               || theChar == '\"')
               && 0 == currentValue.length())
         {  // Start of a quoted value
            inQuotedValue = true;
            quoteCount = 0;
            currentQuoteChar = (char) theChar;
         }
         else
         {
            currentValue.append((char) theChar);
         }

         index++;
      }

      fields.add(currentValue.length() > 0 ? currentValue.toString().trim() : null);

      return fields.toArray(new String[] {});
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy