+sub import {
+ hook(type => "getsetup", id => "passwordauth", "call" => \&getsetup);
+ hook(type => "formbuilder_setup", id => "passwordauth", call => \&formbuilder_setup);
+ hook(type => "formbuilder", id => "passwordauth", call => \&formbuilder);
+ hook(type => "sessioncgi", id => "passwordauth", call => \&sessioncgi);
+ hook(type => "auth", id => "passwordauth", call => \&auth);
+}
+
+sub getsetup () {
+ return
+ plugin => {
+ safe => 1,
+ rebuild => 0,
+ },
+ account_creation_password => {
+ type => "string",
+ example => "s3cr1t",
+ description => "a password that must be entered when signing up for an account",
+ safe => 1,
+ rebuild => 0,
+ },
+ password_cost => {
+ type => "integer",
+ example => 8,
+ description => "cost of generating a password using Authen::Passphrase::BlowfishCrypt",
+ safe => 1,
+ rebuild => 0,
+ },
+}
+
+# Checks if a string matches a user's password, and returns true or false.
+sub checkpassword ($$;$) {
+ my $user=shift;
+ my $password=shift;
+ my $field=shift || "password";
+
+ # It's very important that the user not be allowed to log in with
+ # an empty password!
+ if (! length $password) {
+ return 0;
+ }
+
+ my $userinfo=IkiWiki::userinfo_retrieve();
+ if (! length $user || ! defined $userinfo ||
+ ! exists $userinfo->{$user} || ! ref $userinfo->{$user}) {
+ return 0;
+ }
+
+ my $ret=0;
+ if (exists $userinfo->{$user}->{"crypt".$field}) {
+ eval q{use Authen::Passphrase};
+ error $@ if $@;
+ my $p = Authen::Passphrase->from_crypt($userinfo->{$user}->{"crypt".$field});
+ $ret=$p->match($password);
+ }
+ elsif (exists $userinfo->{$user}->{$field}) {
+ $ret=$password eq $userinfo->{$user}->{$field};
+ }
+
+ if ($ret &&
+ (exists $userinfo->{$user}->{resettoken} ||
+ exists $userinfo->{$user}->{cryptresettoken})) {
+ # Clear reset token since the user has successfully logged in.
+ delete $userinfo->{$user}->{resettoken};
+ delete $userinfo->{$user}->{cryptresettoken};
+ IkiWiki::userinfo_store($userinfo);
+ }
+
+ return $ret;
+}
+
+sub setpassword ($$;$) {
+ my $user=shift;
+ my $password=shift;
+ my $field=shift || "password";
+
+ eval q{use Authen::Passphrase::BlowfishCrypt};
+ if (! $@) {
+ my $p = Authen::Passphrase::BlowfishCrypt->new(
+ cost => $config{password_cost} || 8,
+ salt_random => 1,
+ passphrase => $password,
+ );
+ IkiWiki::userinfo_set($user, "crypt$field", $p->as_crypt);
+ IkiWiki::userinfo_set($user, $field, "");
+ }
+ else {
+ IkiWiki::userinfo_set($user, $field, $password);
+ }
+}