tokuhirom's Blog

How do I implement basic & simple authentication form with Plack::Middleware::Auth::Form

There is two issues for me.

But it works.

#!/usr/bin/env
use strict;
use warnings;
use 5.010001;
use Plack::Builder;
use Plack::Request;

sub dispatch_secret {
    return [
        200,
        [],
        [<<'...'],
<!doctype html>
<html>
<head>
<title>This is a secret web page</title>
</head>
<body>
    <div style="font-size: 500%; color: red">This is a secret web page</div>
    <form method="post" action="/logout"><input type="submit" value="logout" /></a>
</body>
</html>
...
    ]
}

builder {
    enable 'Session';
    enable 'Auth::Form',
        authenticator => sub {
            $_[0] eq 'dankogai' && $_[1] eq 'kogaidan';
        };

    sub {
        my $req = Plack::Request->new(shift);

        if ($req->session->{user_id}) {
            given ($req->path_info) {
            when ('/') {
                return dispatch_secret();
            }
            default {
                return [404, [], []];
            }
            }
        } else {
           my $res = Plack::Response->new();
           $res->redirect('/login');
           return $res->finalize;
        }
    }
};