Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Part 5: Authentication
This is Part 5 of 10 for the Catalyst tutorial.
Tutorial Overview
Introduction
Catalyst Basics
More Catalyst Basics
Basic CRUD
Authentication
Authorization
Debugging
Testing
Advanced CRUD
Appendices
Now that we finally have a simple yet functional application, we can focus on providing authentication (with authorization coming next in Part 6).
This part of the tutorial is divided into two main sections: 1) basic, cleartext authentication and 2) hash-based authentication.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro
This section explores how to add authentication logic to a Catalyst application.
First, we add both user and role information to the database (we will add the role information here although it will not be used until the authorization section, Part 6). Create a new SQL script file by opening myapp02.sql in your editor and insert:
myapp02.sql
-- -- Add users and roles tables, along with a many-to-many join table -- CREATE TABLE users ( id INTEGER PRIMARY KEY, username TEXT, password TEXT, email_address TEXT, first_name TEXT, last_name TEXT, active INTEGER ); CREATE TABLE roles ( id INTEGER PRIMARY KEY, role TEXT ); CREATE TABLE user_roles ( user_id INTEGER, role_id INTEGER, PRIMARY KEY (user_id, role_id) ); -- -- Load up some initial test data -- INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1); INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1); INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0); INSERT INTO roles VALUES (1, 'user'); INSERT INTO roles VALUES (2, 'admin'); INSERT INTO user_roles VALUES (1, 1); INSERT INTO user_roles VALUES (1, 2); INSERT INTO user_roles VALUES (2, 1); INSERT INTO user_roles VALUES (3, 1);
Then load this into the myapp.db database with the following command:
myapp.db
$ sqlite3 myapp.db < myapp02.sql
Although we could manually edit the DBIC schema information to include the new tables added in the previous step, let's use the create=static option on the DBIC model helper to do most of the work for us:
create=static
$ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=static dbi:SQLite:myapp.db $ ls lib/MyApp/Schema Authors.pm BookAuthors.pm Books.pm Roles.pm UserRoles.pm Users.pm
Notice how the helper has added three new table-specific result source files to the lib/MyApp/Schema/MyApp directory. And, more importantly, even if there were changes to the existing result source files, those changes would have only been written above the # DO NOT MODIFY THIS OR ANYTHING ABOVE! comment and your hand-editted enhancements would have been preserved.
lib/MyApp/Schema/MyApp
# DO NOT MODIFY THIS OR ANYTHING ABOVE!
Speaking of "hand-editted enhancements," we should now add relationship information to the three new result source files. Edit each of these files and add the following information between the # DO NOT MODIFY THIS OR ANYTHING ABOVE! comment and the closing 1;:
1;
lib/MyApp/Schema/Users.pm:
lib/MyApp/Schema/Users.pm
# # Set relationships: # # has_many(): # args: # 1) Name of relationship, DBIC will create accessor with this name # 2) Name of the model class referenced by this relationship # 3) Column name in *foreign* table __PACKAGE__->has_many(map_user_role => 'MyApp::Schema::UserRoles', 'user_id'); # many_to_many(): # args: # 1) Name of relationship, DBIC will create accessor with this name # 2) Name of has_many() relationship this many_to_many() is shortcut for # 3) Name of belongs_to() relationship in model class of has_many() above # You must already have the has_many() defined to use a many_to_many(). __PACKAGE__->many_to_many(roles => 'map_user_role', 'role');
lib/MyApp/Schema/Roles.pm:
lib/MyApp/Schema/Roles.pm
# # Set relationships: # # has_many(): # args: # 1) Name of relationship, DBIC will create accessor with this name # 2) Name of the model class referenced by this relationship # 3) Column name in *foreign* table __PACKAGE__->has_many(map_user_role => 'MyApp::Schema::UserRoles', 'role_id');
lib/MyApp/Schema/UserRoles.pm:
lib/MyApp/Schema/UserRoles.pm
# # Set relationships: # # belongs_to(): # args: # 1) Name of relationship, DBIC will create accessor with this name # 2) Name of the model class referenced by this relationship # 3) Column name in *this* table __PACKAGE__->belongs_to(user => 'MyApp::Schema::Users', 'user_id'); # belongs_to(): # args: # 1) Name of relationship, DBIC will create accessor with this name # 2) Name of the model class referenced by this relationship # 3) Column name in *this* table __PACKAGE__->belongs_to(role => 'MyApp::Schema::Roles', 'role_id');
The code for these three sets of updates is obviously very similar to the edits we made to the Books, Authors, and BookAuthors classes created in Part 3.
Books
Authors
BookAuthors
Note that we do not need to make any change to the lib/MyApp/Schema.pm schema file. It simple tells DBIC to load all of the result source files it finds in below the lib/MyApp/Schema directory, so it will automatically pick up our new table information.
lib/MyApp/Schema.pm
lib/MyApp/Schema
We aren't ready to try out the authentication just yet; we only want to do a quick check to be sure our model loads correctly. Press Ctrl-C to kill the previous server instance (if it's still running) and restart it:
Ctrl-C
$ script/myapp_server.pl
Look for the three new model objects in the startup debug output:
... .-------------------------------------------------------------------+----------. | Class | Type | +-------------------------------------------------------------------+----------+ | MyApp::Controller::Books | instance | | MyApp::Controller::Root | instance | | MyApp::Model::DB | instance | | MyApp::Model::DB::Author | class | | MyApp::Model::DB::Books | class | | MyApp::Model::DB::BookAuthors | class | | MyApp::Model::DB::Roles | class | | MyApp::Model::DB::Users | class | | MyApp::Model::DB::UserRoles | class | | MyApp::View::TT | instance | '-------------------------------------------------------------------+----------' ...
Again, notice that your "result source" classes have been "re-loaded" by Catalyst under MyApp::Model.
MyApp::Model
Edit lib/MyApp.pm and update it as follows (everything below StackTrace is new):
lib/MyApp.pm
StackTrace
use Catalyst qw/ -Debug ConfigLoader Static::Simple StackTrace Authentication Session Session::Store::FastMmap Session::State::Cookie /;
The Authentication plugin supports Authentication while the Session plugins are required to maintain state across multiple HTTP requests.
Session
Note that the only required Authentication class is the main one. This is a change that occurred in version 0.09999_01 of the Authentication plugin. You do not need to specify a particular Authentication::Store or Authentication::Credential plugin. Instead, indicate the Store and Credential you want to use in your application configuration (see below).
Note that there are several options for Session::Store (Session::Store::FastMmap is generally a good choice if you are on Unix; try Session::Store::File if you are on Win32) -- consult Session::Store and its subclasses for additional information and options (for example to use a database- backed session store).
Although __PACKAGE__->config(name => 'value'); is still supported, newer Catalyst applications tend to place all configuration information in myapp.conf and automatically load this information into MyApp->config using the ConfigLoader plugin.
__PACKAGE__->config(name => 'value');
myapp.conf
MyApp->config
First, as noted in Part 3 of the tutorial, Catalyst has recently switched from a default config file format of YAML to Config::General (an apache-like format). In case you are using a version of Catalyst earlier than v5.7014, delete the myapp.yml file and simply follow the directions below to create a new myapp.conf file.
Config::General
myapp.yml
Here, we need to load several parameters that tell Catalyst::Plugin::Authentication where to locate information in your database. To do this, edit the myapp.conf file and update it to match:
name MyApp <authentication> default_realm dbic <realms> <dbic> <credential> # Note this first definition would be the same as setting # __PACKAGE__->config->{authentication}->{realms}->{dbic} # ->{credential} = 'Password' in lib/MyApp.pm # # Specify that we are going to do password-based auth class Password # This is the name of the field in the users table with the # password stored in it password_field password # We are using an unencrypted password now password_type clear </credential> <store> # Use DBIC to retrieve username, password & role information class DBIx::Class # This is the model object created by Catalyst::Model::DBIC # from your schema (you created 'MyApp::Schema::User' but as # the Catalyst startup debug messages show, it was loaded as # 'MyApp::Model::DB::Users'). # NOTE: Omit 'MyApp::Model' here just as you would when using # '$c->model("DB::Users)' user_class DB::Users # This is the name of the field in your 'users' table that # contains the user's name id_field username </store> </dbic> </realms> </authentication>
Inline comments in the code above explain how each field is being used.
Note that you can use many other config file formats with catalyst. See Catalyst::Plugin::ConfigLoader for details.
Use the Catalyst create script to create two stub controller files:
$ script/myapp_create.pl controller Login $ script/myapp_create.pl controller Logout
NOTE: You could easily use a single controller here. For example, you could have a User controller with both login and logout actions. Remember, Catalyst is designed to be very flexible, and leaves such matters up to you, the designer and programmer.
User
login
logout
Then open lib/MyApp/Controller/Login.pm, locate the sub index :Path :Args(0) method (or sub index : Private if you are using an older version of Catalyst) that was automatically inserted by the helpers when we created the Login controller above, and delete this line:
lib/MyApp/Controller/Login.pm
sub index :Path :Args(0)
sub index : Private
$c->response->body('Matched MyApp::Controller::Login in Login.');
Then update it to match:
=head2 index Login logic =cut sub index :Path :Args(0) { my ($self, $c) = @_; # Get the username and password from form my $username = $c->request->params->{username} || ""; my $password = $c->request->params->{password} || ""; # If the username and password values were found in form if ($username && $password) { # Attempt to log the user in if ($c->authenticate({ username => $username, password => $password} )) { # If successful, then let them use the application $c->response->redirect($c->uri_for('/books/list')); return; } else { # Set an error message $c->stash->{error_msg} = "Bad username or password."; } } # If either of above don't work out, send to the login page $c->stash->{template} = 'login.tt2'; }
This controller fetches the username and password values from the login form and attempts to authenticate the user. If successful, it redirects the user to the book list page. If the login fails, the user will stay at the login page but receive an error message. If the username and password values are not present in the form, the user will be taken to the empty login form.
username
password
Note that we could have used something like sub default :Path, however partly for historical reasons, and partly for code clarity it is generally recommended only to use default in MyApp::Controller::Root, and then mainly to generate the 404 not found page for the application.
sub default :Path
default
MyApp::Controller::Root
Instead, we are using sub base :Path :Args(0) {...} here to specifically match the URL /login. Path actions (aka, "literal actions") create URI matches relative to the namespace of the controller where they are defined. Although Path supports arguments that allow relative and absolute paths to be defined, here we use an empty Path definition to match on just the name of the controller itself. The method name, index, is arbitrary. We make the match even more specific with the :Args(0) action modifier -- this forces the match on only /login, not /login/somethingelse.
sub base :Path :Args(0) {...}
/login
Path
index
:Args(0)
/login/somethingelse
Next, update the corresponding method in lib/MyApp/Controller/Logout.pm to match:
lib/MyApp/Controller/Logout.pm
=head2 index Logout logic =cut sub index :Path :Args(0) { my ($self, $c) = @_; # Clear the user's state $c->logout; # Send the user to the starting point $c->response->redirect($c->uri_for('/')); }
As with the login controller, be sure to delete the $c->response->body('Matched MyApp::Controller::Logout in Logout.'); line of the sub index.
$c->response->body('Matched MyApp::Controller::Logout in Logout.');
sub index
Create a login form by opening root/src/login.tt2 and inserting:
root/src/login.tt2
[% META title = 'Login' %] <!-- Login form --> <form method="post" action=" [% Catalyst.uri_for('/login') %] "> <table> <tr> <td>Username:</td> <td><input type="text" name="username" size="40" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" size="40" /></td> </tr> <tr> <td colspan="2"><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form>
We need something that provides enforcement for the authentication mechanism -- a global mechanism that prevents users who have not passed authentication from reaching any pages except the login page. This is generally done via an auto action/method (prior to Catalyst v5.66, this sort of thing would go in MyApp.pm, but starting in v5.66, the preferred location is lib/MyApp/Controller/Root.pm).
auto
MyApp.pm
lib/MyApp/Controller/Root.pm
Edit the existing lib/MyApp/Controller/Root.pm class file and insert the following method:
=head2 auto Check if there is a user and, if not, forward to login page =cut # Note that 'auto' runs after 'begin' but before your actions and that # 'auto' "chain" (all from application path to most specific class are run) # See the 'Actions' section of 'Catalyst::Manual::Intro' for more info. sub auto : Private { my ($self, $c) = @_; # Allow unauthenticated users to reach the login page. This # allows anauthenticated users to reach any action in the Login # controller. To lock it down to a single action, we could use: # if ($c->action eq $c->controller('Login')->action_for('index')) # to only allow unauthenticated access to the C<index> action we # added above. if ($c->controller eq $c->controller('Login')) { return 1; } # If a user doesn't exist, force login if (!$c->user_exists) { # Dump a log message to the development server debug output $c->log->debug('***Root::auto User not found, forwarding to /login'); # Redirect the user to the login page $c->response->redirect($c->uri_for('/login')); # Return 0 to cancel 'post-auto' processing and prevent use of application return 0; } # User found, so return 1 to continue with processing after this 'auto' return 1; }
Note: Catalyst provides a number of different types of actions, such as Local, Regex, Private and the new Path. You should refer to Catalyst::Manual::Intro for a more detailed explanation, but the following bullet points provide a quick introduction:
Local
Regex
Private
The majority of application have traditionally use Local actions for items that respond to user requests and Private actions for those that do not directly respond to user input.
Newer Catalyst applications tend to use Path actions and the Args attribute because of their power and flexibility. You can specify the path to match relative to the namespace of the current module as an argument to Path. For example Path('list') in lib/MyApp/Controller/Books.pm would match on the URL http://localhost:3000/books/list but Path('/list') would match on http://localhost:3000/list.
Args
Path('list')
lib/MyApp/Controller/Books.pm
http://localhost:3000/books/list
Path('/list')
http://localhost:3000/list
Automatic "chaining" of actions by the dispatcher is a powerful feature that allows multiple methods to handle a single URL. See Catalyst::DispatchType::Chained for more information on chained actions.
There are five types of build-in Private actions: begin, end, default, index, and auto.
begin
end
With begin, end, default, index private actions, only the most specific action of each type will be called. For example, if you define a begin action in your controller it will override a begin action in your application/root controller -- only the action in your controller will be called.
Unlike the other actions where only a single method is called for each request, every auto action along the chain of namespaces will be called. Each auto action will be called from the application/root controller down through the most specific class.
By placing the authentication enforcement code inside the auto method of lib/MyApp/Controller/Root.pm (or lib/MyApp.pm), it will be called for every request that is received by the entire application.
Let's say you want to provide some information on the login page that changes depending on whether the user has authenticated yet. To do this, open root/src/login.tt2 in your editor and add the following lines to the bottom of the file:
<p> [% # This code illustrates how certain parts of the TT # template will only be shown to users who have logged in %] [% IF Catalyst.user_exists %] Please Note: You are already logged in as '[% Catalyst.user.username %]'. You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here. [% ELSE %] You need to log in to use this application. [% END %] [%# Note that this whole block is a comment because the "#" appears immediate after the "[%" (with no spaces in between). Although it can be a handy way to temporarily "comment out" a whole block of TT code, it's probably a little too subtle for use in "normal" comments. %] </p>
Although most of the code is comments, the middle few lines provide a "you are already logged in" reminder if the user returns to the login page after they have already authenticated. For users who have not yet authenticated, a "You need to log in..." message is displayed (note the use of an IF-THEN-ELSE construct in TT).
Press Ctrl-C to kill the previous server instance (if it's still running) and restart it:
IMPORTANT NOTE: If you are having issues with authentication on Internet Explorer, be sure to check the system clocks on both your server and client machines. Internet Explorer is very picky about timestamps for cookies. Note that you can quickly sync an Ubuntu system with the following command:
sudo ntpdate ntp.ubuntu.com
Now trying going to http://localhost:3000/books/list and you should be redirected to the login page, hitting Shift+Reload if necessary (the "You are already logged in" message should not appear -- if it does, click the logout button and try again). Note the ***Root::auto User not found... debug message in the development server output. Enter username test01 and password mypass, and you should be taken to the Book List page.
***Root::auto User not found...
test01
mypass
Open root/src/books/list.tt2 and add the following lines to the bottom (below the closing </table> tag):
root/src/books/list.tt2
<p> <a href="[% Catalyst.uri_for('/login') %]">Login</a> <a href="[% Catalyst.uri_for('form_create') %]">Create</a> </p>
Reload your browser and you should now see a "Login" and "Create" links at the bottom of the page (as mentioned earlier, you can update template files without reloading the development server). Click the first link to return to the login page. This time you should see the "You are already logged in" message.
Finally, click the You can logout here link on the /login page. You should stay at the login page, but the message should change to "You need to log in to use this application."
You can logout here
In this section we increase the security of our system by converting from cleartext passwords to SHA-1 password hashes.
Note: This section is optional. You can skip it and the rest of the tutorial will function normally.
Note that even with the techniques shown in this section, the browser still transmits the passwords in cleartext to your application. We are just avoiding the storage of cleartext passwords in the database by using a SHA-1 hash. If you are concerned about cleartext passwords between the browser and your application, consider using SSL/TLS, made easy with the Catalyst plugin Catalyst::Plugin:RequireSSL.
Catalyst uses the Digest module to support a variety of hashing algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm). First, we should compute the SHA-1 hash for the "mypass" password we are using. The following command-line Perl script provides a "quick and dirty" way to do this:
Digest
$ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"' e727d1464ae12436e899a726da5b2f11d8381b26 $
Note: If you are following along in Ubuntu, you will need to install Digest::SHA with the following command to run the example code above:
Digest::SHA
sudo apt-get install libdigest-sha-perl
Note: You should probably modify this code for production use to not read the password from the command line. By having the script prompt for the cleartext password, it avoids having the password linger in forms such as your .bash_history files (assuming you are using BASH as your shell). An example of such a script can be found in Appendix 3.
.bash_history
Next, we need to change the password column of our users table to store this hash value vs. the existing cleartext password. Open myapp03.sql in your editor and enter:
users
myapp03.sql
-- -- Convert passwords to SHA-1 hashes -- UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1; UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2; UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
Then use the following command to update the SQLite database:
$ sqlite3 myapp.db < myapp03.sql
Note: We are using SHA-1 hashes here, but many other hashing algorithms are supported. See Digest for more information.
Catalyst::Plugin::Authentication::Store::DBIC
Edit myapp.conf and update it to match (the password_type and password_hash_type are new, everything else is the same):
password_type
password_hash_type
name MyApp <authentication> default_realm dbic <realms> <dbic> <credential> # Note this first definition would be the same as setting # __PACKAGE__->config->{authentication}->{realms}->{dbic} # ->{credential} = 'Password' in lib/MyApp.pm # # Specify that we are going to do password-based auth class Password # This is the name of the field in the users table with the # password stored in it password_field password # Switch to more secure hashed passwords password_type hashed # Use the SHA-1 hashing algorithm password_hash_type SHA-1 </credential> <store> # Use DBIC to retrieve username, password & role information class DBIx::Class # This is the model object created by Catalyst::Model::DBIC # from your schema (you created 'MyApp::Schema::User' but as # the Catalyst startup debug messages show, it was loaded as # 'MyApp::Model::DB::Users'). # NOTE: Omit 'MyApp::Model' here just as you would when using # '$c->model("DB::Users)' user_class DB::Users # This is the name of the field in your 'users' table that # contains the user's name id_field username </store> </dbic> </realms> </authentication>
You should now be able to go to http://localhost:3000/books/list and login as before. When done, click the "Logout" link on the login page (or point your browser at http://localhost:3000/logout).
As discussed in Part 3 of the tutorial, flash allows you to set variables in a way that is very similar to stash, but it will remain set across multiple requests. Once the value is read, it is cleared (unless reset). Although flash has nothing to do with authentication, it does leverage the same session plugins. Now that those plugins are enabled, let's go back and improve the "delete and redirect with query parameters" code seen at the end of the Basic CRUD part of the tutorial.
flash
stash
First, open lib/MyApp/Controller/Books.pm and modify sub delete to match the following (everything after the model search line of code has changed):
sub delete
=head2 delete Delete a book =cut sub delete : Local { # $id = primary key of book to delete my ($self, $c, $id) = @_; # Search for the book and then delete it $c->model('DB::Books')->search({id => $id})->delete_all; # Use 'flash' to save information across requests until it's read $c->flash->{status_msg} = "Book deleted"; # Redirect the user back to the list page $c->response->redirect($c->uri_for('/books/list')); }
Next, open root/lib/site/layout and update the TT code to pull from flash vs. the status_msg query parameter:
root/lib/site/layout
status_msg
<div id="header">[% PROCESS site/header %]</div> <div id="content"> <span class="message">[% status_msg || Catalyst.flash.status_msg %]</span> <span class="error">[% error_msg %]</span> [% content %] </div> <div id="footer">[% PROCESS site/footer %]</div>
Restart the development server and point your browser to http://localhost:3000/books/url_create/Test/1/4 to create an extra several books. Click the "Return to list" link and delete one of the "Test" books you just added. The flash mechanism should retain our "Book deleted" status message across the redirect.
NOTE: While flash will save information across multiple requests, it does get cleared the first time it is read. In general, this is exactly what you want -- the flash message will get displayed on the next screen where it's appropriate, but it won't "keep showing up" after that first time (unless you reset it). Please refer to Catalyst::Plugin::Session for additional information.
Although the a use of flash above is certainly an improvement over the status_msg we employed in Part 4 of the tutorial, the status_msg || Catalyst.flash.status_msg statement is a little ugly. A nice alternative is to use the flash_to_stash feature that automatically copies the content of flash to stash. This makes your code controller and template code work regardless of where it was directly access, a forward, or a redirect. To enable flash_to_stash, you can either set the value in lib/MyApp.pm by changing the default __PACKAGE__->config setting to something like:
status_msg || Catalyst.flash.status_msg
flash_to_stash
__PACKAGE__->config
__PACKAGE__->config( name => 'MyApp', session => {flash_to_stash => 1} );
or add the following to myapp.conf:
<session> flash_to_stash 1 </session>
The __PACKAGE__->config option is probably preferable here since it's not something you will want to change at runtime without it possibly breaking some of your code.
Then edit root/lib/site/layout and change the status_msg line to look like the following:
<span class="message">[% status_msg %]</span>
Restart the development server and go to http://localhost:3000/books/list in your browser. Delete another of the "Test" books you added in the previous step. Flash should still maintain the status message across the redirect even though you are no longer explicitly accessing Catalyst.flash.
Catalyst.flash
Kennedy Clark, hkclark@gmail.com
hkclark@gmail.com
Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.
Copyright 2006-2008, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).
To install Catalyst::Manual, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Catalyst::Manual
CPAN shell
perl -MCPAN -e shell install Catalyst::Manual
For more information on module installation, please visit the detailed CPAN module installation guide.