Serving Files with Dancer::Plugin::DirectoryView and Dancer::Plugin::Auth::Htpasswd
A while ago I was converting a simple PHP website to Dancer, and moving
it from being deployed on Apache to Starman. There wasn't a lot of code,
so rewriting went quickly -- but, the site used a few specific features
of Apache, namely directory indexes (courtesy of
mod_autoindex)
to allow user access to directories/files on the server, and htpasswd
files
to password-protect some of those directories.
I could just deploy the new Dancer website on Apache and keep using those goodies, but I thought that it would be nice if Dancer itself provided similar features. So, I created two plugins that do just that: Dancer::Plugin::DirectoryView and Dancer::Plugin::Auth::Htpasswd. Let me now show you how to use them.
Directory Indexes
Let's say we have a files
directory under public
, and we'd like to
allow users to browse it and download files. Enabling directory access
is as simple as including the plugin in our Dancer application:
package MyWebApp; ... use Dancer::Plugin::DirectoryView;
And updating the configuration file (config.yml
) to tell the plugin which
directory should be made available, and at which URL:
plugins: DirectoryView: url: /pub root_dir: files
That's it -- now, if we launch our app and point the browser at the
/pub
URL, we'll see the contents of the directory:
Protecting Directories with Htpasswd Files
As you might have noticed on the screenshot, there's a secret
directory under files
. It contains some super secret data that should
only be available to authorized users, so now we're going to protect it
using a htpasswd
file.
First, let's create the htpasswd
file and an user, named "alice":
$ htpasswd -c htpasswd alice
Once it is created, we need to put the htpasswd
file in a safe location
outside of the public directory, so let's create a new directory
passwd
and store the file in there.
(If you're migrating from Apache and already have the htpasswd
file, you
just need to copy it to your Dancer application.)
In our Dancer application, we include the Auth::Htpasswd plugin:
package MyWebApp; ... use Dancer::Plugin::Auth::Htpasswd;
Now, we need to update our configuration file and add settings for the
plugin. We'll tell it to protect the /pub/secret
path, and to use the
htpasswd
file we just created:
plugins: "Auth::Htpasswd": paths: "/pub/secret": realm: "Secret Files" passwd_file: passwd/htpasswd
The realm
parameter lets us set the text that will be shown to the
user in the login window displayed by the browser.
Let's see if our protection works. We restart the application and try to
access the /pub/secret/
URL:
Great, our confidential files are safe. Only when we log in as "Alice", we'll be able to access them:
AUTHOR
Michal Wojciechowski, <odyniec@odyniec.net>