+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);
+ 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;
+};
+