cyberman/lib/cyberman/Helper.pm

64 lines
1.0 KiB
Perl
Raw Normal View History

2017-07-17 00:12:38 +02:00
package cyberman::Helper;
use base qw(Exporter);
use Dancer2 appname => "cyberman";
2017-07-17 09:55:50 +02:00
use Math::Random::Secure qw(irand);
2017-07-17 15:25:45 +02:00
use Digest::Bcrypt;
2017-07-17 09:55:50 +02:00
2017-07-17 00:12:38 +02:00
use Exporter qw(import);
2017-07-17 15:25:45 +02:00
our @EXPORT = qw(auth_test randstring hash_password);
2017-07-17 09:55:50 +02:00
# Helper functions
2017-07-17 00:12:38 +02:00
sub auth_test {
2017-07-17 01:35:13 +02:00
my $id = undef;
if (@_) {
$id = shift;
}
2017-07-17 00:12:38 +02:00
if (!vars->{"auth"}) {
return template 'redir' => {
"redir" => "/index",
};
2017-07-17 01:35:13 +02:00
} elsif ($id && vars->{"auth"} != $id) {
return template 'redir' => {
"redir" => "/index",
};
2017-07-17 00:12:38 +02:00
} else {
return 0; # nothing to be returned, route can continue
}
}
2017-07-17 09:55:50 +02:00
sub randstring {
my $len = shift;
my @chars = (0..9, "a".."z", "A".."Z");
my $ret;
for (1..$len) {
$ret .= $chars[irand(scalar(@chars))];
}
return $ret;
}
2017-07-17 15:25:45 +02:00
sub hash_password {
my $plaintext = shift;
my $salt;
if (scalar(@_) > 0) {
$salt = shift;
} else {
$salt = randstring(16);
}
my $b = new Digest::Bcrypt;
$b->cost(8);
$b->salt($salt);
$b->add($plaintext);
return ($b->bcrypt_b64digest, $salt);
}
2017-07-17 00:12:38 +02:00
1;