word edit: present login form on unauthorised request
authorMischa POSLAWSKY <perl@shiar.org>
Sat, 13 Jun 2020 14:39:46 +0000 (16:39 +0200)
committerMischa POSLAWSKY <perl@shiar.org>
Tue, 20 Oct 2020 20:49:11 +0000 (22:49 +0200)
User-friendly creation of access cookies.

writer.plp

index ce52761ef490526c6d510f2b931441d8652e24a7..4df6f8cd71f6ffe4d7d59c7e751209c58a09f521 100644 (file)
@@ -116,11 +116,53 @@ my $db = eval {
 $db->abstract->{array_datatypes}++;
 
 my $user = eval {
+       if (defined $post{username}) {
+               $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
+       }
+       elsif (exists $fields{logout}) {
+               require CGI::Cookie;
+               if (AddCookie(CGI::Cookie->new(
+                       -name    => 'login',
+                       -value   => '',
+                       -path    => '/writer',
+                       -expires => 'now',
+               )->as_string)) {
+                       delete $cookie{login};
+                       die "Logged out as requested\n";
+               }
+               Alert("Failed to log out", "Login cookie could not be removed.");
+       }
+
        my $cookiedata = $cookie{login} or return;
        my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
        my %rowmatch = (username => $name, pass => $key);
-       $db->select(login => '*', \%rowmatch)->hash;
-} or Abort('Login required', 403);
+       my $found = $db->select(login => '*', \%rowmatch)->hash
+               or die "Invalid user or password\n";
+
+       eval {
+               require CGI::Cookie;
+               my $httpcookie = CGI::Cookie->new(
+                       -name    => 'login',
+                       -value   => join(':', @{$found}{qw( username pass )}),
+                       -path    => '/writer',
+               ) or die "prepared object is empty\n";
+               AddCookie($httpcookie->as_string);
+       } or Abort(["Unable to create login cookie", $@], 403);
+
+       return $found;
+} or do {
+       say '<h1>Login to edit words</h1>';
+       Alert('Access denied', $@) if $@;
+       say '<form action="?" method="post" class="inline"><ul>';
+       my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
+       say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
+               username => {-label => 'User name'},
+               pass     => {-label => 'Password', type => 'password'},
+       );
+       say '<li><input type="submit" value="Login" /></li>';
+       say '</ul></form>';
+       exit;
+};
 
 my %lang = (
        nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
@@ -160,7 +202,7 @@ if ($find) {
 if (exists $get{copy}) {
        $row = {%{$row}{ qw(prio lang cat) }};
 }
-elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
+elsif (defined $post{form}) {{
        sub parseinput {
                return if not length $_[0];
                require Encode;