Dancer-Plugin-Auth-Extensible-1.00/ 0000755 0001750 0001750 00000000000 12762006471 016366 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/META.yml 0000644 0001750 0001750 00000001436 12762006471 017643 0 ustar davidp davidp ---
abstract: 'extensible authentication framework for Dancer apps'
author:
- 'David Precious '
build_requires:
ExtUtils::MakeMaker: '0'
configure_requires:
ExtUtils::MakeMaker: '0'
dynamic_config: 1
generated_by: 'ExtUtils::MakeMaker version 7.18, CPAN::Meta::Converter version 2.143240'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: '1.4'
name: Dancer-Plugin-Auth-Extensible
no_index:
directory:
- t
- inc
recommends:
Authen::Simple::PAM: '0'
Dancer::Plugin::Database: '0'
Unix::Passwd::File: '0'
requires:
Crypt::SaltedHash: '0'
Dancer: '1.3118'
Test::More: '0'
YAML: '0'
perl: '5.006001'
resources:
homepage: https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible/
version: '1.00'
Dancer-Plugin-Auth-Extensible-1.00/Changes 0000644 0001750 0001750 00000005244 12762006415 017664 0 ustar davidp davidp Revision history for Dancer-Plugin-Auth-Extensible
1.00 2016-08-26
[ ENHANCEMENTS ]
- Cache logged in user and roles (GH-51)
0.40 2015-04-30
[ ENHANCEMENTS ]
- Login handlers go straight to homepage if user was already logged in
(thanks to @colinmkeith, GH-32)
- Kwalitee improvements from Michael Gray (mjg17) as part of the awesome
pull request challenge (GH-43, GH-44, GH-45, GH-46)
[ SECURITY ]
- Ensure the username and password we got were straight scalars, to
avoid potential for "JSON SQL injection" if they came from a
deserialised JSON POST body, and contained a hashref that, if fed to
e.g. SQL::Abstract or such, would cause a different query to what we'd
expect.
0.30 2013-11-14
[ ENHANCEMENTS ]
- Typo fix and whatis entry courtesy of Debian team
- POD fix (Matt West)
0.20 2013-01-30
[ ENHANCEMENTS ]
- Use return_url to redirect back to requested page after logging in
(GH #14, thanks to @dagolden)
- require_role can now take a regex to match (GH #16, thanks to
@chenryn)
[ BUG FIXES ]
- authenticate_user is now exported (thanks to melmothX on IRC)
0.10 2012-12-19
[ ENHANCEMENTS ]
- WARNING: backwards incompatible change!
The original approach using subroutine attributes was pretty, but not
always reliable (particularly with regards to thread safety, or
running under the debugger or Devel::Cover etc).
Since this module is still in it's early life and not widely used,
I've refactored entirely, to use new requires_login / requires_role
etc keywords, which wrap the provided coderef in a coderef which
checks if the user is logged in / has the required role(s), before
running the route handler provided.
- Configurable /login, /logout URLs - Rene (hertell)
0.04 2012-12-15
[ BUG FIXES ]
- Throw an error properly if not configured correctly - safer to refuse
for anything to be served than to potentially serve stuff the user
expected to be protected if their config is wrong.
0.03 2012-12-07
[ BUG FIXES ]
- import Dancer DSL keywords, so call to debug() if user record is not
found doesn't cause horrific fiery explosions (reported by rwb)
0.02 2012-12-07
[ BUG FIXES ]
- Various bug fixes and improvements, including POD fix from cebjyre,
fixing broken register_plugin call by racke
0.01 Date/time
First version, released on an unsuspecting world.
Dancer-Plugin-Auth-Extensible-1.00/bin/ 0000755 0001750 0001750 00000000000 12762006471 017136 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/bin/generate-crypted-password 0000755 0001750 0001750 00000000410 12412252770 024156 0 ustar davidp davidp #!/usr/bin/env perl
use strict;
use Crypt::SaltedHash;
print "Enter plain-text password ?> ";
chomp(my $plain_text = <>);
my $csh = Crypt::SaltedHash->new(algorithm => 'SHA-1');
$csh->add($plain_text);
my $salted = $csh->generate;
print "Result: $salted\n";
Dancer-Plugin-Auth-Extensible-1.00/ignore.txt 0000644 0001750 0001750 00000000213 12021514014 020367 0 ustar davidp davidp blib*
Makefile
Makefile.old
Build
Build.bat
_build*
pm_to_blib*
*.tar.gz
.lwpcookies
cover_db
pod2htm*.tmp
Dancer-Plugin-Auth-Extensible-*
Dancer-Plugin-Auth-Extensible-1.00/META.json 0000644 0001750 0001750 00000002452 12762006471 020012 0 ustar davidp davidp {
"abstract" : "extensible authentication framework for Dancer apps",
"author" : [
"David Precious "
],
"dynamic_config" : 1,
"generated_by" : "ExtUtils::MakeMaker version 7.18, CPAN::Meta::Converter version 2.143240",
"license" : [
"perl_5"
],
"meta-spec" : {
"url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",
"version" : "2"
},
"name" : "Dancer-Plugin-Auth-Extensible",
"no_index" : {
"directory" : [
"t",
"inc"
]
},
"prereqs" : {
"build" : {
"requires" : {
"ExtUtils::MakeMaker" : "0"
}
},
"configure" : {
"requires" : {
"ExtUtils::MakeMaker" : "0"
}
},
"runtime" : {
"recommends" : {
"Authen::Simple::PAM" : "0",
"Dancer::Plugin::Database" : "0",
"Unix::Passwd::File" : "0"
},
"requires" : {
"Crypt::SaltedHash" : "0",
"Dancer" : "1.3118",
"Test::More" : "0",
"YAML" : "0",
"perl" : "5.006001"
}
}
},
"release_status" : "stable",
"resources" : {
"homepage" : "https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible/"
},
"version" : "1.00"
}
Dancer-Plugin-Auth-Extensible-1.00/README 0000644 0001750 0001750 00000027515 12762006441 017255 0 ustar davidp davidp NAME
Dancer::Plugin::Auth::Extensible - extensible authentication framework
for Dancer apps
DESCRIPTION
A user authentication and authorisation framework plugin for Dancer
apps.
Makes it easy to require a user to be logged in to access certain
routes, provides role-based access control, and supports various
authentication methods/sources (config file, database, Unix system
users, etc).
Designed to support multiple authentication realms and to be as
extensible as possible, and to make secure password handling easy. The
base class for auth providers makes handling `RFC2307'-style hashed
passwords really simple, so you have no excuse for storing plain-text
passwords. A simple script to generate RFC2307-style hashed passwords is
included, or you can use Crypt::SaltedHash yourself to do so, or use the
`slappasswd' utility if you have it installed.
SYNOPSIS
Configure the plugin to use the authentication provider class you wish
to use:
plugins:
Auth::Extensible:
realms:
users:
provider: Example
....
The configuration you provide will depend on the authentication provider
module in use. For a simple example, see
Dancer::Plugin::Auth::Extensible::Provider::Config.
Define that a user must be logged in and have the proper permissions to
access a route:
get '/secret' => require_role Confidant => sub { tell_secrets(); };
Define that a user must be logged in to access a route - and find out
who is logged in with the `logged_in_user' keyword:
get '/users' => require_login sub {
my $user = logged_in_user;
return "Hi there, $user->{username}";
};
AUTHENTICATION PROVIDERS
For flexibility, this authentication framework uses simple
authentication provider classes, which implement a simple interface and
do whatever is required to authenticate a user against the chosen source
of authentication.
For an example of how simple provider classes are, so you can build your
own if required or just try out this authentication framework plugin
easily, see Dancer::Plugin::Auth::Extensible::Provider::Example.
This framework supplies the following providers out-of-the-box:
Dancer::Plugin::Auth::Extensible::Provider::Unix
Authenticates users using system accounts on Linux/Unix type boxes
Dancer::Plugin::Auth::Extensible::Provider::Database
Authenticates users stored in a database table
Dancer::Plugin::Auth::Extensible::Provider::Config
Authenticates users stored in the app's config
Need to write your own? Just subclass
Dancer::Plugin::Auth::Extensible::Provider::Base and implement the
required methods, and you're good to go!
CONTROLLING ACCESS TO ROUTES
Keywords are provided to check if a user is logged in / has appropriate
roles.
require_login - require the user to be logged in
get '/dashboard' => require_login sub { .... };
If the user is not logged in, they will be redirected to the login
page URL to log in. The default URL is `/login' - this may be
changed with the `login_page' option.
require_role - require the user to have a specified role
get '/beer' => require_role BeerDrinker => sub { ... };
Requires that the user be logged in as a user who has the specified
role. If the user is not logged in, they will be redirected to the
login page URL. If they are logged in, but do not have the required
role, they will be redirected to the access denied URL.
require_any_roles - require the user to have one of a list of roles
get '/drink' => require_any_role [qw(BeerDrinker VodaDrinker)] => sub {
...
};
Requires that the user be logged in as a user who has any one (or
more) of the roles listed. If the user is not logged in, they will
be redirected to the login page URL. If they are logged in, but do
not have any of the specified roles, they will be redirected to the
access denied URL.
require_all_roles - require the user to have all roles listed
get '/foo' => require_all_roles [qw(Foo Bar)] => sub { ... };
Requires that the user be logged in as a user who has all of the
roles listed. If the user is not logged in, they will be redirected
to the login page URL. If they are logged in but do not have all of
the specified roles, they will be redirected to the access denied
URL.
Replacing the Default ` /login ' and ` /login/denied ' Routes
By default, the plugin adds a route to present a simple login form at
that URL. If you would rather add your own, set the `no_default_pages'
setting to a true value, and define your own route which responds to
`/login' with a login page. Alternatively you can let DPAE add the
routes and handle the status codes, etc. and simply define the setting
`login_page_handler' and/or `permission_denied_page_handler' with the
name of a subroutine to be called to handle the route. Note that it must
be a fully qualified sub. E.g.
plugins:
Auth::Extensible:
login_page_handler: 'My::App:login_page_handler'
permission_denied_page_handler: 'My::App:permission_denied_page_handler'
Then in your code you might simply use a template:
sub permission_denied_page_handler {
template 'account/login';
}
If the user is logged in, but tries to access a route which requires a
specific role they don't have, they will be redirected to the
"permission denied" page URL, which defaults to `/login/denied' but may
be changed using the `denied_page' option.
Again, by default a route is added to respond to that URL with a default
page; again, you can disable this by setting `no_default_pages' and
creating your own.
This would still leave the routes `post '/login'' and `any '/logout''
routes in place. To disable them too, set the option `no_login_handler'
to a true value. In this case, these routes should be defined by the
user, and should do at least the following:
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
# other code here
} else {
# authentication failed
}
};
any '/logout' => sub {
session->destroy;
};
If you want to use the default `post '/login'' and `any '/logout''
routes you can configure them. See below.
Keywords
require_login
Used to wrap a route which requires a user to be logged in order to
access it.
get '/secret' => require_login sub { .... };
require_role
Used to wrap a route which requires a user to be logged in as a user
with the specified role in order to access it.
get '/beer' => require_role BeerDrinker => sub { ... };
You can also provide a regular expression, if you need to match the
role using a regex - for example:
get '/beer' => require_role qr/Drinker$/ => sub { ... };
require_any_role
Used to wrap a route which requires a user to be logged in as a user
with any one (or more) of the specified roles in order to access it.
get '/foo' => require_any_role [qw(Foo Bar)] => sub { ... };
require_all_roles
Used to wrap a route which requires a user to be logged in as a user
with all of the roles listed in order to access it.
get '/foo' => require_all_roles [qw(Foo Bar)] => sub { ... };
logged_in_user
Returns a hashref of details of the currently logged-in user, if
there is one.
The details you get back will depend upon the authentication
provider in use.
user_has_role
Check if a user has the role named.
By default, the currently-logged-in user will be checked, so you
need only name the role you're looking for:
if (user_has_role('BeerDrinker')) { pour_beer(); }
You can also provide the username to check;
if (user_has_role($user, $role)) { .... }
user_roles
Returns a list of the roles of a user.
By default, roles for the currently-logged-in user will be checked;
alternatively, you may supply a username to check.
Returns a list or arrayref depending on context.
authenticate_user
Usually you'll want to let the built-in login handling code deal
with authenticating users, but in case you need to do it yourself,
this keyword accepts a username and password, and optionally a
specific realm, and checks whether the username and password are
valid.
For example:
if (authenticate_user($username, $password)) {
...
}
If you are using multiple authentication realms, by default each
realm will be consulted in turn. If you only wish to check one of
them (for instance, you're authenticating an admin user, and there's
only one realm which applies to them), you can supply the realm as
an optional third parameter.
In boolean context, returns simply true or false; in list context,
returns `($success, $realm)'.
SAMPLE CONFIGURATION
In your application's configuation file:
session: simple
plugins:
Auth::Extensible:
# Set to 1 if you want to disable the use of roles (0 is default)
disable_roles: 0
# After /login: If no return_url is given: land here ('/' is default)
user_home_page: '/user'
# After /logout: If no return_url is given: land here (no default)
exit_page: '/'
# List each authentication realm, with the provider to use and the
# provider-specific settings (see the documentation for the provider
# you wish to use)
realms:
realm_one:
provider: Database
db_connection_name: 'foo'
Please note that you must have a session provider configured. The
authentication framework requires sessions in order to track information
about the currently logged in user. Please see Dancer::Session for
information on how to configure session management within your
application.
AUTHOR
David Precious, `'
BUGS / FEATURE REQUESTS
This is an early version; there may still be bugs present or features
missing.
This is developed on GitHub - please feel free to raise issues or pull
requests against the repo at:
https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible
ACKNOWLEDGEMENTS
Valuable feedback on the early design of this module came from many
people, including Matt S Trout (mst), David Golden (xdg), Damien
Krotkine (dams), Daniel Perrett, and others.
Configurable login/logout URLs added by Rene (hertell)
Regex support for require_role by chenryn
Support for user_roles looking in other realms by Colin Ewen (casao)
Config options for default login/logout handlers by Henk van Oers
(hvoers)
LICENSE AND COPYRIGHT
Copyright 2012-16 David Precious.
This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.
Dancer-Plugin-Auth-Extensible-1.00/Makefile.PL 0000644 0001750 0001750 00000003017 12761665651 020353 0 ustar davidp davidp use strict;
use warnings;
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Dancer::Plugin::Auth::Extensible',
AUTHOR => q{David Precious },
VERSION_FROM => 'lib/Dancer/Plugin/Auth/Extensible.pm',
ABSTRACT_FROM => 'lib/Dancer/Plugin/Auth/Extensible.pm',
($ExtUtils::MakeMaker::VERSION >= 6.3002
? ('LICENSE'=> 'perl')
: ()),
PL_FILES => {},
EXE_FILES => [ 'bin/generate-crypted-password' ],
PREREQ_PM => {
'Test::More' => 0,
'Dancer' => 1.3118,
'Crypt::SaltedHash' => 0,
'YAML' => 0, # for config files (TODO: make optional?)
},
MIN_PERL_VERSION => 5.006001,
dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', },
clean => { FILES => 'Dancer-Plugin-Auth-Extensible-*' },
META_MERGE => {
"meta-spec" => { version => 2 },
resources => {
repository => 'https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible',
bugtracker => 'https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible/issues',
homepage => 'https://github.com/bigpresh/Dancer-Plugin-Auth-Extensible/',
},
prereqs => {
runtime => {
recommends => {
'Authen::Simple::PAM' => 0,
'Dancer::Plugin::Database' => 0,
'Unix::Passwd::File' => 0,
}
}
}
},
);
Dancer-Plugin-Auth-Extensible-1.00/t/ 0000755 0001750 0001750 00000000000 12762006471 016631 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/t/01-basic.t 0000644 0001750 0001750 00000013566 12762006332 020324 0 ustar davidp davidp use strict;
use warnings;
use Test::More import => ['!pass'];
use t::lib::TestApp;
use Dancer ':syntax';
my $dancer_version;
BEGIN {
$dancer_version = (exists &dancer_version) ? int(dancer_version()) : 1;
require Dancer::Test;
if ($dancer_version == 1) {
Dancer::Test->import();
} else {
Dancer::Test->import('t::lib::TestApp');
}
}
diag sprintf "Testing DPAE version %s under Dancer %s",
$Dancer::Plugin::Auth::Extensible::VERSION,
$Dancer::VERSION;
# First, without being logged in, check we can access the index page, but not
# stuff we need to be logged in for:
response_content_is [ GET => '/' ], 'Index always accessible',
'Index accessible while not logged in';
response_redirect_location_is [ GET => '/loggedin' ],
'http://localhost/login?return_url=%2Floggedin',
'/loggedin redirected to login page when not logged in';
response_redirect_location_is [ GET => '/beer' ],
'http://localhost/login?return_url=%2Fbeer',
'/beer redirected to login page when not logged in';
response_redirect_location_is [ GET => '/regex/a' ],
'http://localhost/login?return_url=%2Fregex%2Fa',
'/regex/a redirected to login page when not logged in';
# OK, now check we can't log in with fake details
response_status_is [
POST => '/login', { body => { username => 'foo', password => 'bar' } }
], 401, 'Login with fake details fails';
# ... and that we can log in with real details
response_status_is [
POST => '/login', { body => { username => 'dave', password => 'beer' } }
], 302, 'Login with real details succeeds';
# Now we're logged in, check we can access stuff we should...
response_status_is [ GET => '/loggedin' ], 200,
'Can access /loggedin now we are logged in';
response_content_is [ GET => '/loggedin' ], 'You are logged in',
'Correct page content while logged in, too';;
response_content_is [ GET => '/name' ], 'Hello, David Precious',
'Logged in user details via logged_in_user work';
response_content_is [ GET => '/roles' ], 'BeerDrinker,Motorcyclist',
'Correct roles for logged in user';
response_content_is [ GET => '/roles/bob'], 'CiderDrinker', 'Correct roles for other user in current realm';
# Check we can request something which requires a role we have....
response_status_is [ GET => '/beer' ], 200,
'We can request a route (/beer) requiring a role we have...';
# Check we can request a route that requires any of a list of roles, one of
# which we have:
response_status_is [ GET => '/anyrole' ], 200,
"We can request a multi-role route requiring with any one role";
response_status_is [ GET => '/allroles' ], 200,
"We can request a multi-role route with all roles required";
# And also a route declared as a regex (this should be no different, but
# melmothX was seeing issues with routes not requiring login when they should...
response_status_is [ GET => '/regex/a' ], 200,
"We can request a regex route when logged in";
response_status_is [ GET => '/piss/regex' ], 200,
"We can request a route requiring a regex role we have";
# ... but can't request something requiring a role we don't have
response_redirect_location_is [ GET => '/piss' ],
'http://localhost/login/denied?return_url=%2Fpiss',
"We cannot request a route requiring a role we don't have";
# Check the realm we authenticated against is what we expect
response_content_is [ GET => '/realm' ], 'config1',
'Authenticated against expected realm';
# Now, log out
response_status_is [
POST => '/logout', {},
], 200, 'Logging out returns 200';
# Check we can't access protected pages now we logged out:
response_redirect_location_is [ GET => '/loggedin' ],
'http://localhost/login?return_url=%2Floggedin',
'/loggedin redirected to login page after logging out';
response_redirect_location_is [ GET => '/beer' ],
'http://localhost/login?return_url=%2Fbeer',
'/beer redirected to login page after logging out';
# OK, log back in, this time as a user from the second realm
response_status_is [
POST => '/login', { body => { username => 'burt', password => 'bacharach' } }
], 302, 'Login as user from second realm succeeds';
# And that now we're logged in again, we can access protected pages
response_status_is [ GET => '/loggedin' ], 200,
'Can access /loggedin now we are logged in again';
# And that the realm we authenticated against is what we expect
response_content_is [ GET => '/realm' ], 'config2',
'Authenticated against expected realm';
response_content_is [ GET => '/roles/bob/config1'], 'CiderDrinker', 'Correct roles for other user in current realm';
# Now, log out again
response_status_is [
POST => '/logout', {},
], 200, 'Logged out again';
# Now check we can log in as a user whose password is stored hashed:
response_status_is [
POST => '/login', {
body => { username => 'hashedpassword', password => 'password' }
}
], 302, 'Login as user with hashed password succeeds';
# And that now we're logged in again, we can access protected pages
response_status_is [ GET => '/loggedin' ], 200,
'Can access /loggedin now we are logged in again';
# Check that the redirect URL can be set when logging in
response_redirect_location_is(
[
POST => '/login', {
body => {
username => 'dave',
password => 'beer',
return_url => '/foobar',
},
},
],
'http://localhost/foobar',
'Redirect after login to given return_url works',
);
# Test that we are in fact caching fetches of user details, and that we do get
# the same details back from the cache. (The numbers are the number of times
# the provider was asked for the user's details, and we check the result from
# logged_in_user is usable both when initially fetched and when fetched from
# cache.)
response_content_is [ GET => '/testcaching' ], "0:dave:1:dave:1",
"Repeated calls to logged_in_user are cached";
done_testing();
Dancer-Plugin-Auth-Extensible-1.00/t/00-load.t 0000644 0001750 0001750 00000000347 12021514014 020137 0 ustar davidp davidp #!perl -T
use Test::More tests => 1;
BEGIN {
use_ok( 'Dancer::Plugin::Auth::Extensible' ) || print "Bail out!
";
}
diag( "Testing Dancer::Plugin::Auth::Extensible $Dancer::Plugin::Auth::Extensible::VERSION, Perl $], $^X" );
Dancer-Plugin-Auth-Extensible-1.00/t/pod.t 0000644 0001750 0001750 00000000521 12241130520 017557 0 ustar davidp davidp #!perl
use strict;
use warnings;
use Test::More;
unless ( $ENV{RELEASE_TESTING} ) {
plan( skip_all => "Author tests not required for installation" );
}
# Ensure a recent version of Test::Pod
my $min_tp = 1.22;
eval "use Test::Pod $min_tp";
plan skip_all => "Test::Pod $min_tp required for testing POD" if $@;
all_pod_files_ok();
Dancer-Plugin-Auth-Extensible-1.00/t/lib/ 0000755 0001750 0001750 00000000000 12762006471 017377 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/t/lib/public/ 0000755 0001750 0001750 00000000000 12762006471 020655 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/t/lib/public/.placeholder 0000644 0001750 0001750 00000000522 12022467635 023141 0 ustar davidp davidp This directory is empty on purpose, and this file is here solely so that git
tracks it, as git won't track empty directories (mostly because it doesn't track
directories at all, only the files in them).
This otherwise-empty directory is needed to avoid a strange bug on Windows
systems where Cwd::realpath() croaks if they don't exist.
Dancer-Plugin-Auth-Extensible-1.00/t/lib/config.yml 0000644 0001750 0001750 00000001507 12054743542 021373 0 ustar davidp davidp session: simple
plugins:
Auth::Extensible:
realms:
config1:
provider: Config
users:
- user: dave
pass: beer
name: "David Precious"
roles:
- BeerDrinker
- Motorcyclist
- user: bob
pass: cider
name: "Bob Smith"
roles:
- CiderDrinker
config2:
provider: Config
users:
- user: burt
pass: bacharach
- user: hashedpassword
pass: "{SSHA}+2u1HpOU7ak6iBR6JlpICpAUvSpA/zBM"
logger: console
log: core
show_errors: 1
Dancer-Plugin-Auth-Extensible-1.00/t/lib/views/ 0000755 0001750 0001750 00000000000 12762006471 020534 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/t/lib/views/.placeholder 0000644 0001750 0001750 00000000522 12022467635 023020 0 ustar davidp davidp This directory is empty on purpose, and this file is here solely so that git
tracks it, as git won't track empty directories (mostly because it doesn't track
directories at all, only the files in them).
This otherwise-empty directory is needed to avoid a strange bug on Windows
systems where Cwd::realpath() croaks if they don't exist.
Dancer-Plugin-Auth-Extensible-1.00/t/lib/TestApp.pm 0000644 0001750 0001750 00000004000 12762006332 021303 0 ustar davidp davidp package t::lib::TestApp;
use Dancer;
set session => 'simple';
set plugins => { 'Auth::Extensible' => { provider => 'Example' } };
use Dancer::Plugin::Auth::Extensible;
no warnings 'uninitialized';
get '/' => sub {
"Index always accessible";
};
get '/loggedin' => require_login sub {
"You are logged in";
};
get '/name' => require_login sub {
return "Hello, " . logged_in_user->{name};
};
get '/roles' => require_login sub {
return join ',', sort @{ user_roles() };
};
get '/roles/:user' => require_login sub {
my $user = param 'user';
return join ',', sort @{ user_roles($user) };
};
get '/roles/:user/:realm' => require_login sub {
my $user = param 'user';
my $realm = param 'realm';
return join ',', sort @{ user_roles($user, $realm) };
};
get '/realm' => require_login sub {
return session->{logged_in_user_realm};
};
get '/beer' => require_role BeerDrinker => sub {
"You can have a beer";
};
get '/piss' => require_role BearGrylls => sub {
"You can drink piss";
};
get '/piss/regex' => require_role qr/beer/i => sub {
"You can drink piss now";
};
get '/anyrole' => require_any_role ['Foo','BeerDrinker'] => sub {
"Matching one of multiple roles works";
};
get '/allroles' => require_all_roles ['BeerDrinker', 'Motorcyclist'] => sub {
"Matching multiple required roles works";
};
get qr{/regex/(.+)} => require_login sub {
return "Matched";
};
get '/testcaching' => sub {
my $orig = Dancer::Plugin::Auth::Extensible::Provider::Config->can('get_user_details');
my $count = 0;
no warnings 'redefine';
local *Dancer::Plugin::Auth::Extensible::Provider::Config::get_user_details = sub {
$count++;
$orig->(@_);
};
# Call logged_in_user() multiple times, ensure we get the same result each
# time, and that it's cached
my @res;
push @res, $count;
push @res, logged_in_user()->{user};
push @res, $count;
push @res, logged_in_user()->{user};
push @res, $count;
return join ":", @res;
};
1;
Dancer-Plugin-Auth-Extensible-1.00/t/lib/lib/ 0000755 0001750 0001750 00000000000 12762006471 020145 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/t/lib/lib/.placeholder 0000644 0001750 0001750 00000000522 12022467635 022431 0 ustar davidp davidp This directory is empty on purpose, and this file is here solely so that git
tracks it, as git won't track empty directories (mostly because it doesn't track
directories at all, only the files in them).
This otherwise-empty directory is needed to avoid a strange bug on Windows
systems where Cwd::realpath() croaks if they don't exist.
Dancer-Plugin-Auth-Extensible-1.00/t/manifest.t 0000644 0001750 0001750 00000000420 12021514014 020601 0 ustar davidp davidp #!perl -T
use strict;
use warnings;
use Test::More;
unless ( $ENV{RELEASE_TESTING} ) {
plan( skip_all => "Author tests not required for installation" );
}
eval "use Test::CheckManifest 0.9";
plan skip_all => "Test::CheckManifest 0.9 required" if $@;
ok_manifest();
Dancer-Plugin-Auth-Extensible-1.00/MANIFEST 0000644 0001750 0001750 00000001345 12762006471 017522 0 ustar davidp davidp README
t/00-load.t
t/01-basic.t
t/pod.t
t/lib/TestApp.pm
t/lib/views/.placeholder
t/lib/public/.placeholder
t/lib/lib/.placeholder
t/lib/config.yml
t/manifest.t
lib/Dancer/Plugin/Auth/Extensible/Provider/Database.pm
lib/Dancer/Plugin/Auth/Extensible/Provider/Example.pm
lib/Dancer/Plugin/Auth/Extensible/Provider/Config.pm
lib/Dancer/Plugin/Auth/Extensible/Provider/Unix.pm
lib/Dancer/Plugin/Auth/Extensible/Provider/Base.pm
lib/Dancer/Plugin/Auth/Extensible.pm
bin/generate-crypted-password
MANIFEST
example/authextest.pl
example/config.yml
ignore.txt
Makefile.PL
Changes
META.yml Module YAML meta-data (added by MakeMaker)
META.json Module JSON meta-data (added by MakeMaker)
Dancer-Plugin-Auth-Extensible-1.00/example/ 0000755 0001750 0001750 00000000000 12762006471 020021 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/example/config.yml 0000644 0001750 0001750 00000001207 12064170234 022003 0 ustar davidp davidp appname: authextest
session: simple
logger: console
log: core
plugins:
Auth::Extensible:
realms:
example:
provider: Example
config:
provider: Config
users:
- user: 'beerdrinker'
pass: 'password'
name: 'Beer drinker'
roles:
- BeerDrinker
- user: 'vodkadrinker'
pass: 'password'
name: 'Vodka drinker'
roles:
- VodkaDrinker
show_errors: 1
Dancer-Plugin-Auth-Extensible-1.00/example/authextest.pl 0000644 0001750 0001750 00000002151 12064170362 022547 0 ustar davidp davidp #!/usr/bin/perl
use Dancer;
use lib '../lib';
use Dancer::Plugin::Auth::Extensible;
get '/' => sub {
my $content = "Non-secret home page!
";
if (my $user = logged_in_user()) {
$content .= "Hi there, $user->{name}!
";
} else {
$content .= "Why not log in?
";
}
$content .= <Psst, wanna know a secret?
Or maybe you want a beer
Or, a vodka?
LINKS
if (user_has_role('BeerDrinker')) {
$content .= "You can drink beer
";
}
if (user_has_role('WineDrinker')) {
$content .= "You can drink wine
";
}
return $content;
};
get '/secret' => require_login sub { "Only logged-in users can see this" };
get '/beer' => require_any_role [qw(BeerDrinker HardDrinker)], sub {
"Any drinker can get beer.";
};
get '/vodka' => require_role HardDrinker => sub {
"Only hard drinkers get vodka";
};
get '/realm' => require_login sub {
"You are logged in using realm: " . session->{logged_in_user_realm};
};
dance();
Dancer-Plugin-Auth-Extensible-1.00/lib/ 0000755 0001750 0001750 00000000000 12762006471 017134 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/ 0000755 0001750 0001750 00000000000 12762006471 020330 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/ 0000755 0001750 0001750 00000000000 12762006471 021566 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/ 0000755 0001750 0001750 00000000000 12762006471 022467 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/ 0000755 0001750 0001750 00000000000 12762006471 024571 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/ 0000755 0001750 0001750 00000000000 12762006471 026363 5 ustar davidp davidp Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/Config.pm 0000644 0001750 0001750 00000004563 12520443776 030143 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible::Provider::Config;
use strict;
use warnings;
use base "Dancer::Plugin::Auth::Extensible::Provider::Base";
=head1 NAME
Dancer::Plugin::Auth::Extensible::Config - example auth provider using app config
=head1 DESCRIPTION
This is a simple authentication provider which authenticates based on a list of
usernames, passwords (crypted, preferably - see below) and role specifications
provided in the realm definition in your app's config file.
This class is primarily intended as an example of what an authentication
provider class should do; however, if you just want simple user authentication
with user details stored in your app's config file, it may well suit your needs.
See L for details on how to use the
authentication framework.
=head1 SYNOPSIS
In your app's C:
plugins:
Auth::Extensible:
realms:
config:
provider: Config
users:
- user: dave
pass: supersecret
roles:
- Developer
- Manager
- BeerDrinker
- user: bob
pass: '{SSHA}+2u1HpOU7ak6iBR6JlpICpAUvSpA/zBM'
roles:
- Tester
As you can see, you can define the usernames, passwords (please use crypted
passwords, RFC2307-style, not plain text (although plain text *is* supported,
but really not a good idea), and the roles for each user (if you're
not planning to use roles, omit the roles section from each user entirely).
=cut
sub authenticate_user {
my ($self, $username, $password) = @_;
my $user_details = $self->get_user_details($username) or return;
return $self->match_password($password, $user_details->{pass});
}
# Just return the whole user definition from the config; this way any additional
# fields defined for users will just get passed through.
sub get_user_details {
my ($self, $username) = @_;
my ($user) = grep {
$_->{user} eq $username
} @{ $self->realm_settings->{users} };
return $user;
}
sub get_user_roles {
my ($self, $username) = @_;
my $user_details = $self->get_user_details($username) or return;
return $user_details->{roles};
}
1;
Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/Database.pm 0000644 0001750 0001750 00000023272 12762006332 030427 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible::Provider::Database;
use strict;
use warnings;
use base 'Dancer::Plugin::Auth::Extensible::Provider::Base';
use Dancer::Plugin::Database;
use Dancer qw(:syntax);
=head1 NAME
Dancer::Plugin::Auth::Extensible::Database - authenticate via a database
=head1 DESCRIPTION
This class is an authentication provider designed to authenticate users against
a database, using L to access a database.
L is used to handle hashed passwords securely; you wouldn't
want to store plain text passwords now, would you? (If your answer to that is
yes, please reconsider; you really don't want to do that, when it's so easy to
do things right!)
See L for how to configure a database connection
appropriately; see the L section below for how to configure this
authentication provider with database details.
See L for details on how to use the
authentication framework, including how to pick a more useful authentication
provider.
=head1 CONFIGURATION
This provider tries to use sensible defaults, so you may not need to provide
much configuration if your database tables look similar to those in the
L section below.
The most basic configuration, assuming defaults for all options, and defining a
single authentication realm named 'users':
plugins:
Auth::Extensible:
realms:
users:
provider: 'Database'
You would still need to have provided suitable database connection details to
L, of course; see the docs for that plugin for full
details, but it could be as simple as, e.g.:
plugins:
Auth::Extensible:
realms:
users:
provider: 'Database'
Database:
driver: 'SQLite'
database: 'test.sqlite'
A full example showing all options:
plugins:
Auth::Extensible:
realms:
users:
provider: 'Database'
# optionally set DB connection name to use (see named
# connections in Dancer::Plugin::Database docs)
db_connection_name: 'foo'
# Optionally disable roles support, if you only want to check
# for successful logins but don't need to use role-based access:
disable_roles: 1
# optionally specify names of tables if they're not the defaults
# (defaults are 'users', 'roles' and 'user_roles')
users_table: 'users'
roles_table: 'roles'
user_roles_table: 'user_roles'
# optionally set the column names (see the SUGGESTED SCHEMA
# section below for the default names; if you use them, they'll
# Just Work)
users_id_column: 'id'
users_username_column: 'username'
users_password_column: 'password'
roles_id_column: 'id'
roles_role_column: 'role'
user_roles_user_id_column: 'user_id'
user_roles_role_id_column: 'roles_id'
See the main L documentation for how to
configure multiple authentication realms.
=head1 SUGGESTED SCHEMA
If you use a schema similar to the examples provided here, you should need
minimal configuration to get this authentication provider to work for you.
The examples given here should be MySQL-compatible; minimal changes should be
required to use them with other database engines.
=head2 users table
You'll need a table to store user accounts in, of course. A suggestion is
something like:
CREATE TABLE users (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(32) NOT NULL UNIQUE KEY,
password VARCHAR(40) NOT NULL
);
You will quite likely want other fields to store e.g. the user's name, email
address, etc; all columns from the users table will be returned by the
C keyword for your convenience.
=head2 roles table
You'll need a table to store a list of available roles in (unless you're not
using roles - in which case, disable role support (see the L
section).
CREATE TABLE roles (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
role VARCHAR(32) NOT NULL
);
=head2 user_roles table
Finally, (unless you've disabled role support) you'll need a table to store
user <-> role mappings (i.e. one row for every role a user has; so adding
extra roles to a user consists of adding a new role to this table). It's
entirely up to you whether you use an "id" column in this table; you probably
shouldn't need it.
CREATE TABLE user_roles (
user_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
UNIQUE KEY user_role (user_id, role_id)
);
If you're using InnoDB tables rather than the default MyISAM, you could add a
foreign key constraint for better data integrity; see the MySQL documentation
for details, but a table definition using foreign keys could look like:
CREATE TABLE user_roles (
user_id INTEGER, FOREIGN KEY (user_id) REFERENCES users (id),
role_id INTEGER, FOREIGN_KEY (role_id) REFERENCES roles (id),
UNIQUE KEY user_role (user_id, role_id)
) ENGINE=InnoDB;
=cut
sub authenticate_user {
my ($self, $username, $password) = @_;
# Look up the user:
my $user = $self->get_user_details($username);
return unless $user;
# OK, we found a user, let match_password (from our base class) take care of
# working out if the password is correct
my $settings = $self->realm_settings;
my $password_column = $settings->{users_password_column} || 'password';
return $self->match_password($password, $user->{$password_column});
}
# Return details about the user. The user's row in the users table will be
# fetched and all columns returned as a hashref.
sub get_user_details {
my ($self, $username) = @_;
return unless defined $username;
my $settings = $self->realm_settings;
# Get our database handle and find out the table and column names:
my $database = database($settings->{db_connection_name})
or die "No database connection";
my $users_table = $settings->{users_table} || 'users';
my $username_column = $settings->{users_username_column} || 'username';
my $password_column = $settings->{users_password_column} || 'password';
# Look up the user,
my $user = $database->quick_select(
$users_table, { $username_column => $username }
);
if (!$user) {
debug("No such user $username");
return;
} else {
return $user;
}
}
sub get_user_roles {
my ($self, $username) = @_;
my $settings = $self->realm_settings;
# Get our database handle and find out the table and column names:
my $database = database($settings->{db_connection_name});
# Get details of the user first; both to check they exist, and so we have
# their ID to use.
my $user = $self->get_user_details($username)
or return;
# Right, fetch the roles they have. There's currently no support for
# JOINs in Dancer::Plugin::Database, so we'll need to do this query
# ourselves - so we'd better take care to quote the table & column names, as
# we're going to have to interpolate them. (They're coming from our config,
# so should be pretty trustable, but they might conflict with reserved
# identifiers or have unacceptable characters to not be quoted.)
# Because I've tried to be so flexible in allowing the user to configure
# table names, column names, etc, this is going to be fucking ugly.
# Seriously ugly. Clear bag of smashed arseholes territory.
my $roles_table = $database->quote_identifier(
$settings->{roles_table} || 'roles'
);
my $roles_role_id_column = $database->quote_identifier(
$settings->{roles_id_column} || 'id'
);
my $roles_role_column = $database->quote_identifier(
$settings->{roles_role_column} || 'role'
);
my $user_roles_table = $database->quote_identifier(
$settings->{user_roles_table} || 'user_roles'
);
my $user_roles_user_id_column = $database->quote_identifier(
$settings->{user_roles_user_id_column} || 'user_id'
);
my $user_roles_role_id_column = $database->quote_identifier(
$settings->{user_roles_role_id_column} || 'role_id'
);
# Yes, there's SQL interpolation here; yes, it makes me throw up a little.
# However, all the variables used have been quoted appropriately above, so
# although it might look like a camel's arsehole, at least it's safe.
my $sql = <prepare($sql)
or die "Failed to prepare query - error: " . $database->err_str;
$sth->execute($user->{$settings->{users_id_column} || 'id'});
my @roles;
while (my($role) = $sth->fetchrow_array) {
push @roles, $role;
}
return \@roles;
# If you read through this, I'm truly, truly sorry. This mess was the price
# of making things so configurable. Send me your address, and I'll send you
# a complementary fork to remove your eyeballs with as way of apology.
# If I can bear to look at this code again, I think I might seriously
# refactor it and use Template::Tiny or something on it. Or Acme::Bleach.
}
1;
Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/Base.pm 0000644 0001750 0001750 00000004445 12520443776 027607 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible::Provider::Base;
use strict;
use warnings;
use Crypt::SaltedHash;
=head1 NAME
Dancer::Plugin::Auth::Extensible::Provider::Base - base class for authentication providers
=head1 DESCRIPTION
Base class for authentication providers. Provides a constructor which handles
receiving the realm settings and returning an instance of the provider.
Also provides secure password matching which automatically handles crypted
passwords via Crypt::SaltedHash.
Finally, provides the methods which providers must override with their
implementation, which will die if they are not overridden.
=cut
sub new {
my ($class, $realm_settings) = @_;
my $self = {
realm_settings => $realm_settings,
};
return bless $self => $class;
}
sub realm_settings { shift->{realm_settings} || {} }
sub match_password {
my ($self, $given, $correct) = @_;
# TODO: perhaps we should accept a configuration option to state whether
# passwords are crypted or not, rather than guessing by looking for the
# {...} tag at the start.
# I wanted to let it try straightforward comparison first, then try
# Crypt::SaltedHash->validate, but that has a weakness: if a list of hashed
# passwords got leaked, you could use the hashed password *as it is* to log
# in, rather than cracking it first. That's obviously Not Fucking Good.
# TODO: think about this more. This shit is important. I'm thinking a
# config option to indicate whether passwords are crypted - yes, no, auto
# (where auto would do the current guesswork, and yes/no would just do as
# told.)
if ($correct =~ /^{.+}/) {
# Looks like a crypted password starting with the scheme, so try to
# validate it with Crypt::SaltedHash:
return Crypt::SaltedHash->validate($correct, $given);
} else {
# Straightforward comparison, then:
return $given eq $correct;
}
}
# Install basic method placeholders which will blow up if the provider module
# did not implement their own version.
{
no strict 'refs';
for my $method (qw(
authenticate_user
get_user_details
get_user_roles
))
{
*$method = sub {
die "$method was not implemented by provider " . __PACKAGE__;
};
}
}
1;
Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/Unix.pm 0000644 0001750 0001750 00000002535 12520443776 027656 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible::Provider::Unix;
use strict;
use warnings;
use base 'Dancer::Plugin::Auth::Extensible::Provider::Base';
use Authen::Simple::PAM;
use Unix::Passwd::File;
=head1 NAME
Dancer::Plugin::Auth::Extensible::Unix - authenticate *nix system accounts
=head1 DESCRIPTION
An authentication provider for L which
authenticates Linux/Unix system accounts.
Uses L to read user details, and L to
perform authentication via PAM.
The C call for this provider will return information from the
C file - expect C, C, C, C, C, C.
Unix group membership is used as a reasonable facsimile for roles - this seems
sensible.
=cut
sub authenticate_user {
my ($class, $username, $password) = @_;
my $pam = Authen::Simple::PAM->new( service => 'login' );
return $pam->authenticate($username, $password);
}
sub get_user_details {
my ($class, $username) = @_;
my $result = Unix::Passwd::File::get_user(
user => $username
);
return if $result->[0] != 200;
return $result->[2];
}
sub get_user_roles {
my ($class, $username) = @_;
my $result = Unix::Passwd::File::get_user_groups(user => $username);
return if $result->[0] != 200;
return $result->[2];
}
1;
Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible/Provider/Example.pm 0000644 0001750 0001750 00000004337 12761670526 030332 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible::Provider::Example;
use strict;
use warnings;
use base "Dancer::Plugin::Auth::Extensible::Provider::Base";
# A more sensible provider would be likely to get this information from e.g. a
# database (or LDAP, or...) rather than hardcoding it. This, however, is an
# example.
sub users {
return {
'dave' => {
name => 'David Precious',
password => 'beer',
roles => [ qw(Motorcyclist BeerDrinker) ],
},
'bob' => {
name => 'Bob The Builder',
password => 'canhefixit',
roles => [ qw(Fixer) ],
},
};
}
=head1 NAME
Dancer::Plugin::Auth::Extensible::Example - example authentication provider
=head1 DESCRIPTION
This class is intended as an example of what an authentication provider class
should do. It is not intended for serious use (clearly).
See L for details on how to use the
authentication framework, including how to pick a more useful authentication
provider.
However, if you just want to test the framework, or want an example to work from
to build your own authentication provider class, this may be of use.
=cut
=head1 Class methods
=over
=item authenticate_user
Given the username and password entered by the user, return true if they are
authenticated, or false if not.
=cut
sub authenticate_user {
my ($self, $username, $password) = @_;
my $user_details = $self->get_user_details($username) or return;
return $self->match_password($password, $user_details->{password});
}
=item get_user_details
Given a username, return details about the user. The details returned will vary
depending on the provider; some providers may be able to return various data
about the user, some may not, depending on the authentication source.
Details should be returned as a hashref.
=cut
sub get_user_details {
my ($self, $username) = @_;
return $self->users->{lc $username};
}
=item get_user_roles
Given a username, return a list of roles that user has.
=back
=cut
sub get_user_roles {
my ($self, $username) = @_;
my $user_details = $self->get_user_details($username) or return;
return $user_details->{roles};
}
1;
Dancer-Plugin-Auth-Extensible-1.00/lib/Dancer/Plugin/Auth/Extensible.pm 0000644 0001750 0001750 00000055262 12762006332 025135 0 ustar davidp davidp package Dancer::Plugin::Auth::Extensible;
use warnings;
use strict;
use Carp;
use Dancer::Plugin;
use Dancer qw(:syntax);
our $VERSION = '1.00';
my $settings = plugin_setting;
my $loginpage = $settings->{login_page} || '/login';
my $userhomepage = $settings->{user_home_page} || '/';
my $logoutpage = $settings->{logout_page} || '/logout';
my $deniedpage = $settings->{denied_page} || '/login/denied';
my $exitpage = $settings->{exit_page};
=head1 NAME
Dancer::Plugin::Auth::Extensible - extensible authentication framework for Dancer apps
=head1 DESCRIPTION
A user authentication and authorisation framework plugin for Dancer apps.
Makes it easy to require a user to be logged in to access certain routes,
provides role-based access control, and supports various authentication
methods/sources (config file, database, Unix system users, etc).
Designed to support multiple authentication realms and to be as extensible as
possible, and to make secure password handling easy. The base class for auth
providers makes handling C-style hashed passwords really simple, so you
have no excuse for storing plain-text passwords. A simple script to generate
RFC2307-style hashed passwords is included, or you can use L
yourself to do so, or use the C utility if you have it installed.
=head1 SYNOPSIS
Configure the plugin to use the authentication provider class you wish to use:
plugins:
Auth::Extensible:
realms:
users:
provider: Example
....
The configuration you provide will depend on the authentication provider module
in use. For a simple example, see
L.
Define that a user must be logged in and have the proper permissions to
access a route:
get '/secret' => require_role Confidant => sub { tell_secrets(); };
Define that a user must be logged in to access a route - and find out who is
logged in with the C keyword:
get '/users' => require_login sub {
my $user = logged_in_user;
return "Hi there, $user->{username}";
};
=head1 AUTHENTICATION PROVIDERS
For flexibility, this authentication framework uses simple authentication
provider classes, which implement a simple interface and do whatever is required
to authenticate a user against the chosen source of authentication.
For an example of how simple provider classes are, so you can build your own if
required or just try out this authentication framework plugin easily,
see L.
This framework supplies the following providers out-of-the-box:
=over 4
=item L
Authenticates users using system accounts on Linux/Unix type boxes
=item L
Authenticates users stored in a database table
=item L
Authenticates users stored in the app's config
=back
Need to write your own? Just subclass
L and implement the required
methods, and you're good to go!
=head1 CONTROLLING ACCESS TO ROUTES
Keywords are provided to check if a user is logged in / has appropriate roles.
=over
=item require_login - require the user to be logged in
get '/dashboard' => require_login sub { .... };
If the user is not logged in, they will be redirected to the login page URL to
log in. The default URL is C - this may be changed with the
C option.
=item require_role - require the user to have a specified role
get '/beer' => require_role BeerDrinker => sub { ... };
Requires that the user be logged in as a user who has the specified role. If
the user is not logged in, they will be redirected to the login page URL. If
they are logged in, but do not have the required role, they will be redirected
to the access denied URL.
=item require_any_roles - require the user to have one of a list of roles
get '/drink' => require_any_role [qw(BeerDrinker VodaDrinker)] => sub {
...
};
Requires that the user be logged in as a user who has any one (or more) of the
roles listed. If the user is not logged in, they will be redirected to the
login page URL. If they are logged in, but do not have any of the specified
roles, they will be redirected to the access denied URL.
=item require_all_roles - require the user to have all roles listed
get '/foo' => require_all_roles [qw(Foo Bar)] => sub { ... };
Requires that the user be logged in as a user who has all of the roles listed.
If the user is not logged in, they will be redirected to the login page URL. If
they are logged in but do not have all of the specified roles, they will be
redirected to the access denied URL.
=back
=head2 Replacing the Default C< /login > and C< /login/denied > Routes
By default, the plugin adds a route to present a simple login form at that URL.
If you would rather add your own, set the C setting to a true
value, and define your own route which responds to C with a login page.
Alternatively you can let DPAE add the routes and handle the status codes, etc.
and simply define the setting C and/or
C with the name of a subroutine to be called to
handle the route. Note that it must be a fully qualified sub. E.g.
plugins:
Auth::Extensible:
login_page_handler: 'My::App:login_page_handler'
permission_denied_page_handler: 'My::App:permission_denied_page_handler'
Then in your code you might simply use a template:
sub permission_denied_page_handler {
template 'account/login';
}
If the user is logged in, but tries to access a route which requires a specific
role they don't have, they will be redirected to the "permission denied" page
URL, which defaults to C but may be changed using the
C option.
Again, by default a route is added to respond to that URL with a default page;
again, you can disable this by setting C and creating your
own.
This would still leave the routes C and C
routes in place. To disable them too, set the option C
to a true value. In this case, these routes should be defined by the user,
and should do at least the following:
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
# other code here
} else {
# authentication failed
}
};
any '/logout' => sub {
session->destroy;
};
If you want to use the default C and C routes
you can configure them. See below.
=head2 Keywords
=over
=item require_login
Used to wrap a route which requires a user to be logged in order to access
it.
get '/secret' => require_login sub { .... };
=cut
sub require_login {
my $coderef = shift;
return sub {
if (!$coderef || ref $coderef ne 'CODE') {
croak "Invalid require_login usage, please see docs";
}
my $user = logged_in_user();
if (!$user) {
execute_hook('login_required', $coderef);
# TODO: see if any code executed by that hook set up a response
return redirect uri_for($loginpage, { return_url => request->request_uri });
}
return $coderef->();
};
}
register require_login => \&require_login;
register requires_login => \&require_login;
=item require_role
Used to wrap a route which requires a user to be logged in as a user with the
specified role in order to access it.
get '/beer' => require_role BeerDrinker => sub { ... };
You can also provide a regular expression, if you need to match the role using a
regex - for example:
get '/beer' => require_role qr/Drinker$/ => sub { ... };
=cut
sub require_role {
return _build_wrapper(@_, 'single');
}
register require_role => \&require_role;
register requires_role => \&require_role;
=item require_any_role
Used to wrap a route which requires a user to be logged in as a user with any
one (or more) of the specified roles in order to access it.
get '/foo' => require_any_role [qw(Foo Bar)] => sub { ... };
=cut
sub require_any_role {
return _build_wrapper(@_, 'any');
}
register require_any_role => \&require_any_role;
register requires_any_role => \&require_any_role;
=item require_all_roles
Used to wrap a route which requires a user to be logged in as a user with all
of the roles listed in order to access it.
get '/foo' => require_all_roles [qw(Foo Bar)] => sub { ... };
=cut
sub require_all_roles {
return _build_wrapper(@_, 'all');
}
register require_all_roles => \&require_all_roles;
register requires_all_roles => \&require_all_roles;
sub _build_wrapper {
my $require_role = shift;
my $coderef = shift;
my $mode = shift;
my @role_list = ref $require_role eq 'ARRAY'
? @$require_role
: $require_role;
return sub {
my $user = logged_in_user();
if (!$user) {
execute_hook('login_required', $coderef);
# TODO: see if any code executed by that hook set up a response
return redirect uri_for($loginpage, { return_url => request->request_uri });
}
my $role_match;
if ($mode eq 'single') {
for (user_roles()) {
$role_match++ and last if _smart_match($_, $require_role);
}
} elsif ($mode eq 'any') {
my %role_ok = map { $_ => 1 } @role_list;
for (user_roles()) {
$role_match++ and last if $role_ok{$_};
}
} elsif ($mode eq 'all') {
$role_match++;
for my $role (@role_list) {
if (!user_has_role($role)) {
$role_match = 0;
last;
}
}
}
if ($role_match) {
# We're happy with their roles, so go head and execute the route
# handler coderef.
return $coderef->();
}
execute_hook('permission_denied', $coderef);
# TODO: see if any code executed by that hook set up a response
return redirect uri_for($deniedpage, { return_url => request->request_uri });
};
}
=item logged_in_user
Returns a hashref of details of the currently logged-in user, if there is one.
The details you get back will depend upon the authentication provider in use.
=cut
sub logged_in_user {
if (my $user = session 'logged_in_user') {
my $realm = session 'logged_in_user_realm';
# First, if we've cached the details of this user earlier in this route
# execution in vars, just return it rather than ask the provider again
if (my $cached = vars->{dpae_user_cache}{$realm}{$user}) {
return $cached;
}
my $provider = auth_provider($realm);
my $result = $provider->get_user_details($user, $realm);
vars->{dpae_user_cache}{$realm}{$user} = $result;
return $result;
} else {
return;
}
}
register logged_in_user => \&logged_in_user;
=item user_has_role
Check if a user has the role named.
By default, the currently-logged-in user will be checked, so you need only name
the role you're looking for:
if (user_has_role('BeerDrinker')) { pour_beer(); }
You can also provide the username to check;
if (user_has_role($user, $role)) { .... }
=cut
sub user_has_role {
my ($username, $want_role);
if (@_ == 2) {
($username, $want_role) = @_;
} else {
$username = session 'logged_in_user';
$want_role = shift;
}
return unless defined $username;
my $roles = user_roles($username);
for my $has_role (@$roles) {
return 1 if $has_role eq $want_role;
}
return 0;
}
register user_has_role => \&user_has_role;
=item user_roles
Returns a list of the roles of a user.
By default, roles for the currently-logged-in user will be checked;
alternatively, you may supply a username to check.
Returns a list or arrayref depending on context.
=cut
sub user_roles {
my ($username, $realm) = @_;
$username = session 'logged_in_user' unless defined $username;
my $search_realm = ($realm ? $realm : '');
# First, if we cached the roles they have earlier in the route execution,
# don't ask the provider again
if (my $cached = vars->{dpae_roles_cache}{$search_realm}{$username}) {
# Deref even if returning an arrayref, so calling code can't modify the
# cached entry
return wantarray ? @$cached : [ @$cached ];
}
my $roles = auth_provider($search_realm)->get_user_roles($username);
return unless defined $roles;
vars->{dpae_roles_cache}{$search_realm}{$username} = $roles;
return wantarray ? @$roles : $roles;
}
register user_roles => \&user_roles;
=item authenticate_user
Usually you'll want to let the built-in login handling code deal with
authenticating users, but in case you need to do it yourself, this keyword
accepts a username and password, and optionally a specific realm, and checks
whether the username and password are valid.
For example:
if (authenticate_user($username, $password)) {
...
}
If you are using multiple authentication realms, by default each realm will be
consulted in turn. If you only wish to check one of them (for instance, you're
authenticating an admin user, and there's only one realm which applies to them),
you can supply the realm as an optional third parameter.
In boolean context, returns simply true or false; in list context, returns
C<($success, $realm)>.
=cut
sub authenticate_user {
my ($username, $password, $realm) = @_;
my @realms_to_check = $realm? ($realm) : (keys %{ $settings->{realms} });
for my $realm (@realms_to_check) {
debug "Attempting to authenticate $username against realm $realm";
my $provider = auth_provider($realm);
if ($provider->authenticate_user($username, $password)) {
debug "$realm accepted user $username";
return wantarray ? (1, $realm) : 1;
}
}
# If we get to here, we failed to authenticate against any realm using the
# details provided.
# TODO: allow providers to raise an exception if something failed, and catch
# that and do something appropriate, rather than just treating it as a
# failed login.
return wantarray ? (0, undef) : 0;
}
register authenticate_user => \&authenticate_user;
=back
=head2 SAMPLE CONFIGURATION
In your application's configuation file:
session: simple
plugins:
Auth::Extensible:
# Set to 1 if you want to disable the use of roles (0 is default)
disable_roles: 0
# After /login: If no return_url is given: land here ('/' is default)
user_home_page: '/user'
# After /logout: If no return_url is given: land here (no default)
exit_page: '/'
# List each authentication realm, with the provider to use and the
# provider-specific settings (see the documentation for the provider
# you wish to use)
realms:
realm_one:
provider: Database
db_connection_name: 'foo'
B that you B have a session provider configured. The
authentication framework requires sessions in order to track information about
the currently logged in user.
Please see L for information on how to configure session
management within your application.
=cut
# Given a realm, returns a configured and ready to use instance of the provider
# specified by that realm's config.
{
my %realm_provider;
sub auth_provider {
my $realm = shift;
# If no realm was provided, but we have a logged in user, use their realm:
if (!$realm && session->{logged_in_user}) {
$realm = session->{logged_in_user_realm};
}
# First, if we already have a provider for this realm, go ahead and use it:
return $realm_provider{$realm} if exists $realm_provider{$realm};
# OK, we need to find out what provider this realm uses, and get an instance
# of that provider, configured with the settings from the realm.
my $realm_settings = $settings->{realms}{$realm}
or die "Invalid realm $realm";
my $provider_class = $realm_settings->{provider}
or die "No provider configured - consult documentation for "
. __PACKAGE__;
if ($provider_class !~ /::/) {
$provider_class = __PACKAGE__ . "::Provider::$provider_class";
}
my ($ok, $error) = Dancer::ModuleLoader->load($provider_class);
if (! $ok) {
die "Cannot load provider $provider_class: $error";
}
return $realm_provider{$realm} = $provider_class->new($realm_settings);
}
}
register_hook qw(login_required permission_denied);
register_plugin for_versions => [qw(1 2)];
# Given a class method name and a set of parameters, try calling that class
# method for each realm in turn, arranging for each to receive the configuration
# defined for that realm, until one returns a non-undef, then return the realm which
# succeeded and the response.
# Note: all provider class methods return a single value; if any need to return
# a list in future, this will need changing)
sub _try_realms {
my ($method, @args);
for my $realm (keys %{ $settings->{realms} }) {
my $provider = auth_provider($realm);
if (!$provider->can($method)) {
die "Provider $provider does not provide a $method method!";
}
if (defined(my $result = $provider->$method(@args))) {
return $result;
}
}
return;
}
# Set up routes to serve default pages, if desired
if ( !$settings->{no_default_pages} ) {
get $loginpage => sub {
if(logged_in_user()) {
redirect params->{return_url} || $userhomepage;
}
status 401;
my $_default_login_page =
$settings->{login_page_handler} || '_default_login_page';
no strict 'refs';
return &{$_default_login_page}();
};
get $deniedpage => sub {
status 403;
my $_default_permission_denied_page =
$settings->{permission_denied_page_handler}
|| '_default_permission_denied_page';
no strict 'refs';
return &{$_default_permission_denied_page}();
};
}
# If no_login_handler is set, let the user do the login/logout herself
if (!$settings->{no_login_handler}) {
# Handle logging in...
post $loginpage => sub {
# For security, ensure the username and password are straight scalars; if
# the app is using a serializer and we were sent a blob of JSON, they could
# have come from that JSON, and thus could be hashrefs (JSON SQL injection)
# - for database providers, feeding a carefully crafted hashref to the SQL
# builder could result in different SQL to what we'd expect.
# For instance, if we pass password => params->{password} to an SQL builder,
# we'd expect the query to include e.g. "WHERE password = '...'" (likely
# with paremeterisation) - but if params->{password} was something
# different, e.g. { 'like' => '%' }, we might end up with some SQL like
# WHERE password LIKE '%' instead - which would not be a Good Thing.
my ($username, $password) = @{ params() }{qw(username password)};
for ($username, $password) {
if (ref $_) {
# TODO: handle more cleanly
die "Attempt to pass a reference as username/password blocked";
}
}
if(logged_in_user()) {
redirect params->{return_url} || $userhomepage;
}
my ($success, $realm) = authenticate_user(
$username, $password
);
if ($success) {
session logged_in_user => $username;
session logged_in_user_realm => $realm;
redirect params->{return_url} || $userhomepage;
} else {
vars->{login_failed}++;
forward $loginpage, { login_failed => 1 }, { method => 'GET' };
}
};
# ... and logging out.
any ['get','post'] => $logoutpage => sub {
session->destroy;
if (params->{return_url}) {
redirect params->{return_url};
} elsif ($exitpage) {
redirect $exitpage;
} else {
# TODO: perhaps make this more configurable, perhaps by attempting to
# render a template first.
return "OK, logged out successfully.";
}
};
}
sub _default_permission_denied_page {
return <Permission Denied
Sorry, you're not allowed to access that page.
PAGE
}
sub _default_login_page {
my $login_fail_message = vars->{login_failed}
? "LOGIN FAILED
"
: "";
my $return_url = params->{return_url} || '';
return <Login Required
You need to log in to continue.
$login_fail_message
PAGE
}
# Replacement for much maligned and misunderstood smartmatch operator
sub _smart_match {
my ($got, $want) = @_;
if (!ref $want) {
return $got eq $want;
} elsif (ref $want eq 'Regexp') {
return $got =~ $want;
} elsif (ref $want eq 'ARRAY') {
return grep { $_ eq $got } @$want;
} else {
carp "Don't know how to match against a " . ref $want;
}
}
=head1 AUTHOR
David Precious, C<< >>
=head1 BUGS / FEATURE REQUESTS
This is an early version; there may still be bugs present or features missing.
This is developed on GitHub - please feel free to raise issues or pull requests
against the repo at:
L
=head1 ACKNOWLEDGEMENTS
Valuable feedback on the early design of this module came from many people,
including Matt S Trout (mst), David Golden (xdg), Damien Krotkine (dams),
Daniel Perrett, and others.
Configurable login/logout URLs added by Rene (hertell)
Regex support for require_role by chenryn
Support for user_roles looking in other realms by Colin Ewen (casao)
Config options for default login/logout handlers by Henk van Oers (hvoers)
=head1 LICENSE AND COPYRIGHT
Copyright 2012-16 David Precious.
This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.
=cut
1; # End of Dancer::Plugin::Auth::Extensible