Authentication and authorization is something every framework must manage. Because they're boring and frameworks exist to manage boring things.
When a user can be considered authenticated? The easiest way to check it it searching is its session for a user key with some interesting value. Is this secure? Enough, because we're talking about server-side session, something a user can't touch, we have to trust it well... until a new security flaw is found in one of the layer of our system.
The "auth" thing is a pattern well known in the web world and you can find many solutions for it, looking for "Dancer::Plugin::Auth" you'll find a lot of stuff. Unfortunately Dancer2 is still a young project so the only tool we have is the Dancer2::Plugin::Auth::Tiny from Golden.
We'll not use it. Ok, the plugin is a very good piece of software but its main purpose is define which routes need login to redirect on login page the not authenticated users. I think that this is made useless by the Dancer2 App scope.
In a situation where routes for logged users and routes for not-logged users are mixed up probably D2::P::A::Tiny is the right solution, but here we have an app where every route needs auth so we'll solve our problem just with a before hook defined in the app itself.
But we have to start from: how to open the doors to a logged user? Login went well, user and password were right, what the server will do? As I said before, it will write in the user session the username.
session 'user' => $the_username;
This is what our hook will check:
Yes, just this. The most common mistake is forgetting that the login route has to skip the check because is the only page allowed for not logged users. In every other case the hook does NOTHING for logged users and redirect to the login page the guests.
I made it more longer than what is needed because I like to talk and write and because sometimes I think that also obvious things need some explanation, somewhere. Conclusion is that using the snippets from the dump code festival you have the start situation for an admin tool you can use for every purpose. Probably, working on it, you'll find a lot o things to improve it or make it smarter. But this is just the first step, the dump step, so it's right as it is.