PM/Password.pm

114 lines
2.2 KiB
Perl
Raw Normal View History

2014-04-27 03:46:32 +04:00
package Password;
use strict;
use warnings;
use utf8;
2014-04-27 23:11:52 +04:00
use Database;
2014-04-28 16:14:23 +04:00
use GPG;
2014-04-27 03:46:32 +04:00
2014-05-06 00:40:26 +04:00
# Debug
use Data::Dumper;
2014-04-27 03:46:32 +04:00
sub new {
2014-04-28 12:17:17 +04:00
my $class = shift;
2014-04-27 03:46:32 +04:00
2014-04-28 16:14:23 +04:00
my $db = Database->new();
my $gpg = GPG->new( $ENV{HOME} );
2014-04-28 12:04:17 +04:00
2014-04-28 12:17:17 +04:00
my $self = {
2014-04-29 15:45:31 +04:00
_db => $db,
_gpg => $gpg,
2014-04-27 03:46:32 +04:00
};
2014-04-28 12:17:17 +04:00
2014-04-27 03:46:32 +04:00
bless $self, $class;
return $self;
}
2014-04-28 16:14:23 +04:00
sub show {
my ( $self, $name ) = @_;
my $db_class = $self->{_db};
my $gpg = $self->{_gpg};
# Decrypt db
my $dec_db_file = $gpg->decrypt_db();
# Query
my $query_string
= "select name, resource, password from passwords where name='$name'";
my $mdo_q = {
file => $dec_db_file,
query => $query_string,
name => $name,
type => 'select',
};
my $q_hash = $db_class->mdo($mdo_q);
# Remove unencrypted file
2014-04-28 16:43:00 +04:00
my @rm_cmd = ( "rm", "-f", "$dec_db_file" );
2014-04-28 16:14:23 +04:00
system(@rm_cmd) == 0 or die "Cannot remove unencrypted database! $!\n";
return $q_hash;
}
2014-04-29 11:37:41 +04:00
# Decrypt base and store new password
sub save {
my ( $self, $store ) = @_;
my $db_class = $self->{_db};
my $gpg = $self->{_gpg};
my $name = $store->{name};
my $resource = $store->{resource};
my $password = $store->{password};
my $generate = $store->{gen};
if ( $generate == 1 ) {
$password = Password->generate();
}
# Decrypt database
my $dec_db_file = $gpg->decrypt_db();
my $q
2014-05-06 00:40:26 +04:00
= "insert into passwords(name, resource, password)
values('$name', '$resource', '$password')";
2014-04-29 11:37:41 +04:00
my $mdo_q = {
file => $dec_db_file,
name => $name,
2014-04-29 15:45:31 +04:00
query => $q,
2014-04-29 11:37:41 +04:00
type => 'do',
};
$db_class->mdo($mdo_q);
$gpg->encrypt_db($dec_db_file);
return 0;
}
# Generate password
sub generate {
my @chars = ( "A" .. "Z", "a" .. "z", 0 .. 9 );
my $string;
$string .= $chars[ rand @chars ] for 1 .. 16;
return $string;
}
2014-04-28 12:04:17 +04:00
# Check configuration. If it doesn't exist create it.
sub check_config {
2014-04-28 12:17:17 +04:00
my ($self) = @_;
2014-04-28 16:14:23 +04:00
if ( -e $ENV{HOME} . "/.PM/db.sqlite" ) {
2014-04-28 12:17:17 +04:00
return 0;
}
else {
my $db = $self->{_db};
$db->create_base();
2014-04-29 15:45:31 +04:00
2014-05-06 00:40:26 +04:00
print "Done!\n";
2014-04-29 15:45:31 +04:00
return 0;
2014-04-28 12:17:17 +04:00
}
2014-04-29 15:45:31 +04:00
return 1;
2014-04-28 12:04:17 +04:00
}
2014-04-28 12:17:17 +04:00
1;