Apache-Htpasswd

 view release on metacpan or  search on metacpan

Htpasswd.pm  view on Meta::CPAN

    my $self = shift;
    my $Id   = shift;
    my $pass = shift;
    my $MD5Magic = '$apr1$';
    my $SHA1Magic = '{SHA}';

    my $cryptPass = $self->fetchPass($Id);
    if ( !$cryptPass ) { return undef; }

    if (index($cryptPass, $MD5Magic) == 0) {
        # This is an MD5 password
        require Crypt::PasswdMD5;
        my $salt = $cryptPass;
        $salt =~ s/^\Q$MD5Magic//;      # Take care of the magic string if present
        $salt =~ s/^(.*)\$/$1/;         # Salt can have up to 8 chars...
        $salt = substr( $salt, 0, 8 );  # That means no more than 8 chars too.
        return 1 if Crypt::PasswdMD5::apache_md5_crypt( $pass, $salt ) eq $cryptPass;
    }
    elsif (index($cryptPass, $SHA1Magic) == 0) {
        # This is an SHA1 password
        require Digest::SHA;
        require MIME::Base64;
        return 1 if '{SHA}'.MIME::Base64::encode_base64( Digest::SHA::sha1( $pass ), '' ) eq $cryptPass;
    }

    # See if it is encrypted using crypt
    return 1 if crypt($pass, $cryptPass) eq $cryptPass;

    # See if it is a plain, unencrypted password
    return 1 if $self->{USEPLAIN} && $pass eq $cryptPass;
    
    $self->{'ERROR'} =
        __PACKAGE__ . "::htCheckPassword - Passwords do not match.";
    carp $self->error() if caller eq $self;
    return 0;
}

#-----------------------------------------------------------#

sub htpasswd {
    my $self    = shift;
    my $Id      = shift;
    my $newPass = shift;
    my $oldPass = shift;
    my $noOld = 0;

    if ( $self->{READONLY} ) {
        $self->{'ERROR'} =
          __PACKAGE__ . "::htpasswd - Can't change passwords in ReadOnly mode";
        carp $self->error();
        return undef;
    }

    if ( !defined($oldPass) ) { 
			$noOld = 1; 
		}

    if ( defined($oldPass) && ref $oldPass eq 'HASH' ) {
        if ($oldPass->{'overwrite'}) {
            $newPass = $Id unless $newPass;
            my $newEncrypted = $self->CryptPasswd($newPass);
            return $self->writePassword( $Id, $newEncrypted );
        }
    }

    # New Entry
    if ($noOld) {
        my $passwdFile = $self->{'PASSWD'};

        # Encrypt new password string

        my $passwordCrypted = $self->CryptPasswd($newPass);

        $self->_open();

        if ( $self->fetchPass($Id) ) {

            # User already has a password in the file.
            $self->{'ERROR'} =
              __PACKAGE__ . "::htpasswd - $Id already exists in $passwdFile";
            carp $self->error();
            $self->_close();
            return undef;
        }
        else {

            # If we can add the user.
            seek( FH, 0, SEEK_END );
            print FH "$Id\:$passwordCrypted\n";

            $self->_close();
            return 1;
        }

        $self->_close();

    }
    else {
        $self->_open();

Htpasswd.pm  view on Meta::CPAN

}

#-----------------------------------------------------------#

1;

__END__

=head1 NAME

Apache::Htpasswd - Manage Unix crypt-style password file.

=head1 SYNOPSIS

    use Apache::Htpasswd;

    $foo = new Apache::Htpasswd("path-to-file");

    $foo = new Apache::Htpasswd({passwdFile => "path-to-file",
				 ReadOnly   => 1}
				);

    # Add an entry
    $foo->htpasswd("zog", "password");

    # Change a password
    $foo->htpasswd("zog", "new-password", "old-password");

    # Change a password without checking against old password

    $foo->htpasswd("zog", "new-password", {'overwrite' => 1});

    # Check that a password is correct
    $foo->htCheckPassword("zog", "password");

    # Fetch an encrypted password
    $foo->fetchPass("foo");

    # Delete entry
    $foo->htDelete("foo");

    # If something fails, check error
    $foo->error;

    # Write in the extra info field
    $foo->writeInfo("login", "info");

    # Get extra info field for a user
    $foo->fetchInfo("login");

=head1 DESCRIPTION

This module comes with a set of methods to use with htaccess password
files. These files (and htaccess) are used to do Basic Authentication
on a web server.

The passwords file is a flat-file with login name and their associated
crypted password. You can use this for non-Apache files if you wish, but
it was written specifically for .htaccess style files.

=head2 FUNCTIONS

=over 4

=item Apache::Htpasswd->new(...);

As of version 1.5.4 named params have been added, and it is suggested that
you use them from here on out.

	Apache::Htpasswd->new("path-to-file");

"path-to-file" should be the path and name of the file containing
the login/password information.

	Apache::Htpasswd->new({passwdFile => "path-to-file",
			       ReadOnly   => 1,
			       UseMD5     => 1,
			     });

This is the prefered way to instantiate an object. The 'ReadOnly' param
is optional, and will open the file in read-only mode if used. The 'UseMD5'
is also optional: it will force MD5 password under Unix.

If you want to support plain un-encrypted passwords, then you need to set
the UsePlain option (this is NOT recommended, but might be necesary in some
situations)

=item error;

If a method returns an error, or a method fails, the error can
be retrieved by calling error()


=item htCheckPassword("login", "password");

Finds if the password is valid for the given login.

Returns 1 if passes.
Returns 0 if fails.


=item htpasswd("login", "password");

This will add a new user to the password file.
Returns 1 if succeeds.
Returns undef on failure.


=item htDelete("login")

Delete users entry in password file.

Returns 1 on success
Returns undef on failure.


=item htpasswd("login", "new-password", "old-password");

If the I<old-password> matches the I<login's> password, then
it will replace it with I<new-password>. If the I<old-password>
is not correct, will return 0.


=item htpasswd("login", "new-password", {'overwrite' => 1});

Will replace the password for the login. This will force the password
to be changed. It does no verification of old-passwords.

Returns 1 if succeeds
Returns undef if fails

=item fetchPass("login");

Returns I<encrypted> password if succeeds.
Returns 0 if login is invalid.
Returns undef otherwise.

=item fetchInfo("login");

Returns additional information if succeeds.
Returns 0 if login is invalid.
Returns undef otherwise.

=item fetchUsers();

Htpasswd.pm  view on Meta::CPAN

The following will return the count:
my $user_count = $Htpasswd->fetchUsers();

=item writeInfo("login", "info");

Will replace the additional information for the login.
Returns 0 if login is invalid.
Returns undef otherwise.


=item CryptPasswd("password", "salt");

Will return an encrypted password using 'crypt'. If I<salt> is
ommitted, a salt will be created.

=back

=head1 INSTALLATION

You install Apache::Htpasswd, as you would install any perl module library,
by running these commands:

   perl Makefile.PL
   make
   make test
   make install
   make clean

If you are going to use MD5 encrypted passwords, you need to install L<Crypt::PasswdMD5>.

If you need to support SHA1 encrypted passwords, you need to install L<Digest::SHA> and L<MIME::Base64>.

=head1 DOCUMENTATION

POD style documentation is included in the module.
These are normally converted to manual pages and installed as part
of the "make install" process.  You should also be able to use
the 'perldoc' utility to extract and read documentation from the
module files directly.


Htpasswd.pm  view on Meta::CPAN

Visit <URL:http://www.perl.com/CPAN/> to find a CPAN
site near you.

=head1 CHANGES

Revision 1.9.0  SHA dependency changes

Revision 1.8.0  Added proper PREREQ_PM

Revision 1.7.0  Handle SHA1 and plaintext. Also change the interface
for allowing change of password without first checking old password. IF
YOU DON'T READ THE DOCS AND SEE I DID THIS DON'T EMAIL ME!

Revision 1.6.0  Handle Blowfish hashes when that's the mechanism crypt() uses.

Revision 1.5.9  MD5 for *nix with new UseMD5 arg for new()

Revision 1.5.8  Bugfix to htpasswd().

Revision 1.5.7  MD5 for Windows, and other minor changes.

README  view on Meta::CPAN

NAME
    Apache::Htpasswd - Manage Unix crypt-style password file.

SYNOPSIS
        use Apache::Htpasswd;

        $foo = new Apache::Htpasswd("path-to-file");

        # Add an entry    
        $foo->htpasswd("zog", "password");

        # Change a password    
        $foo->htpasswd("zog", "new-password", "old-password");
    
        # Change a password without checking against old password
        # The 1 signals that the change is being forced.
    
        $foo->htpasswd("zog", "new-password", 1);
        
        # Check that a password is correct
        $pwdFile->htCheckPassword("zog", "password");

        # Fetch an encrypted password 
        $foo->fetchPass("foo");
    
        # Delete entry
        $foo->htDelete("foo");

        # If something fails, check error
        $foo->error;

        # Write in the extra info field
        $foo->writeInfo("login", "info");

        # Get extra info field for a user
        $foo->fetchInfo("login");

DESCRIPTION
    This module comes with a set of methods to use with htaccess password
    files. These files (and htaccess) are used to do Basic Authentication on
    a web server.

    The passwords file is a flat-file with login name and their associated
    crypted password. You can use this for non-Apache files if you wish, but
    it was written specifically for .htaccess style files.

  FUNCTIONS

    htaccess->new("path-to-file");
        "path-to-file" should be the path and name of the file containing
        the login/password information.

    error;
        If a method returns an error, or a method fails, the error can be
        retrived by calling error()

    htCheckPassword("login", "password");
        Finds if the password is valid for the given login.

        Returns 1 if passes. Returns 0 if fails.

    htpasswd("login", "password");
        This will add a new user to the password file. Returns 1 if
        succeeds. Returns undef on failure.

    htDelete("login")
        Delete users entry in password file.

        Returns 1 on success Returns undef on failure.

    htpasswd("login", "new-password", "old-password");
        If the *old-password* matches the *login's* password, then it will
        replace it with *new-password*. If the *old-password* is not
        correct, will return 0.

    htpasswd("login", "new-password", 1);
        Will replace the password for the login. This will force the
        password to be changed. It does no verification of old-passwords.

        Returns 1 if succeeds Returns undef if fails

    fetchPass("login");
        Returns *encrypted* password if succeeds. Returns 0 if login is
        invalid. Returns undef otherwise.

    fetchInfo("login");
        Returns additional information if succeeds. Returns 0 if login is
        invalid. Returns undef otherwise.

    writeInfo("login", "info");
        Will replace the additional information for the login. Returns 0 if
        login is invalid. Returns undef otherwise.

    CryptPasswd("password", "salt");
        Will return an encrypted password using 'crypt'. If *salt* is
        ommitted, a salt will be generated. 

INSTALLATION
    You install Apache::Htpasswd, as you would install any perl module
    library, by running these commands:

       perl Makefile.PL
       make
       make test
       make install

README  view on Meta::CPAN

    The latest version of Apache::Htpasswd should always be available from:

        $CPAN/modules/by-authors/id/K/KM/KMELTZ/

    Visit <URL:http://www.perl.com/CPAN/> to find a CPAN site near you.

CHANGES

    Revision 1.5.7  2004/08/23 09:05:12 Made generated salt more
		random. Tidied up the code a bit. Also added use of Crypt::PasswdMD5
		for Apache on MSWin for use of (modified) MD5 passwords on that
		platform.
	
    Revision 1.5.5  2002/08/14 11:27:05 Newline issue fixed for certain conditions.

    Revision 1.5.4  2002/07/26 12:17:43 kevin doc fixes, new fetchUsers method,
    new ReadOnly option, named params for new(), various others

    Revision 1.5.3  2001/05/02 08:21:18 kevin Minor bugfix

    Revision 1.5.2  2001/04/03 09:14:57 kevin Really fixed newline problem :)

test.pl  view on Meta::CPAN

	print "@_\n" if (not $ok and $ENV{TEST_VERBOSE});
	$TEST_NUM++;
}

sub report_skip {
        my $why = shift;
        print "not ok $TEST_NUM # SKIP $why\n";
	$TEST_NUM++;
}

# Create a test password file
my $File = "testpasswords.test";
open(TEST,">$File") || die "Can't run tests because I can't create $File [$!]";
print TEST "kevin:kjDqW.pgNIz3Ufoo:suvPq./X7Q8nk\n";
close TEST;



{
	
	# 2: Get file
	&report_result($pwdFile = new Apache::Htpasswd ($File), $! );

test.pl  view on Meta::CPAN

print TEST "cryptuser:Iao36C/TVmCRc\n";
print TEST "MD5user:\$apr1\$Yy.pS/..\$4bwpMUiVq/95BDr4kZ2lK.\n";
print TEST "SHA1user:{SHA}QL0AFWMIX8NRZTKeof9cXsvbvu8=\n";
print TEST "plainuser:123\n";
close TEST;

{
	# 16: Create in read-only mode with UsePlain
        &report_result($pwdFile = new Apache::Htpasswd({passwdFile => $File, ReadOnly => 1, UsePlain => 1}), $! );

	# 17: check whether crypt passwords work
	&report_result($pwdFile->htCheckPassword("cryptuser","123"),$!);

	# 18: check whether MD5 passwords work
        eval { require Crypt::PasswdMD5 };
        if ($@) {
            &report_skip('Crypt::PasswdMD5 required for this test');
        } else {
            &report_result($pwdFile->htCheckPassword("MD5user","123"),$!);
        }

	# 19: check whether SHA1 passwords work
        eval { require Digest::SHA; require MIME::Base64 };
        if ($@) {
            &report_skip('Digest::SHA and MIME::Base64 required for this test');
        } else {
            &report_result($pwdFile->htCheckPassword("SHA1user","123"),$!);
        }

	# 20: check whether plain passwords work
	&report_result($pwdFile->htCheckPassword("plainuser","123"),$!);

}

print "Test complete.\n";



( run in 0.454 second using v1.01-cache-2.11-cpan-49f99fa48dc )